answer
stringlengths
17
10.2M
// of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // all copies or substantial portions of the Software. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // File created: 2011-06-14 13:38:57 package fi.tkk.ics.hadoop.bam.cli.plugins; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import org.apache.hadoop.fs.Path; import net.sf.samtools.SAMFormatException; import net.sf.samtools.SAMFileReader.ValidationStringency; import fi.tkk.ics.hadoop.bam.custom.jargs.gnu.CmdLineParser; import fi.tkk.ics.hadoop.bam.custom.samtools.SAMFileHeader; import fi.tkk.ics.hadoop.bam.custom.samtools.SAMFileReader; import fi.tkk.ics.hadoop.bam.custom.samtools.SAMRecord; import fi.tkk.ics.hadoop.bam.custom.samtools.SAMRecordIterator; import fi.tkk.ics.hadoop.bam.custom.samtools.SAMSequenceRecord; import fi.tkk.ics.hadoop.bam.custom.samtools.SAMTextWriter; import fi.tkk.ics.hadoop.bam.cli.CLIPlugin; import fi.tkk.ics.hadoop.bam.util.Pair; import fi.tkk.ics.hadoop.bam.util.WrapSeekable; import static fi.tkk.ics.hadoop.bam.custom.jargs.gnu.CmdLineParser.Option.*; public final class View extends CLIPlugin { private static final List<Pair<CmdLineParser.Option, String>> optionDescs = new ArrayList<Pair<CmdLineParser.Option, String>>(); private static final CmdLineParser.Option headerOnlyOpt = new BooleanOption('H', "header-only"); public View() { super("view", "BAM viewing", "1.0", "PATH [regions...]", optionDescs, "Reads the BAM file in PATH and, by default, outputs it in SAM "+ "format. If any number of regions is given, only the alignments "+ "overlapping with those regions are output. Then an index is also "+ "required, expected at PATH.bai by default."+ "\n\n"+ "Regions can be given as only reference sequence names or indices "+ "like 'chr1', or with position ranges as well like 'chr1:100-200'. "+ "These coordinates are 1-based, with 0 representing the start or "+ "end of the sequence."); } static { optionDescs.add(new Pair<CmdLineParser.Option, String>( headerOnlyOpt, "print header only")); } @Override protected int run(CmdLineParser parser) { final List<String> args = parser.getRemainingArgs(); if (args.isEmpty()) { System.err.println("view :: PATH not given."); return 3; } final String path = args.get(0); final List<String> regions = args.subList(1, args.size()); final boolean headerOnly = parser.getBoolean(headerOnlyOpt); final SAMFileReader reader; try { final Path p = new Path(path); reader = new SAMFileReader( WrapSeekable.openPath(getConf(), p), WrapSeekable.openPath(getConf(), p.suffix(".bai")), false); } catch (Exception e) { System.err.printf("view :: Could not open '%s': %s\n", path, e.getMessage()); return 4; } reader.setValidationStringency(ValidationStringency.SILENT); final SAMTextWriter writer = new SAMTextWriter(System.out); final SAMFileHeader header; try { header = reader.getFileHeader(); } catch (SAMFormatException e) { System.err.printf("view :: Could not parse '%s': %s\n", path, e.getMessage()); return 4; } if (regions.isEmpty() || headerOnly) { writer.setSortOrder(header.getSortOrder(), true); writer.setHeader(header); if (!headerOnly) if (!writeIterator(writer, reader.iterator(), path)) return 4; writer.close(); return 0; } if (!reader.hasIndex()) { System.err.println( "view :: Cannot output regions from BAM file lacking an index"); return 4; } reader.enableIndexCaching(true); boolean errors = false; for (final String region : regions) { final StringTokenizer st = new StringTokenizer(region, ":-"); final String refStr = st.nextToken(); final int beg, end; if (st.hasMoreTokens()) { beg = parseCoordinate(st.nextToken()); end = st.hasMoreTokens() ? parseCoordinate(st.nextToken()) : -1; if (beg < 0 || end < 0) { errors = true; continue; } if (end < beg) { System.err.printf( "view :: Invalid range, cannot end before start: '%d-%d'\n", beg, end); errors = true; continue; } } else beg = end = 0; SAMSequenceRecord ref = header.getSequence(refStr); if (ref == null) try { ref = header.getSequence(Integer.parseInt(refStr)); } catch (NumberFormatException e) {} if (ref == null) { System.err.printf( "view :: Not a valid sequence name or index: '%s'\n", refStr); errors = true; continue; } final SAMRecordIterator it = reader.queryOverlapping(ref.getSequenceName(), beg, end); if (!writeIterator(writer, it, path)) return 4; } writer.close(); return errors ? 5 : 0; } private boolean writeIterator( SAMTextWriter writer, SAMRecordIterator it, String path) { try { while (it.hasNext()) writer.writeAlignment(it.next()); return true; } catch (SAMFormatException e) { writer.close(); System.err.printf("view :: Could not parse '%s': %s\n", path, e.getMessage()); return false; } } private int parseCoordinate(String s) { int c; try { c = Integer.parseInt(s); } catch (NumberFormatException e) { c = -1; } if (c < 0) System.err.printf("view :: Not a valid coordinate: '%s'\n", s); return c; } }
package com.annimon.stream; import com.annimon.stream.function.DoubleConsumer; import com.annimon.stream.function.DoubleFunction; import com.annimon.stream.function.DoublePredicate; import com.annimon.stream.function.DoubleSupplier; import com.annimon.stream.function.DoubleToIntFunction; import com.annimon.stream.function.DoubleUnaryOperator; import com.annimon.stream.function.Supplier; import java.util.NoSuchElementException; /** * A container object which may or may not contain a {@code double} value. * * @since 1.1.4 * @see Optional */ @SuppressWarnings("WeakerAccess") public final class OptionalDouble { private static final OptionalDouble EMPTY = new OptionalDouble(); /** * Returns an empty {@code OptionalDouble} instance. * * @return an empty {@code OptionalDouble} */ public static OptionalDouble empty() { return EMPTY; } /** * Returns an {@code OptionalDouble} with the specified value present. * * @param value the value to be present * @return an {@code OptionalDouble} with the value present */ public static OptionalDouble of(double value) { return new OptionalDouble(value); } private final boolean isPresent; private final double value; private OptionalDouble() { this.isPresent = false; this.value = 0; } private OptionalDouble(double value) { this.isPresent = true; this.value = value; } /** * Returns an inner value if present, otherwise throws {@code NoSuchElementException}. * * @return the inner value of this {@code OptionalDouble} * @throws NoSuchElementException if there is no value present * @see OptionalDouble#isPresent() */ public double getAsDouble() { if (!isPresent) { throw new NoSuchElementException("No value present"); } return value; } /** * Checks value present. * * @return {@code true} if a value present, {@code false} otherwise */ public boolean isPresent() { return isPresent; } /** * Invokes consumer function with value if present, otherwise does nothing. * * @param consumer the consumer function to be executed if a value is present * @throws NullPointerException if value is present and {@code consumer} is null */ public void ifPresent(DoubleConsumer consumer) { if (isPresent) { consumer.accept(value); } } /** * If a value is present, performs the given action with the value, * otherwise performs the empty-based action. * * @param consumer the consumer function to be executed, if a value is present * @param emptyAction the empty-based action to be performed, if no value is present * @throws NullPointerException if a value is present and the given consumer function is null, * or no value is present and the given empty-based action is null. */ public void ifPresentOrElse(DoubleConsumer consumer, Runnable emptyAction) { if (isPresent) { consumer.accept(value); } else { emptyAction.run(); } } /** * Invokes consumer function with the value if present. * This method same as {@code ifPresent}, but does not breaks chaining * * @param consumer consumer function * @return this {@code OptionalDouble} * @see #ifPresent(com.annimon.stream.function.DoubleConsumer) */ public OptionalDouble executeIfPresent(DoubleConsumer consumer) { ifPresent(consumer); return this; } /** * Invokes action function if value is absent. * * @param action action that invokes if value absent * @return this {@code OptionalDouble} */ public OptionalDouble executeIfAbsent(Runnable action) { if (!isPresent()) { action.run(); } return this; } /** * Performs filtering on inner value if present. * * @param predicate a predicate function * @return this {@code OptionalDouble} if the value is present and matches predicate, * otherwise an empty {@code OptionalDouble} */ public OptionalDouble filter(DoublePredicate predicate) { if (!isPresent()) return this; return predicate.test(value) ? this : OptionalDouble.empty(); } /** * Invokes the given mapping function on inner value if present. * * @param mapper mapping function * @return an {@code OptionalDouble} with transformed value if present, * otherwise an empty {@code OptionalDouble} * @throws NullPointerException if value is present and * {@code mapper} is {@code null} */ public OptionalDouble map(DoubleUnaryOperator mapper) { if (!isPresent()) { return empty(); } Objects.requireNonNull(mapper); return OptionalDouble.of(mapper.applyAsDouble(value)); } /** * Invokes the given mapping function on inner value if present. * * @param <U> the type of result value * @param mapper mapping function * @return an {@code Optional} with transformed value if present, * otherwise an empty {@code Optional} * @throws NullPointerException if value is present and * {@code mapper} is {@code null} */ public <U> Optional<U> mapToObj(DoubleFunction<U> mapper) { if (!isPresent()) { return Optional.empty(); } Objects.requireNonNull(mapper); return Optional.ofNullable(mapper.apply(value)); } /** * Invokes the given mapping function on inner value if present. * * @param mapper mapping function * @return an {@code OptionalInt} with transformed value if present, * otherwise an empty {@code OptionalInt} * @throws NullPointerException if value is present and * {@code mapper} is {@code null} */ public OptionalInt mapToInt(DoubleToIntFunction mapper) { if (!isPresent()) { return OptionalInt.empty(); } Objects.requireNonNull(mapper); return OptionalInt.of(mapper.applyAsInt(value)); } /** * Wraps a value into {@code DoubleStream} if present, * otherwise returns an empty {@code DoubleStream}. * * @return the optional value as an {@code DoubleStream} */ public DoubleStream stream() { if (!isPresent()) { return DoubleStream.empty(); } return DoubleStream.of(value); } /** * Returns current {@code OptionalDouble} if value is present, otherwise * returns an {@code OptionalDouble} produced by supplier function. * * @param supplier supplier function that produces an {@code OptionalDouble} to be returned * @return this {@code OptionalDouble} if value is present, otherwise * an {@code OptionalDouble} produced by supplier function * @throws NullPointerException if value is not present and * {@code supplier} or value produced by it is {@code null} */ public OptionalDouble or(Supplier<OptionalDouble> supplier) { if (isPresent()) return this; Objects.requireNonNull(supplier); return Objects.requireNonNull(supplier.get()); } /** * Returns inner value if present, otherwise returns {@code other}. * * @param other the value to be returned if there is no value present * @return the value, if present, otherwise {@code other} */ public double orElse(double other) { return isPresent ? value : other; } /** * Returns the value if present, otherwise returns value produced by supplier function. * * @param other supplier function that produces value if inner value is not present * @return the value if present otherwise the result of {@code other.getAsDouble()} * @throws NullPointerException if value is not present and {@code other} is null */ public double orElseGet(DoubleSupplier other) { return isPresent ? value : other.getAsDouble(); } /** * Returns the value if present, otherwise throws an exception provided by supplier function. * * @param <X> the type of exception to be thrown * @param exceptionSupplier supplier function that produces an exception to be thrown * @return inner value if present * @throws X if inner value is not present */ public <X extends Throwable> double orElseThrow(Supplier<X> exceptionSupplier) throws X { if (isPresent) { return value; } else { throw exceptionSupplier.get(); } } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof OptionalDouble)) { return false; } OptionalDouble other = (OptionalDouble) obj; return (isPresent && other.isPresent) ? Double.compare(value, other.value) == 0 : isPresent == other.isPresent; } @Override public int hashCode() { return isPresent ? Objects.hashCode(value) : 0; } @Override public String toString() { return isPresent ? String.format("OptionalDouble[%s]", value) : "OptionalDouble.empty"; } }
package cn.cerc.mis.core; import java.io.Serializable; import javax.servlet.http.HttpServletRequest; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import org.springframework.web.context.WebApplicationContext; import cn.cerc.core.Utils; import cn.cerc.mis.language.LanguageType; import cn.cerc.mis.other.BufferType; import cn.cerc.mis.other.MemoryBuffer; import lombok.extern.slf4j.Slf4j; /** * // TODO: 2019/12/7 AppClient */ @Slf4j @Component @Scope(WebApplicationContext.SCOPE_SESSION) public class ClientDevice implements IClient, Serializable { private static final long serialVersionUID = -3593077761901636920L; public static final String APP_CLIENT_ID = "CLIENTID"; public static final String APP_DEVICE_TYPE = "device"; public static final String APP_DEVICE_PHONE = "phone"; public static final String APP_DEVICE_ANDROID = "android"; public static final String APP_DEVICE_IPHONE = "iphone"; public static final String APP_DEVICE_WEIXIN = "weixin"; public static final String APP_DEVICE_PAD = "pad"; public static final String APP_DEVICE_PC = "pc"; public static final String APP_DEVICE_EE = "ee"; private String token; // application session id; private String deviceId; // device id private String device; // phone/pad/ee/pc private String languageId; // device language: cn/en private HttpServletRequest request; public ClientDevice() { super(); } private String getValue(MemoryBuffer buff, String key, String def) { String result = def; String tmp = buff.getString(key); // def if (tmp != null && !"".equals(tmp)) { if (def == null || "".equals(def)) { result = tmp; } } // def if (def != null && !"".equals(def)) { if (tmp == null || !tmp.equals(def)) { buff.setField(key, def); } } return result; } @Override public String getId() { return this.deviceId == null ? RequestData.WEBCLIENT : this.deviceId; } public void setId(String value) { this.deviceId = value; request.setAttribute(APP_CLIENT_ID, this.deviceId == null ? "" : this.deviceId); request.getSession().setAttribute(APP_CLIENT_ID, value); if (value != null && value.length() == 28) { setDevice(APP_DEVICE_PHONE); } if (token != null && this.deviceId != null && !"".equals(this.deviceId)) { try (MemoryBuffer buff = new MemoryBuffer(BufferType.getDeviceInfo, token)) { getValue(buff, APP_CLIENT_ID, this.deviceId); } } } /** * pc * * @return device */ @Override public String getDevice() { return this.device == null ? APP_DEVICE_PC : device; } @Override public void setDevice(String device) { if (device == null || "".equals(device)) { return; } this.device = device; // request request.setAttribute(APP_DEVICE_TYPE, device == null ? "" : device); request.getSession().setAttribute(APP_DEVICE_TYPE, device); if (token != null) { try (MemoryBuffer buff = new MemoryBuffer(BufferType.getDeviceInfo, token)) { getValue(buff, APP_DEVICE_TYPE, device); } } return; } @Override public String getLanguage() { return languageId == null ? LanguageType.zh_CN : languageId; } public String getToken() { return "".equals(token) ? null : token; } /** * token * <p> * TODO: 2019/12/7 */ public void clear() { if (Utils.isNotEmpty(token)) { try (MemoryBuffer buff = new MemoryBuffer(BufferType.getDeviceInfo, token)) { buff.clear(); } try (MemoryBuffer buff = new MemoryBuffer(BufferType.getSessionBase, token)) { buff.clear(); } } this.token = null; } @Override public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append("token:").append(this.token).append(", "); buffer.append("deviceId:").append(this.deviceId).append(", "); buffer.append("deviceType:").append(this.device); return buffer.toString(); } @Override public boolean isPhone() { return APP_DEVICE_PHONE.equals(getDevice()) || APP_DEVICE_ANDROID.equals(getDevice()) || APP_DEVICE_IPHONE.equals(getDevice()) || APP_DEVICE_WEIXIN.equals(getDevice()); } public boolean isNotPhone() { return !isPhone(); } public HttpServletRequest getRequest() { return this.request; } @Override public void setRequest(HttpServletRequest request) { this.request = request; this.device = request.getParameter(APP_DEVICE_TYPE); if (this.device == null || "".equals(this.device)) { this.device = (String) request.getSession().getAttribute(APP_DEVICE_TYPE); } if (this.device != null && !"".equals(this.device)) { request.getSession().setAttribute(APP_DEVICE_TYPE, this.device); } request.setAttribute(APP_DEVICE_TYPE, this.device == null ? "" : this.device); // device_id this.deviceId = request.getParameter(APP_CLIENT_ID); if (this.deviceId == null || "".equals(this.deviceId)) { this.deviceId = (String) request.getSession().getAttribute(APP_CLIENT_ID); } request.setAttribute(APP_CLIENT_ID, this.deviceId); request.getSession().setAttribute(APP_CLIENT_ID, this.deviceId); this.languageId = request.getParameter(Application.deviceLanguage); if (this.languageId == null || "".equals(this.languageId)) { this.languageId = (String) request.getSession().getAttribute(Application.deviceLanguage); } request.setAttribute(Application.deviceLanguage, this.languageId); request.getSession().setAttribute(Application.deviceLanguage, this.languageId); // token String token = request.getParameter(RequestData.TOKEN);// token if (token == null || "".equals(token)) { token = (String) request.getSession().getAttribute(RequestData.TOKEN); // token } log.debug("sessionID 1: {}", request.getSession().getId()); // token setToken(token); } public void setToken(String value) { String token = Utils.isEmpty(value) ? null : value; if (token != null) { try (MemoryBuffer buff = new MemoryBuffer(BufferType.getDeviceInfo, token)) { this.deviceId = getValue(buff, APP_CLIENT_ID, this.deviceId); this.device = getValue(buff, APP_DEVICE_TYPE, this.device); } } else { if (this.token != null && !"".equals(this.token)) { MemoryBuffer.delete(BufferType.getDeviceInfo, this.token); } } log.debug("sessionID 2: {}", request.getSession().getId()); this.token = token; request.getSession().setAttribute(RequestData.TOKEN, this.token); request.setAttribute(RequestData.TOKEN, this.token == null ? "" : this.token); } }
package org.robovm.templater; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.net.URL; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.GZIPInputStream; import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; /** * The RoboVM {@code Templater} generates a new RoboVM project from a template. * * @author BlueRiver Interactive */ public class Templater { private static final String PACKAGE_FOLDER_PLACEHOLDER = "__packageInPathFormat__"; private static final String MAIN_CLASS_FILE_PLACEHOLDER = "__mainClass__"; private static final Set<String> SUBSTITUTED_PLACEHOLDER_FILES_EXTENSIONS = new HashSet<>(Arrays.asList("xml", "java")); private static final String DOLLAR_SYMBOL_PLACEHOLDER = Pattern.quote("${symbol_dollar}"); private static final String PACKAGE_PLACEHOLDER = Pattern.quote("package ${package};"); private static final String MAIN_CLASS_PLACEHOLDER = Pattern.quote("${mainClass}"); private static final String MAVEN_ARCHETYPE_SET_PLACEHOLDER = "#set\\(.*\\)\n"; private static final String ROBOVM_PROPERTIES_FILE = "robovm.properties"; private static final String ROBOVM_PROPERTIES_PACKAGE_PLACEHOLDER = Pattern.quote("${package}"); private static final String ROBOVM_PROPERTIES_MAIN_CLASS_PLACEHOLDER = Pattern.quote("${mainClass}"); private static final String ROBOVM_PROPERTIES_APP_NAME_PLACEHOLDER = Pattern.quote("${appName}"); private final String template; private final URL templateURL; private String mainClass; private String mainClassName; private String packageName; private String packageDirName; private String appName; private String appId; private String executable; public Templater(String template) { if (template == null) { throw new IllegalArgumentException("No template specified"); } this.template = template; templateURL = Templater.class.getResource("/templates/robovm-" + template + "-template.tar.gz"); if (templateURL == null) { throw new IllegalArgumentException(String.format("Template with name '%s' doesn't exist!", template)); } } /** * <p> * Sets the main class for the generated project. This is the only required * parameter. All other parameters will derive from this one if not * explicitly specified. * </p> * * Example: {@code com.company.app.MainClass} * * @param mainClass * @return */ public Templater mainClass(String mainClass) { this.mainClass = mainClass; return this; } /** * <p> * Sets the package name for the generated project. Will derive from the * main class name if not explicitly specified. * </p> * * Example: {@code com.company.app} * * @param packageName * @return */ public Templater packageName(String packageName) { this.packageName = packageName; return this; } /** * <p> * Sets the app name for the generated project. Will derive from the main * class name if not explicitly specified. * </p> * * Example: {@code MyApp} * * @param appName * @return */ public Templater appName(String appName) { this.appName = appName; return this; } /** * <p> * Sets the app id for the generated project. Will derive from the main * class name if not explicitly specified. * </p> * * Example: {@code com.company.app} * * @param appId * @return */ public Templater appId(String appId) { this.appId = appId; return this; } /** * <p> * Sets the executable name for the generated project. Will derive from the * main class name if not explicitly specified. * </p> * * Example: {@code MyApp} * * @param executable * @return */ public Templater executable(String executable) { this.executable = executable; return this; } public void buildProject(File projectRoot) { if (projectRoot == null) { throw new NullPointerException("projectRoot"); } if (mainClass == null) { throw new IllegalArgumentException("No main class specified"); } mainClassName = mainClass.substring(mainClass.lastIndexOf('.') + 1); if (executable == null || executable.length() == 0) { executable = mainClassName; } if (appName == null || appName.length() == 0) { appName = mainClassName; } if (packageName == null || packageName.length() == 0) { int index = mainClass.lastIndexOf('.'); if (index == -1) { packageName = ""; } else { packageName = mainClass.substring(0, index); } } packageDirName = packageName.replaceAll("\\.", File.separator); if (appId == null || appId.length() == 0) { appId = packageName; if (appId == null || appId.length() == 0) { appId = mainClassName; } } try { File targetFile = new File(projectRoot, FilenameUtils.getBaseName(templateURL.getPath())); FileUtils.copyURLToFile(templateURL, targetFile); extractArchive(targetFile, targetFile.getParentFile()); targetFile.delete(); } catch (IOException e) { throw new Error(e); } } private void extractArchive(File archive, File destDir) throws IOException { TarArchiveInputStream in = null; try { in = new TarArchiveInputStream(new GZIPInputStream(new FileInputStream(archive))); ArchiveEntry entry = null; while ((entry = in.getNextEntry()) != null) { File f = new File(destDir, substitutePlaceholdersInFileName(entry.getName())); if (entry.isDirectory()) { f.mkdirs(); } else { f.getParentFile().mkdirs(); OutputStream out = null; try { out = new FileOutputStream(f); IOUtils.copy(in, out); } finally { IOUtils.closeQuietly(out); } substitutePlaceholdersInFile(f); } } } finally { IOUtils.closeQuietly(in); } } private String substitutePlaceholdersInFileName(String fileName) { fileName = fileName.replaceAll(PACKAGE_FOLDER_PLACEHOLDER, packageDirName); fileName = fileName.replaceAll(MAIN_CLASS_FILE_PLACEHOLDER, mainClassName); return fileName; } private void substitutePlaceholdersInFile(File file) throws IOException { String extension = FilenameUtils.getExtension(file.getName()); if (ROBOVM_PROPERTIES_FILE.equals(file.getName())) { String content = FileUtils.readFileToString(file, "UTF-8"); // special case for app id content = content.replaceAll(Pattern.quote("app.id=${package}"), "app.id=" + appId); content = content.replaceAll(ROBOVM_PROPERTIES_APP_NAME_PLACEHOLDER, appName); content = content.replaceAll(ROBOVM_PROPERTIES_MAIN_CLASS_PLACEHOLDER, mainClassName); String propsPackageName = packageName == null || packageName.length() == 0 ? "" : packageName; content = content.replaceAll(ROBOVM_PROPERTIES_PACKAGE_PLACEHOLDER, propsPackageName); // need to fix up app.mainclass in case package name was empty content = content.replaceAll(Pattern.quote("mainclass=."), "mainclass="); FileUtils.writeStringToFile(file, content, "UTF-8"); } else if (SUBSTITUTED_PLACEHOLDER_FILES_EXTENSIONS.contains(extension)) { String content = FileUtils.readFileToString(file, "UTF-8"); content = content.replaceAll(MAVEN_ARCHETYPE_SET_PLACEHOLDER, ""); content = content.replaceAll(DOLLAR_SYMBOL_PLACEHOLDER, Matcher.quoteReplacement("$")); content = content.replaceAll(PACKAGE_PLACEHOLDER, getPackageNameReplacement(packageName)); content = content.replaceAll(MAIN_CLASS_PLACEHOLDER, mainClassName); FileUtils.writeStringToFile(file, content, "UTF-8"); } } private static String getPackageNameReplacement(String packageName) { if (packageName == null || packageName.length() == 0) { return ""; } return String.format("package %s;", packageName); } public static void main(String[] args) { if (args.length <= 1) { printHelpText(); return; } String template = null; String mainClass = null; String packageName = null; String appName = null; String appId = null; String executable = null; File projectRoot = null; for (int i = 0; i < args.length; i += 2) { if (isOption(args[i])) { if (args[i].length() <= 1) { throw new IllegalArgumentException("invalid option: " + args[i]); } char option = args[i].charAt(1); switch (option) { case 't': // template template = getOptionValue(args, i); break; case 'c': // main class mainClass = getOptionValue(args, i); break; case 'p': // package name packageName = getOptionValue(args, i); break; case 'n': // app name appName = getOptionValue(args, i); break; case 'i': // app id appId = getOptionValue(args, i); break; case 'e': // executable name executable = getOptionValue(args, i); break; case 'g': // generate projectRoot = new File(getOptionValue(args, i)); break; default: // ignore break; } } else { printHelpText(); } } new Templater(template).mainClass(mainClass).packageName(packageName).appName(appName) .appId(appId) .executable(executable).buildProject(projectRoot); System.out.println("Project created in " + projectRoot.getAbsolutePath()); } private static boolean isOption(String arg) { return arg.startsWith("-"); } private static String getOptionValue(String[] args, int option) { if (args.length < option + 1) { throw new IllegalArgumentException("value missing for option: " + args[option]); } String value = args[option + 1]; if (isOption(value)) { throw new IllegalArgumentException("illegal value for option: " + args[option]); } return value; } private static void printHelpText() { System.out.println("RoboVM Templater\n" + "Generates a new RoboVM project from a template\n" + "Usage: templater\n" + "-t <TEMPLATE> template (required)\n" + "-c <CLASS> main class (required)\n" + "-p <PACKAGE> package name\n" + "-n <NAME> app name\n" + "-i <ID> app id\n" + "-e <EXECUTABLE> executable name\n" + "-g <PROJECT_ROOT> generates project to project root (required)"); } }
package algorithms.imageProcessing; import algorithms.imageProcessing.features.BlobPerimeterCornerHelper; import algorithms.imageProcessing.features.CornerRegion; import algorithms.misc.Histogram; import algorithms.misc.MiscDebug; import algorithms.util.PairInt; import algorithms.util.PairIntArray; import algorithms.util.PolygonAndPointPlotter; import algorithms.util.ResourceFinder; import gnu.trove.iterator.TIntIterator; import gnu.trove.map.TIntObjectMap; import gnu.trove.map.hash.TIntObjectHashMap; import gnu.trove.set.TIntSet; import gnu.trove.set.hash.TIntHashSet; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Logger; import junit.framework.TestCase; import static org.junit.Assert.*; /** * * @author nichole */ public class ImageSegmentationTest extends TestCase { private Logger log = Logger.getLogger(this.getClass().getName()); public ImageSegmentationTest(String testName) { super(testName); } public void estNextSegmentation() throws Exception { String fileName1, fileName2; for (int i = 5; i < 6; ++i) { //fileName1 = "valve_gaussian.png"; //fileName2 = "valve_gaussian.png"; switch(i) { case 0: { fileName1 = "brown_lowe_2003_image1.jpg"; fileName2 = "brown_lowe_2003_image2.jpg"; break; } case 1: { fileName1 = "venturi_mountain_j6_0001.png"; fileName2 = "venturi_mountain_j6_0010.png"; break; } case 2: { fileName1 = "books_illum3_v0_695x555.png"; fileName2 = "books_illum3_v6_695x555.png"; break; } case 3: { fileName1 = "campus_010.jpg"; fileName2 = "campus_011.jpg"; break; } case 4: { fileName1 = "merton_college_I_001.jpg"; fileName2 = "merton_college_I_002.jpg"; break; } default: { fileName1 = "checkerboard_01.jpg"; fileName2 = "checkerboard_02.jpg"; break; } } System.out.println("fileName1=" + fileName1); String bin = ResourceFinder.findDirectory("bin"); String filePath1 = ResourceFinder.findFileInTestResources(fileName1); String filePath2 = ResourceFinder.findFileInTestResources(fileName2); int idx = fileName1.lastIndexOf("."); String fileNameRoot = fileName1.substring(0, idx); GreyscaleImage img1 = ImageIOHelper.readImage(filePath1).copyToGreyscale(); GreyscaleImage img2 = ImageIOHelper.readImage(filePath2).copyToGreyscale(); ImageSegmentation imageSegmentation = new ImageSegmentation(); GreyscaleImage segImg1 = imageSegmentation.createGreyscale5(img1); GreyscaleImage segImg2 = imageSegmentation.createGreyscale5(img2); String outPath1 = bin + "/seg_1_" + fileNameRoot +".png"; String outPath2 = bin + "/seg_2_" + fileNameRoot +".png"; ImageIOHelper.writeOutputImage(outPath1, segImg1); ImageIOHelper.writeOutputImage(outPath2, segImg2); int z0 = 1; } } public void estBlobExtraction() throws Exception { String fileName1, fileName2; for (int i = 0; i < 6; ++i) { //fileName1 = "valve_gaussian.png"; //fileName2 = "valve_gaussian.png"; switch(i) { case 0: { fileName1 = "brown_lowe_2003_image1.jpg"; fileName2 = "brown_lowe_2003_image2.jpg"; break; } case 1: { fileName1 = "venturi_mountain_j6_0001.png"; fileName2 = "venturi_mountain_j6_0010.png"; break; } case 2: { fileName1 = "books_illum3_v0_695x555.png"; fileName2 = "books_illum3_v6_695x555.png"; break; } case 3: { fileName1 = "campus_010.jpg"; fileName2 = "campus_011.jpg"; break; } case 4: { fileName1 = "merton_college_I_001.jpg"; fileName2 = "merton_college_I_002.jpg"; break; } default: { fileName1 = "checkerboard_01.jpg"; fileName2 = "checkerboard_02.jpg"; break; } } System.out.println("fileName1=" + fileName1); String filePath1 = ResourceFinder.findFileInTestResources(fileName1); String filePath2 = ResourceFinder.findFileInTestResources(fileName2); int idx = fileName1.lastIndexOf("."); String fileNameRoot1 = fileName1.substring(0, idx); idx = fileName2.lastIndexOf("."); String fileNameRoot2 = fileName2.substring(0, idx); ImageExt img1 = ImageIOHelper.readImageExt(filePath1); ImageExt img2 = ImageIOHelper.readImageExt(filePath2); int binnedImageMaxDimension = 512; SegmentationType type = SegmentationType.GREYSCALE_HIST; BlobPerimeterCornerHelper imgHelper1 = new BlobPerimeterCornerHelper(img1, fileNameRoot1); imgHelper1.createBinnedGreyscaleImage(binnedImageMaxDimension); imgHelper1.applySegmentation(type, true); List<List<CornerRegion>> cornerRegions1 = imgHelper1.generatePerimeterCorners(type, true); BlobPerimeterCornerHelper imgHelper2 = new BlobPerimeterCornerHelper(img2, fileNameRoot2); imgHelper2.createBinnedGreyscaleImage(binnedImageMaxDimension); imgHelper2.applySegmentation(type, true); List<List<CornerRegion>> cornerRegions2 = imgHelper2.generatePerimeterCorners(type, true); int z0 = 1; } } public void est0() throws Exception { String[] fileNames = new String[2]; fileNames[0] = "merton_college_I_002.jpg"; fileNames[1] = "merton_college_I_001.jpg"; //fileNames[0] = "brown_lowe_2003_image1.jpg"; //fileNames[1] = "brown_lowe_2003_image2.jpg"; //fileNames[0] = "venturi_mountain_j6_0001.png"; //fileNames[1] = "venturi_mountain_j6_0010.png"; //fileNames[0] = "books_illum3_v0_695x555.png"; //fileNames[1] = "books_illum3_v6_695x555.png"; //fileNames[0] = "campus_010.jpg"; //fileNames[1] = "campus_011.jpg"; //fileNames[0] = "checkerboard_01.jpg"; //fileNames[1] = "checkerboard_02.jpg"; //fileNames[0] = "seattle.jpg"; //fileNames[1] = "arches.jpg"; //fileNames[0] = "stinson_beach.jpg"; //fileNames[1] = "cloudy_san_jose.jpg"; //fileNames[0] = "stonehenge.jpg"; //fileNames[1] = "norwegian_mtn_range.jpg"; //fileNames[0] = "halfdome.jpg"; //fileNames[1] = "costa_rica.jpg"; //fileNames[0] = "new-mexico-sunrise_w725_h490.jpg"; //fileNames[1] = "arizona-sunrise-1342919937GHz.jpg"; //fileNames[0] = "sky_with_rainbow.jpg"; //fileNames[1] = "sky_with_rainbow2.jpg"; //fileNames[0] = "patagonia_snowy_foreground.jpg"; //fileNames[1] = "mt_rainier_snowy_field.jpg"; //fileNames[0] = "klein_matterhorn_snowy_foreground.jpg"; //fileNames[1] = "30.jpg"; //fileNames[0] = "arches_sun_01.jpg"; //fileNames[1] = "stlouis_arch.jpg"; //fileNames[0] = "contrail.jpg"; for (String fileName : fileNames) { int idx = fileName.lastIndexOf("."); String fileNameRoot = fileName.substring(0, idx); String filePath = ResourceFinder.findFileInTestResources(fileName); ImageExt img = ImageIOHelper.readImageExt(filePath); int binnedImageMaxDimension = 512; int binFactor = (int) Math.ceil(Math.max((float) img.getWidth() / binnedImageMaxDimension, (float) img.getHeight() / binnedImageMaxDimension)); ImageProcessor imageProcessor = new ImageProcessor(); img = imageProcessor.binImage(img, binFactor); //ImageSegmentation imageSegmentation = new ImageSegmentation(); //GreyscaleImage gsImg = imageSegmentation.createGreyscale5(img.copyToGreyscale()); GreyscaleImage gsImg = img.copyToGreyscale(); Set<PairInt> pixels = imageProcessor.extract2ndDerivPoints(gsImg, 1000, true); String bin = ResourceFinder.findDirectory("bin"); gsImg.fill(0); for (PairInt p : pixels) { gsImg.setValue(p.getX(), p.getY(), 250); } ImageIOHelper.writeOutputImage(bin + "/" + fileNameRoot + "_seg_max.png", gsImg); /*StringBuilder sb = new StringBuilder(); for (List<CornerRegion> list : cornerRegions2) { for (CornerRegion cr : list) { sb.append(String.format("crImg.setValue(%d, %d);\n", Math.round(cr.getX()[cr.getKMaxIdx()]), Math.round(cr.getY()[cr.getKMaxIdx()]), 255)); } } log.info(sb.toString()); GreyscaleImage crImg = new GreyscaleImage(img4.getWidth(), img4.getHeight(), GreyscaleImage.Type.Bits32FullRangeInt); if (fileNameRoot.equals("checkerboard_01")) { populateCleanedCR1(crImg); } else { populateCleanedCR2(crImg); } imageProcessor.apply2DFFT(crImg, true); ImageIOHelper.writeOutputImage(bin + "/" + fileNameRoot + "_blob_cr_cleaned_fft.png", crImg); plotFFT(crImg, fileNameRoot + "_cleaned"); } GreyscaleImage crImg = new GreyscaleImage(img4.getWidth(), img4.getHeight(), GreyscaleImage.Type.Bits32FullRangeInt); for (List<CornerRegion> list : cornerRegions2) { for (CornerRegion cr : list) { crImg.setValue(cr.getX()[cr.getKMaxIdx()], cr.getY()[cr.getKMaxIdx()], 255); } } //ImageDisplayer.displayImage("img0", crImg); imageProcessor.apply2DFFT(crImg, true); //ImageDisplayer.displayImage("FFT of img0", crImg); ImageIOHelper.writeOutputImage(bin + "/" + fileNameRoot + "_blob_cr_fft.png", crImg); plotFFT(crImg, fileNameRoot); */ int z = 1; } } public void testApplyColorSegmentation() throws Exception { //String fileName = "two_circles_color2.png"; //String fileName = "two_circles_color.png"; //String fileName = "cloudy_san_jose.jpg"; //String fileName = "middlebury_cones_im2.png"; // a limitFrac of 0.1 works well //String fileName = "brown_lowe_2003_image2.jpg"; String fileName = "android_statues_02.jpg"; //String fileName = "venturi_mountain_j6_0010.png"; //String fileName = "books_illum3_v6_695x555.png"; //String fileName = "brown_lowe_2003_image1.jpg"; String filePath = ResourceFinder.findFileInTestResources(fileName); ImageExt img = ImageIOHelper.readImageExt(filePath); //HistogramEqualizationForColor hEq = new HistogramEqualizationForColor(img); //hEq.applyFilter(); ImageSegmentation imageSegmentation = new ImageSegmentation(); List<Set<PairInt>> clusterSets = //imageSegmentation.calculateUsingPolarCIEXYAndFrequency(img, /*0.1f,*/ true); imageSegmentation.calculateUsingPolarCIEXYAndFrequency(img, 0.1f, true); //imageSegmentation.calculateUsingCIEXYAndClustering(img, true); int nPoints = count(clusterSets); int nExtraForDot = 0; Image img2 = new Image(img.getWidth(), img.getHeight()); for (int i = 0; i < clusterSets.size(); ++i) { int[] rgb = ImageIOHelper.getNextRGB(i); Set<PairInt> set = clusterSets.get(i); ImageIOHelper.addToImage(set, 0, 0, img2, nExtraForDot, rgb[0], rgb[1], rgb[2]); } String bin = ResourceFinder.findDirectory("bin"); ImageIOHelper.writeOutputImage(bin + "/cluster.png", img2); //assertTrue(nPoints == img.getNPixels()); boolean[] present = new boolean[img.getNPixels()]; for (Set<PairInt> set : clusterSets) { for (PairInt p : set) { int pixIdx = img.getInternalIndex(p.getX(), p.getY()); assertFalse(present[pixIdx]); present[pixIdx] = true; } } int z = 1; } public void testKMPP_image() throws IOException, Exception { String[] fileNames1 = new String[]{ //"tmp2.png", "brown_lowe_2003_image1.jpg", "venturi_mountain_j6_0001.png", "books_illum3_v0_695x555.png" }; String[] fileNames2 = new String[]{ "brown_lowe_2003_image2.jpg", "venturi_mountain_j6_0010.png", "books_illum3_v6_695x555.png" }; for (int i = 0; i < 1/*fileNames1.length*/; ++i) { String fileName1 = fileNames1[i]; String fileName2 = fileNames2[i]; int idx = fileName1.lastIndexOf("."); String fileNameRoot = fileName1.substring(0, idx); log.info("fileName=" + fileNameRoot); String filePath1 = ResourceFinder.findFileInTestResources(fileName1); String filePath2 = ResourceFinder.findFileInTestResources(fileName2); ImageSegmentation imageSegmentation = new ImageSegmentation(); String bin = ResourceFinder.findDirectory("bin"); int k = 4; ImageExt img1 = ImageIOHelper.readImageExt(filePath1); ImageExt img2 = ImageIOHelper.readImageExt(filePath2); imageSegmentation.applyUsingKMPP(img1, k); MiscDebug.writeImage(img1, "_kmpp_" + fileName1); imageSegmentation.applyUsingKMPP(img2, k); MiscDebug.writeImage(img2, "_kmpp_" + fileName2); GreyscaleImage gsImg1 = ImageIOHelper.readImageAsGrayScaleAvgRGB(filePath1); GreyscaleImage gsImg2 = ImageIOHelper.readImageAsGrayScaleAvgRGB(filePath2); imageSegmentation.applyUsingKMPP(gsImg1, k); MiscDebug.writeImage(gsImg1, "_gs_kmpp_" + fileName1); imageSegmentation.applyUsingKMPP(gsImg2, k); MiscDebug.writeImage(gsImg2, "_gs_kmpp_" + fileName2); } } public void estApplyColorSegmentation2() throws Exception { String[] fileNames1 = new String[]{ "brown_lowe_2003_image1.jpg", "venturi_mountain_j6_0001.png", "books_illum3_v0_695x555.png" }; String[] fileNames2 = new String[]{ "brown_lowe_2003_image2.jpg", "venturi_mountain_j6_0010.png", "books_illum3_v6_695x555.png" }; for (int i = 0; i < fileNames1.length; ++i) { String fileName1 = fileNames1[i]; String fileName2 = fileNames2[i]; int idx = fileName1.lastIndexOf("."); String fileNameRoot = fileName1.substring(0, idx); log.info("fileName=" + fileNameRoot); String filePath1 = ResourceFinder.findFileInTestResources(fileName1); String filePath2 = ResourceFinder.findFileInTestResources(fileName2); //HistogramEqualizationForColor hEq = new HistogramEqualizationForColor(img); //hEq.applyFilter(); ImageSegmentation imageSegmentation = new ImageSegmentation(); String bin = ResourceFinder.findDirectory("bin"); for (int j = 6; j < 7; ++j) { ImageExt img1 = ImageIOHelper.readImageExt(filePath1); ImageExt img2 = ImageIOHelper.readImageExt(filePath2); log.info(" j=" + j); switch (j) { case 0: { int kBands = 2; GreyscaleImage gsImg1 = img1.copyToGreyscale(); GreyscaleImage gsImg2 = img2.copyToGreyscale(); imageSegmentation.applyUsingKMPP(gsImg1, kBands); imageSegmentation.applyUsingKMPP(gsImg2, kBands); img1 = gsImg1.copyToColorGreyscaleExt(); img2 = gsImg2.copyToColorGreyscaleExt(); break; } case 1: { int kBands = 3; GreyscaleImage gsImg1 = img1.copyToGreyscale(); GreyscaleImage gsImg2 = img2.copyToGreyscale(); /*float[] values1 = gsImg1.getFloatValues(); float[] errors1 = Errors.populateYErrorsBySqrt(values1); HistogramHolder hist = Histogram.createSimpleHistogram(values1, errors1); String str = hist.plotLogHistogram(fileNameRoot, "img_" + fileNameRoot + "_hist"); float maxValue = MiscMath.findMax(values1);*/ imageSegmentation.applyUsingKMPP(gsImg1, kBands); imageSegmentation.applyUsingKMPP(gsImg2, kBands); img1 = gsImg1.copyToColorGreyscaleExt(); img2 = gsImg2.copyToColorGreyscaleExt(); break; } case 2: { int kBands = 8; GreyscaleImage gsImg1 = img1.copyToGreyscale(); GreyscaleImage gsImg2 = img2.copyToGreyscale(); imageSegmentation.applyUsingKMPP(gsImg1, kBands); imageSegmentation.applyUsingKMPP(gsImg2, kBands); img1 = gsImg1.copyToColorGreyscaleExt(); img2 = gsImg2.copyToColorGreyscaleExt(); break; } case 3: { int kBands = 2; GreyscaleImage gsImg1 = imageSegmentation .applyUsingCIEXYPolarThetaThenHistEq(img1, kBands, true); GreyscaleImage gsImg2 = imageSegmentation .applyUsingCIEXYPolarThetaThenHistEq(img2, kBands, true); img1 = gsImg1.copyToColorGreyscaleExt(); img2 = gsImg2.copyToColorGreyscaleExt(); break; } case 4: { int kBands = 3; GreyscaleImage gsImg1 = imageSegmentation .applyUsingCIEXYPolarThetaThenHistEq(img1, kBands, true); GreyscaleImage gsImg2 = imageSegmentation .applyUsingCIEXYPolarThetaThenHistEq(img2, kBands, true); img1 = gsImg1.copyToColorGreyscaleExt(); img2 = gsImg2.copyToColorGreyscaleExt(); break; } case 5: { int kBands = 8; GreyscaleImage gsImg1 = imageSegmentation .applyUsingCIEXYPolarThetaThenHistEq(img1, kBands, true); GreyscaleImage gsImg2 = imageSegmentation .applyUsingCIEXYPolarThetaThenHistEq(img2, kBands, true); img1 = gsImg1.copyToColorGreyscaleExt(); img2 = gsImg2.copyToColorGreyscaleExt(); break; } case 6: { int kBands = 2; GreyscaleImage gsImg1 = imageSegmentation .applyUsingCIEXYPolarThetaThenKMPPThenHistEq(img1, kBands, true); GreyscaleImage gsImg2 = imageSegmentation .applyUsingCIEXYPolarThetaThenKMPPThenHistEq(img2, kBands, true); img1 = gsImg1.copyToColorGreyscaleExt(); img2 = gsImg2.copyToColorGreyscaleExt(); break; } case 7: { int kBands = 3; GreyscaleImage gsImg1 = imageSegmentation .applyUsingCIEXYPolarThetaThenKMPPThenHistEq(img1, kBands, true); GreyscaleImage gsImg2 = imageSegmentation .applyUsingCIEXYPolarThetaThenKMPPThenHistEq(img2, kBands, true); img1 = gsImg1.copyToColorGreyscaleExt(); img2 = gsImg2.copyToColorGreyscaleExt(); break; } case 8: { int kBands = 8; GreyscaleImage gsImg1 = imageSegmentation .applyUsingCIEXYPolarThetaThenKMPPThenHistEq(img1, kBands, true); GreyscaleImage gsImg2 = imageSegmentation .applyUsingCIEXYPolarThetaThenKMPPThenHistEq(img2, kBands, true); img1 = gsImg1.copyToColorGreyscaleExt(); img2 = gsImg2.copyToColorGreyscaleExt(); break; } case 9: { int kBands = 2; //TODO: may need a blur of 1 GreyscaleImage gsImg1 = imageSegmentation .applyUsingCIEXYPolarThetaThenHistogram(img1, kBands); GreyscaleImage gsImg2 = imageSegmentation .applyUsingCIEXYPolarThetaThenHistogram(img2, kBands); img1 = gsImg1.copyToColorGreyscaleExt(); img2 = gsImg2.copyToColorGreyscaleExt(); break; } case 10: { int kBands = 3; //TODO: may need a blur of 1 GreyscaleImage gsImg1 = imageSegmentation .applyUsingCIEXYPolarThetaThenHistogram(img1, kBands); GreyscaleImage gsImg2 = imageSegmentation .applyUsingCIEXYPolarThetaThenHistogram(img2, kBands); img1 = gsImg1.copyToColorGreyscaleExt(); img2 = gsImg2.copyToColorGreyscaleExt(); break; } case 11: { int kBands = 8; //TODO: may need a blur of 1 GreyscaleImage gsImg1 = imageSegmentation .applyUsingCIEXYPolarThetaThenHistogram(img1, kBands); GreyscaleImage gsImg2 = imageSegmentation .applyUsingCIEXYPolarThetaThenHistogram(img2, kBands); img1 = gsImg1.copyToColorGreyscaleExt(); img2 = gsImg2.copyToColorGreyscaleExt(); break; } case 12: { int kBands = 2; //TODO: may need a blur of 1 GreyscaleImage gsImg1 = imageSegmentation .applyUsingCIEXYPolarThetaThenKMPP(img1, kBands); GreyscaleImage gsImg2 = imageSegmentation .applyUsingCIEXYPolarThetaThenKMPP(img2, kBands); img1 = gsImg1.copyToColorGreyscaleExt(); img2 = gsImg2.copyToColorGreyscaleExt(); break; } case 13: { int kBands = 3; //TODO: may need a blur of 1 GreyscaleImage gsImg1 = imageSegmentation .applyUsingCIEXYPolarThetaThenKMPP(img1, kBands); GreyscaleImage gsImg2 = imageSegmentation .applyUsingCIEXYPolarThetaThenKMPP(img2, kBands); img1 = gsImg1.copyToColorGreyscaleExt(); img2 = gsImg2.copyToColorGreyscaleExt(); break; } case 14: { int kBands = 8; //TODO: may need a blur of 1 GreyscaleImage gsImg1 = imageSegmentation .applyUsingCIEXYPolarThetaThenKMPP(img1, kBands); GreyscaleImage gsImg2 = imageSegmentation .applyUsingCIEXYPolarThetaThenKMPP(img2, kBands); img1 = gsImg1.copyToColorGreyscaleExt(); img2 = gsImg2.copyToColorGreyscaleExt(); break; } case 15: { List<Set<PairInt>> groups1 = imageSegmentation.calculateUsingCIEXYAndClustering(img1, true); List<Set<PairInt>> groups2 = imageSegmentation.calculateUsingCIEXYAndClustering(img2, true); int nExtraForDot = 0; ImageExt img11 = new ImageExt(img1.getWidth(), img1.getHeight()); for (int k = 0; k < groups1.size(); ++k) { int[] rgb = ImageIOHelper.getNextRGB(k); Set<PairInt> set = groups1.get(k); ImageIOHelper.addToImage(set, 0, 0, img11, nExtraForDot, rgb[0], rgb[1], rgb[2]); } img1 = img11; ImageExt img22 = new ImageExt(img2.getWidth(), img2.getHeight()); for (int k = 0; k < groups2.size(); ++k) { int[] rgb = ImageIOHelper.getNextRGB(k); Set<PairInt> set = groups2.get(k); ImageIOHelper.addToImage(set, 0, 0, img22, nExtraForDot, rgb[0], rgb[1], rgb[2]); } img2 = img22; break; } case 16: { GreyscaleImage gsImg1 = imageSegmentation.applyUsingPolarCIEXYAndFrequency(img1, true); GreyscaleImage gsImg2 = imageSegmentation.applyUsingPolarCIEXYAndFrequency(img2, true); img1 = gsImg1.copyToColorGreyscaleExt(); img2 = gsImg1.copyToColorGreyscaleExt(); break; } case 17: { List<Set<PairInt>> groups1 = imageSegmentation.calculateUsingPolarCIEXYAndClustering(img1, true); List<Set<PairInt>> groups2 = imageSegmentation.calculateUsingPolarCIEXYAndClustering(img2, true); int nExtraForDot = 0; ImageExt img11 = new ImageExt(img1.getWidth(), img1.getHeight()); for (int k = 0; k < groups1.size(); ++k) { int[] rgb = ImageIOHelper.getNextRGB(k); Set<PairInt> set = groups1.get(k); ImageIOHelper.addToImage(set, 0, 0, img11, nExtraForDot, rgb[0], rgb[1], rgb[2]); } img1 = img11; ImageExt img22 = new ImageExt(img2.getWidth(), img2.getHeight()); for (int k = 0; k < groups2.size(); ++k) { int[] rgb = ImageIOHelper.getNextRGB(k); Set<PairInt> set = groups2.get(k); ImageIOHelper.addToImage(set, 0, 0, img22, nExtraForDot, rgb[0], rgb[1], rgb[2]); } img2 = img22; break; } case 18: { List<Set<PairInt>> groups1 = imageSegmentation.calculateUsingPolarCIEXYAndFrequency(img1, true); List<Set<PairInt>> groups2 = imageSegmentation.calculateUsingPolarCIEXYAndFrequency(img2, true); int nExtraForDot = 0; ImageExt img11 = new ImageExt(img1.getWidth(), img1.getHeight()); for (int k = 0; k < groups1.size(); ++k) { int[] rgb = ImageIOHelper.getNextRGB(k); Set<PairInt> set = groups1.get(k); ImageIOHelper.addToImage(set, 0, 0, img11, nExtraForDot, rgb[0], rgb[1], rgb[2]); } img1 = img11; ImageExt img22 = new ImageExt(img2.getWidth(), img2.getHeight()); for (int k = 0; k < groups2.size(); ++k) { int[] rgb = ImageIOHelper.getNextRGB(k); Set<PairInt> set = groups2.get(k); ImageIOHelper.addToImage(set, 0, 0, img22, nExtraForDot, rgb[0], rgb[1], rgb[2]); } img2 = img22; break; } case 19: { List<Set<PairInt>> groups1 = imageSegmentation.calculateUsingPolarCIEXYAndFrequency(img1, 0.2f, true); List<Set<PairInt>> groups2 = imageSegmentation.calculateUsingPolarCIEXYAndFrequency(img2, 0.2f, true); int nExtraForDot = 0; ImageExt img11 = new ImageExt(img1.getWidth(), img1.getHeight()); for (int k = 0; k < groups1.size(); ++k) { int[] rgb = ImageIOHelper.getNextRGB(k); Set<PairInt> set = groups1.get(k); ImageIOHelper.addToImage(set, 0, 0, img11, nExtraForDot, rgb[0], rgb[1], rgb[2]); } img1 = img11; ImageExt img22 = new ImageExt(img2.getWidth(), img2.getHeight()); for (int k = 0; k < groups2.size(); ++k) { int[] rgb = ImageIOHelper.getNextRGB(k); Set<PairInt> set = groups2.get(k); ImageIOHelper.addToImage(set, 0, 0, img22, nExtraForDot, rgb[0], rgb[1], rgb[2]); } img2 = img22; break; } default: { break; } } ImageIOHelper.writeOutputImage(bin + "/" + fileNameRoot + "_segmentation1_" + j + ".png", img1); ImageIOHelper.writeOutputImage(bin + "/" + fileNameRoot + "_segmentation2_" + j + ".png", img2); } } } private int count(List<Set<PairInt>> setList) { int c = 0; for (Set<PairInt> set : setList) { c += set.size(); } return c; } private void plotFFT(GreyscaleImage crImg, String fileNameRoot) throws IOException { int bn = 1; float[] xPoints = new float[crImg.getWidth() / bn]; float[] yPoints = new float[crImg.getWidth() / bn]; float xmn = 0; float xmx = crImg.getWidth() / bn; float ymn = Float.MAX_VALUE; float ymx = Float.MIN_VALUE; int row = 50; for (int i = 0; i < (crImg.getWidth() / bn) - 1; ++i) { int ii = bn * i; xPoints[i] = i; for (int k = 0; k < bn; ++k) { yPoints[i] += crImg.getValue(ii + k, row); } yPoints[i] /= bn; if (yPoints[i] < ymn) { ymn = yPoints[i]; } if (yPoints[i] > ymx) { ymx = yPoints[i]; } } PolygonAndPointPlotter plotter = new PolygonAndPointPlotter(); plotter.addPlot(xmn, xmx, ymn, ymx, xPoints, yPoints, null, null, xPoints, yPoints, "X fft_" + fileNameRoot); xPoints = new float[crImg.getHeight() / bn]; yPoints = new float[crImg.getHeight() / bn]; xmn = 0; xmx = crImg.getHeight() / bn; ymn = Float.MAX_VALUE; ymx = Float.MIN_VALUE; int col = 50; for (int j = 0; j < (crImg.getHeight() / bn) - 1; ++j) { int jj = bn * j; xPoints[j] = j; for (int k = 0; k < bn; ++k) { yPoints[j] += crImg.getValue(jj + k, row); } yPoints[j] /= bn; if (yPoints[j] < ymn) { ymn = yPoints[j]; } if (yPoints[j] > ymx) { ymx = yPoints[j]; } } plotter.addPlot(xmn, xmx, ymn, ymx, xPoints, yPoints, null, null, xPoints, yPoints, "y fft_" + fileNameRoot); plotter.writeFile(fileNameRoot + "_blob_cr_fft"); } public void testCalculateKeyPoints() throws Exception { /* 100 x 100 pixels diagonal segment of width 20 pixels */ TIntSet indexes = new TIntHashSet(); ImageExt img = new ImageExt(100, 100); float[] x = new float[100 * 20]; float[] y = new float[100 * 20]; int count = 0; for (int row = 0; row < 100; ++row) { if (row > 99) { continue; } for (int col = row; col < (row + 20); ++col) { if (col > (99)) { continue; } int pixIdx = img.getInternalIndex(col, row); img.setRGB(pixIdx, 200, 200, 200); indexes.add(pixIdx); x[count] = col; y[count] = row; count++; } } ImageSegmentation.DecimatedData dd = new ImageSegmentation.DecimatedData(); dd.dImages[0] = img; TIntObjectMap<TIntSet> indexMap = new TIntObjectHashMap<TIntSet>(); indexMap.put(1, indexes); dd.dLabeledIndexes.add(indexMap); dd.dBinFactors[0] = 1; // centroid not needed for test ImageSegmentation imageSegmentation = new ImageSegmentation(); List<List<PairInt>> listKeypoints = imageSegmentation.calculateKeyPoints(dd, 0, 100, 100); List<PairInt> keyPoints = listKeypoints.get(0); /*float[] xPoints = new float[keyPoints.size()]; float[] yPoints = new float[keyPoints.size()]; for (int i = 0; i < keyPoints.size(); ++i) { PairInt kp = keyPoints.get(i); xPoints[i] = kp.getX(); yPoints[i] = kp.getY(); } PolygonAndPointPlotter plotter = new PolygonAndPointPlotter(); plotter.addPlot(0, 101, 0, 101, xPoints, yPoints, null, null, x, y, "keypoints"); plotter.writeFile("keypoints"); */ //assert that every point n indexes is withon // dist of 6 to a keypoint TIntIterator iter = indexes.iterator(); while (iter.hasNext()) { int pixIdx = iter.next(); int xp = img.getCol(pixIdx); int yp = img.getRow(pixIdx); boolean found = false; for (PairInt kp : keyPoints) { int diffX = kp.getX() - xp; int diffY = kp.getY() - yp; if (diffX < 7 && diffY < 7) { found = true; break; } } assertTrue(found); } } private void populateCleanedCR2(GreyscaleImage crImg) { crImg.setValue(84, 146); crImg.setValue(36, 146); crImg.setValue(35, 99); crImg.setValue(85, 99); crImg.setValue(83, 97); crImg.setValue(37, 97); //crImg.setValue(36, 77); artifact //crImg.setValue(35, 65); artifact crImg.setValue(36, 50); //crImg.setValue(45, 49); artifact //crImg.setValue(67, 50); artifact crImg.setValue(83, 51); crImg.setValue(83, 193); crImg.setValue(37, 194); crImg.setValue(36, 148); crImg.setValue(84, 148); crImg.setValue(131, 99); crImg.setValue(86, 98); crImg.setValue(86, 51); //crImg.setValue(105, 52); artifact crImg.setValue(131, 53); crImg.setValue(131, 192); crImg.setValue(86, 193); crImg.setValue(86, 146); crImg.setValue(131, 146); crImg.setValue(130, 52); //crImg.setValue(105, 51); artifact crImg.setValue(86, 50); crImg.setValue(86, 4); //crImg.setValue(104, 5); artifact //crImg.setValue(119, 6); artifact crImg.setValue(131, 7); crImg.setValue(176, 54); crImg.setValue(133, 53); crImg.setValue(132, 13); crImg.setValue(134, 6); //crImg.setValue(154, 7); artifact //crImg.setValue(168, 8); artifact crImg.setValue(176, 9); crImg.setValue(130, 145); crImg.setValue(86, 144); crImg.setValue(87, 99); //crImg.setValue(92, 100); artifact crImg.setValue(131, 101); crImg.setValue(176, 144); //crImg.setValue(138, 145); artifact crImg.setValue(133, 146); crImg.setValue(132, 101); crImg.setValue(177, 101); crImg.setValue(175, 99); crImg.setValue(133, 98); crImg.setValue(134, 54); //crImg.setValue(155, 55); artifact crImg.setValue(176, 56); //crImg.setValue(219, 89); artifact crImg.setValue(218, 101); crImg.setValue(178, 100); crImg.setValue(177, 56); //crImg.setValue(187, 55); artifact //crImg.setValue(190, 56); artifact crImg.setValue(220, 58); crImg.setValue(175, 189); //crImg.setValue(168, 190); artifact crImg.setValue(134, 191); crImg.setValue(133, 148); crImg.setValue(176, 147); crImg.setValue(218, 189); crImg.setValue(178, 190); crImg.setValue(177, 146); crImg.setValue(219, 146); crImg.setValue(218, 56); //crImg.setValue(190, 55); artifact crImg.setValue(179, 54); crImg.setValue(179, 10); //crImg.setValue(190, 11); artifact //crImg.setValue(203, 12); artifact crImg.setValue(219, 14); crImg.setValue(218, 144); crImg.setValue(178, 144); //crImg.setValue(177, 116); artifact crImg.setValue(178, 102); //crImg.setValue(201, 101); artifact //crImg.setValue(204, 102); artifact crImg.setValue(219, 103); crImg.setValue(259, 144); crImg.setValue(221, 145); crImg.setValue(221, 101); crImg.setValue(260, 103); crImg.setValue(260, 58); //crImg.setValue(248, 57); artifact crImg.setValue(222, 56); crImg.setValue(222, 12); //crImg.setValue(237, 13); artifact //crImg.setValue(250, 14); artifact //crImg.setValue(253, 15); artifact crImg.setValue(261, 16); } private void populateCleanedCR1(GreyscaleImage crImg) { crImg.setValue(123, 148); crImg.setValue(78, 148); crImg.setValue(77, 102); //crImg.setValue(110, 101); artifact //crImg.setValue(113, 102); artifact crImg.setValue(124, 103); crImg.setValue(123, 55); crImg.setValue(78, 54); crImg.setValue(78, 8); crImg.setValue(124, 9); crImg.setValue(169, 101); crImg.setValue(125, 102); crImg.setValue(125, 55); crImg.setValue(138, 56); crImg.setValue(170, 57); //crImg.setValue(170, 96); artifact crImg.setValue(75, 147); crImg.setValue(31, 147); crImg.setValue(30, 102); crImg.setValue(50, 101); crImg.setValue(53, 102); crImg.setValue(76, 103); crImg.setValue(75, 53); crImg.setValue(31, 53); crImg.setValue(30, 17); crImg.setValue(31, 14); crImg.setValue(32, 7); crImg.setValue(53, 8); crImg.setValue(76, 9); crImg.setValue(214, 56); crImg.setValue(171, 56); crImg.setValue(171, 10); //crImg.setValue(206, 11); artifact crImg.setValue(215, 12); crImg.setValue(213, 148); crImg.setValue(171, 148); crImg.setValue(171, 102); crImg.setValue(215, 103); //crImg.setValue(214, 112); artifact //crImg.setValue(215, 136); artifact crImg.setValue(168, 193); crImg.setValue(125, 194); crImg.setValue(125, 148); crImg.setValue(169, 149); crImg.setValue(122, 101); crImg.setValue(79, 100); crImg.setValue(78, 56); crImg.setValue(108, 55); crImg.setValue(111, 56); crImg.setValue(123, 57); crImg.setValue(259, 102); crImg.setValue(215, 101); //crImg.setValue(215, 66); artifact crImg.setValue(217, 57); crImg.setValue(260, 58); crImg.setValue(168, 55); crImg.setValue(135, 54); crImg.setValue(125, 53); crImg.setValue(125, 10); //crImg.setValue(141, 9); artifact //crImg.setValue(144, 10); artifact crImg.setValue(169, 11); crImg.setValue(258, 193); crImg.setValue(216, 193); crImg.setValue(216, 148); crImg.setValue(258, 148); crImg.setValue(122, 193); crImg.setValue(79, 193); crImg.setValue(78, 150); crImg.setValue(123, 150); crImg.setValue(168, 147); crImg.setValue(126, 147); crImg.setValue(125, 104); crImg.setValue(169, 104); //crImg.setValue(214, 66); artifact crImg.setValue(213, 101); crImg.setValue(172, 101); crImg.setValue(172, 57); crImg.setValue(215, 58); crImg.setValue(213, 192); crImg.setValue(170, 191); crImg.setValue(170, 150); crImg.setValue(214, 150); crImg.setValue(258, 147); crImg.setValue(217, 147); crImg.setValue(216, 104); crImg.setValue(258, 103); crImg.setValue(258, 56); crImg.setValue(217, 56); crImg.setValue(217, 12); crImg.setValue(258, 13); } }
package org.jfree.chart.block.junit; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.chart.block.Block; import org.jfree.chart.block.BlockContainer; import org.jfree.chart.block.EmptyBlock; import org.jfree.chart.block.GridArrangement; import org.jfree.chart.block.LengthConstraintType; import org.jfree.chart.block.RectangleConstraint; import org.jfree.chart.util.Size2D; import org.jfree.data.Range; /** * Tests for the {@link GridArrangement} class. */ public class GridArrangementTests extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(GridArrangementTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public GridArrangementTests(String name) { super(name); } /** * Confirm that the equals() method can distinguish all the required fields. */ public void testEquals() { GridArrangement f1 = new GridArrangement(11, 22); GridArrangement f2 = new GridArrangement(11, 22); assertTrue(f1.equals(f2)); assertTrue(f2.equals(f1)); f1 = new GridArrangement(33, 22); assertFalse(f1.equals(f2)); f2 = new GridArrangement(33, 22); assertTrue(f1.equals(f2)); f1 = new GridArrangement(33, 44); assertFalse(f1.equals(f2)); f2 = new GridArrangement(33, 44); assertTrue(f1.equals(f2)); } /** * Immutable - cloning is not necessary. */ public void testCloning() { GridArrangement f1 = new GridArrangement(1, 2); assertFalse(f1 instanceof Cloneable); } /** * Serialize an instance, restore it, and check for equality. */ public void testSerialization() { GridArrangement f1 = new GridArrangement(33, 44); GridArrangement f2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(f1); out.close(); ObjectInput in = new ObjectInputStream(new ByteArrayInputStream( buffer.toByteArray())); f2 = (GridArrangement) in.readObject(); in.close(); } catch (Exception e) { e.printStackTrace(); } assertEquals(f1, f2); } private static final double EPSILON = 0.000000001; /** * Test arrangement with no constraints. */ public void testNN() { BlockContainer c = createTestContainer1(); Size2D s = c.arrange(null, RectangleConstraint.NONE); assertEquals(90.0, s.width, EPSILON); assertEquals(33.0, s.height, EPSILON); } /** * Test arrangement with a fixed width and no height constraint. */ public void testFN() { BlockContainer c = createTestContainer1(); RectangleConstraint constraint = new RectangleConstraint(100.0, null, LengthConstraintType.FIXED, 0.0, null, LengthConstraintType.NONE); Size2D s = c.arrange(null, constraint); assertEquals(100.0, s.width, EPSILON); assertEquals(33.0, s.height, EPSILON); } /** * Test arrangement with a fixed height and no width constraint. */ public void testNF() { BlockContainer c = createTestContainer1(); RectangleConstraint constraint = RectangleConstraint.NONE.toFixedHeight( 100.0); Size2D s = c.arrange(null, constraint); assertEquals(90.0, s.width, EPSILON); assertEquals(100.0, s.height, EPSILON); } /** * Test arrangement with a range for the width and a fixed height. */ public void testRF() { BlockContainer c = createTestContainer1(); RectangleConstraint constraint = new RectangleConstraint(new Range(40.0, 60.0), 100.0); Size2D s = c.arrange(null, constraint); assertEquals(60.0, s.width, EPSILON); assertEquals(100.0, s.height, EPSILON); } /** * Test arrangement with a range for the width and height. */ public void testRR() { BlockContainer c = createTestContainer1(); RectangleConstraint constraint = new RectangleConstraint(new Range(40.0, 60.0), new Range(50.0, 70.0)); Size2D s = c.arrange(null, constraint); assertEquals(60.0, s.width, EPSILON); assertEquals(50.0, s.height, EPSILON); } /** * Test arrangement with a range for the width and no height constraint. */ public void testRN() { BlockContainer c = createTestContainer1(); RectangleConstraint constraint = RectangleConstraint.NONE.toRangeWidth( new Range(40.0, 60.0)); Size2D s = c.arrange(null, constraint); assertEquals(60.0, s.width, EPSILON); assertEquals(33.0, s.height, EPSILON); } /** * Test arrangement with a range for the height and no width constraint. */ public void testNR() { BlockContainer c = createTestContainer1(); RectangleConstraint constraint = RectangleConstraint.NONE.toRangeHeight( new Range(40.0, 60.0)); Size2D s = c.arrange(null, constraint); assertEquals(90.0, s.width, EPSILON); assertEquals(40.0, s.height, EPSILON); } private BlockContainer createTestContainer1() { Block b1 = new EmptyBlock(10, 11); Block b2 = new EmptyBlock(20, 22); Block b3 = new EmptyBlock(30, 33); BlockContainer result = new BlockContainer(new GridArrangement(1, 3)); result.add(b1); result.add(b2); result.add(b3); return result; } /** * The arrangement should be able to handle null blocks in the layout. */ public void testNullBlock_FF() { BlockContainer c = new BlockContainer(new GridArrangement(1, 1)); c.add(null); Size2D s = c.arrange(null, new RectangleConstraint(20, 10)); assertEquals(20.0, s.getWidth(), EPSILON); assertEquals(10.0, s.getHeight(), EPSILON); } /** * The arrangement should be able to handle null blocks in the layout. */ public void testNullBlock_FN() { BlockContainer c = new BlockContainer(new GridArrangement(1, 1)); c.add(null); Size2D s = c.arrange(null, RectangleConstraint.NONE.toFixedWidth(10)); assertEquals(10.0, s.getWidth(), EPSILON); assertEquals(0.0, s.getHeight(), EPSILON); } /** * The arrangement should be able to handle null blocks in the layout. */ public void testNullBlock_FR() { BlockContainer c = new BlockContainer(new GridArrangement(1, 1)); c.add(null); Size2D s = c.arrange(null, new RectangleConstraint(30.0, new Range(5.0, 10.0))); assertEquals(30.0, s.getWidth(), EPSILON); assertEquals(5.0, s.getHeight(), EPSILON); } /** * The arrangement should be able to handle null blocks in the layout. */ public void testNullBlock_NN() { BlockContainer c = new BlockContainer(new GridArrangement(1, 1)); c.add(null); Size2D s = c.arrange(null, RectangleConstraint.NONE); assertEquals(0.0, s.getWidth(), EPSILON); assertEquals(0.0, s.getHeight(), EPSILON); } /** * The arrangement should be able to handle less blocks than grid spaces. */ public void testGridNotFull_FF() { Block b1 = new EmptyBlock(5, 5); BlockContainer c = new BlockContainer(new GridArrangement(2, 3)); c.add(b1); Size2D s = c.arrange(null, new RectangleConstraint(200, 100)); assertEquals(200.0, s.getWidth(), EPSILON); assertEquals(100.0, s.getHeight(), EPSILON); } /** * The arrangement should be able to handle less blocks than grid spaces. */ public void testGridNotFull_FN() { Block b1 = new EmptyBlock(5, 5); BlockContainer c = new BlockContainer(new GridArrangement(2, 3)); c.add(b1); Size2D s = c.arrange(null, RectangleConstraint.NONE.toFixedWidth(30.0)); assertEquals(30.0, s.getWidth(), EPSILON); assertEquals(10.0, s.getHeight(), EPSILON); } /** * The arrangement should be able to handle less blocks than grid spaces. */ public void testGridNotFull_FR() { Block b1 = new EmptyBlock(5, 5); BlockContainer c = new BlockContainer(new GridArrangement(2, 3)); c.add(b1); Size2D s = c.arrange(null, new RectangleConstraint(30.0, new Range(5.0, 10.0))); assertEquals(30.0, s.getWidth(), EPSILON); assertEquals(10.0, s.getHeight(), EPSILON); } /** * The arrangement should be able to handle less blocks than grid spaces. */ public void testGridNotFull_NN() { Block b1 = new EmptyBlock(5, 5); BlockContainer c = new BlockContainer(new GridArrangement(2, 3)); c.add(b1); Size2D s = c.arrange(null, RectangleConstraint.NONE); assertEquals(15.0, s.getWidth(), EPSILON); assertEquals(10.0, s.getHeight(), EPSILON); } }
package com.kii.thingif.query.clause; import android.os.Parcel; import org.json.JSONObject; import java.util.Arrays; public class And extends com.kii.thingif.internal.clause.And implements Clause{ public And(Clause... clauses) { super(clauses); } @Override public JSONObject toJSONObject() { return super.toJSONObject(); } @Override public boolean equals(Object o) { return super.equals(o); } @Override public int hashCode() { return Arrays.hashCode(this.getClauses()); } // Implementation of Parcelable private And(Parcel in) { super(in); } public static final Creator<And> CREATOR = new Creator<And>() { @Override public And createFromParcel(Parcel in) { return new And(in); } @Override public And[] newArray(int size) { return new And[size]; } }; }
package org.jgrapes.http; import java.io.UnsupportedEncodingException; import java.net.Inet4Address; import java.net.InetAddress; import java.net.SocketAddress; import java.net.UnknownHostException; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.text.ParseException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import javax.net.ssl.SNIHostName; import javax.net.ssl.SNIServerName; import org.jdrupes.httpcodec.Codec; import org.jdrupes.httpcodec.Decoder; import org.jdrupes.httpcodec.MessageHeader; import org.jdrupes.httpcodec.ProtocolException; import org.jdrupes.httpcodec.ServerEngine; import org.jdrupes.httpcodec.protocols.http.HttpConstants.HttpStatus; import org.jdrupes.httpcodec.protocols.http.HttpField; import org.jdrupes.httpcodec.protocols.http.HttpRequest; import org.jdrupes.httpcodec.protocols.http.HttpResponse; import org.jdrupes.httpcodec.protocols.http.server.HttpRequestDecoder; import org.jdrupes.httpcodec.protocols.http.server.HttpResponseEncoder; import org.jdrupes.httpcodec.protocols.websocket.WsCloseFrame; import org.jdrupes.httpcodec.protocols.websocket.WsMessageHeader; import org.jdrupes.httpcodec.types.Converters; import org.jdrupes.httpcodec.types.MediaType; import org.jdrupes.httpcodec.types.StringList; import org.jgrapes.core.Channel; import org.jgrapes.core.Component; import org.jgrapes.core.annotation.Handler; import org.jgrapes.http.events.OptionsRequest; import org.jgrapes.http.events.Request; import org.jgrapes.http.events.Response; import org.jgrapes.http.events.Upgraded; import org.jgrapes.http.events.WebSocketAccepted; import org.jgrapes.http.events.WebSocketClosed; import org.jgrapes.io.IOSubchannel; import org.jgrapes.io.events.Close; import org.jgrapes.io.events.Closed; import org.jgrapes.io.events.Input; import org.jgrapes.io.events.Output; import org.jgrapes.io.util.LinkedIOSubchannel; import org.jgrapes.io.util.ManagedBuffer; import org.jgrapes.io.util.ManagedBufferQueue; import org.jgrapes.io.util.ManagedByteBuffer; import org.jgrapes.io.util.ManagedCharBuffer; import org.jgrapes.net.TcpServer; import org.jgrapes.net.events.Accepted; /** * A converter component that receives and sends byte buffers on a * network channel and sends HTTP requests and receives HTTP * responses on its own channel. */ public class HttpServer extends Component { private List<Class<? extends Request>> providedFallbacks; private int matchLevels = 1; boolean acceptNoSni = false; int applicationBufferSize = 4096; /** * Create a new server that uses the {@code networkChannel} for network * level I/O. * <P> * As a convenience the server can provide fall back handlers for the * specified types of requests. The fall back handler simply returns 404 ( * "Not found"). * * @param appChannel * this component's channel * @param networkChannel * the channel for network level I/O * @param fallbacks * the requests for which a fall back handler is provided */ @SafeVarargs public HttpServer(Channel appChannel, Channel networkChannel, Class<? extends Request>... fallbacks) { super(appChannel); this.providedFallbacks = Arrays.asList(fallbacks); Handler.Evaluator.add( this, "onAccepted", networkChannel.defaultCriterion()); Handler.Evaluator.add( this, "onInput", networkChannel.defaultCriterion()); Handler.Evaluator.add( this, "onClosed", networkChannel.defaultCriterion()); } /** * Create a new server that creates its own {@link TcpServer} with the given * address and uses it for network level I/O. * * @param appChannel * this component's channel * @param serverAddress the address to listen on * @param fallbacks fall backs */ @SafeVarargs public HttpServer(Channel appChannel, SocketAddress serverAddress, Class<? extends Request>... fallbacks) { super(appChannel); this.providedFallbacks = Arrays.asList(fallbacks); TcpServer server = new TcpServer().setServerAddress(serverAddress); attach(server); Handler.Evaluator.add( this, "onAccepted", server.defaultCriterion()); Handler.Evaluator.add( this, "onInput", server.defaultCriterion()); } /** * @return the matchLevels */ public int matchLevels() { return matchLevels; } /** * Sets the number of elements from the request path used in the match value * of the generated events (see {@link Request#defaultCriterion()}), defaults * to 1. * * @param matchLevels the matchLevels to set * @return the http server for easy chaining */ public HttpServer setMatchLevels(int matchLevels) { this.matchLevels = matchLevels; return this; } /** * Sets the size of the buffers used for {@link Output} events * on the application channel. Defaults to 4096. * * @param applicationBufferSize the size to set * @return the http server for easy chaining */ public HttpServer setApplicationBufferSize(int applicationBufferSize) { this.applicationBufferSize = applicationBufferSize; return this; } /** * Returns the size of the application side (receive) buffers. * * @return the value */ public int applicationBufferSize() { return applicationBufferSize; } /** * Determines if request from secure (TLS) connections without * SNI are accepted. * * Secure (TLS) requests usually transfer the name of the server that * they want to connect to during handshake. The HTTP server checks * that the `Host` header field of decoded requests matches the * name used to establish the connection. If, however, the connection * is made using the IP-address, the client does not have a host name. * If such connections are to be accepted, this flag, which * defaults to `false`, must be set. * * Note that in request accepted without SNI, the `Host` header field * will be modified to contain the IP-address of the indicated host * to prevent accidental matching wit virtual host names. * * @param acceptNoSni the value to set * @return the http server for easy chaining */ public HttpServer setAcceptNoSni(boolean acceptNoSni) { this.acceptNoSni = acceptNoSni; return this; } /** * Returns if secure (TLS) requests without SNI are allowed. * * @return the result */ public boolean acceptNoSni() { return acceptNoSni; } /** * Creates a new downstream connection as {@link LinkedIOSubchannel} * of the network connection, a {@link HttpRequestDecoder} and a * {@link HttpResponseEncoder}. * * @param event * the accepted event */ @Handler(dynamic=true) public void onAccepted(Accepted event, IOSubchannel netChannel) { new AppChannel(event, netChannel); } /** * Handles data from the client (from upstream). The data is send through * the {@link HttpRequestDecoder} and events are sent downstream according * to the decoding results. * * @param event the event * @throws ProtocolException if a protocol exception occurs * @throws InterruptedException */ @Handler(dynamic=true) public void onInput( Input<ManagedByteBuffer> event, IOSubchannel netChannel) throws ProtocolException, InterruptedException { final AppChannel appChannel = (AppChannel) LinkedIOSubchannel.lookupLinked(netChannel); if (appChannel == null || appChannel.converterComponent() != this) { return; } appChannel.handleNetInput(event); } @Handler(dynamic=true) public void onClosed(Closed event, IOSubchannel netChannel) { final AppChannel appChannel = (AppChannel) LinkedIOSubchannel.lookupLinked(netChannel); if (appChannel == null || appChannel.converterComponent() != this) { return; } appChannel.handleClosed(event); } /** * Handles a response event from downstream by sending it through an * {@link HttpResponseEncoder} that generates the data (encoded information) * and sends it upstream with {@link Output} events. Depending on whether * the response has a body, subsequent {@link Output} events can * follow. * * @param event * the response event * @throws InterruptedException if the execution was interrupted */ @Handler public void onResponse(Response event, AppChannel appChannel) throws InterruptedException { appChannel.handleResponse(event); } /** * Receives the message body of a response. A {@link Response} event that * has a message body can be followed by one or more {@link Output} events * from downstream that contain the data. An {@code Output} event * with the end of record flag set signals the end of the message body. * * @param event * the event with the data * @throws InterruptedException if the execution was interrupted */ @Handler public void onOutput(Output<ManagedBuffer<?>> event, AppChannel appChannel) throws InterruptedException { appChannel.handleAppOutput(event); } /** * Handles a close event from downstream by sending a {@link Close} * event upstream. * * @param event * the close event * @throws InterruptedException if the execution was interrupted */ @Handler public void onClose(Close event, AppChannel appChannel) throws InterruptedException { final IOSubchannel netChannel = appChannel.upstreamChannel(); netChannel.respond(new Close()); } /** * Checks whether the request has been handled (status code of response has * been set). If not, send the default response ("Not implemented") to the * client. * * @param event * the request completed event * @param appChannel the application channel * @throws InterruptedException if the execution was interrupted */ @Handler public void onRequestCompleted( Request.Completed event, IOSubchannel appChannel) throws InterruptedException { final Request requestEvent = event.event(); if (requestEvent.isStopped()) { // Has been handled return; } final HttpResponse response = requestEvent.request().response().get(); if (response.statusCode() != HttpStatus.NOT_IMPLEMENTED.statusCode()) { // Some other component takes care return; } // No component has taken care of the request, provide // fallback response sendResponse(response, appChannel, HttpStatus.NOT_IMPLEMENTED.statusCode(), HttpStatus.NOT_IMPLEMENTED.reasonPhrase()); } /** * Provides a fallback handler for an OPTIONS request with asterisk. Simply * responds with "OK". * * @param event the event * @param appChannel the application channel */ @Handler(priority = Integer.MIN_VALUE) public void onOptions(OptionsRequest event, IOSubchannel appChannel) { if (event.requestUri() == HttpRequest.ASTERISK_REQUEST) { HttpResponse response = event.request().response().get(); response.setStatus(HttpStatus.OK); appChannel.respond(new Response(response)); event.stop(); } } @Handler(priority = Integer.MIN_VALUE) public void onRequest(Request event, IOSubchannel appChannel) throws ParseException { if (providedFallbacks == null || !providedFallbacks.contains(event.getClass())) { return; } sendResponse(event.request().response().get(), appChannel, HttpStatus.NOT_FOUND.statusCode(), HttpStatus.NOT_FOUND.reasonPhrase()); event.stop(); } @Handler public void onWebSocketAccepted( WebSocketAccepted event, AppChannel appChannel) { appChannel.handleWebSocketAccepted(event); } private void sendResponse(HttpResponse response, IOSubchannel appChannel, int statusCode, String reasonPhrase) { response.setStatusCode(statusCode).setReasonPhrase(reasonPhrase) .setHasPayload(true).setField( HttpField.CONTENT_TYPE, MediaType.builder().setType("text", "plain") .setParameter("charset", "utf-8").build()); fire(new Response(response), appChannel); try { fire(Output.wrap((statusCode + " " + reasonPhrase) .getBytes("utf-8"), true), appChannel); } catch (UnsupportedEncodingException e) { // Supported by definition } } private class AppChannel extends LinkedIOSubchannel { // Starts as ServerEngine<HttpRequest,HttpResponse> but may change private ServerEngine<?,?> engine; private ManagedByteBuffer outBuffer; private boolean secure; private List<String> snis = Collections.emptyList(); private ManagedBufferQueue<ManagedByteBuffer, ByteBuffer> byteBufferPool; private ManagedBufferQueue<ManagedCharBuffer, CharBuffer> charBufferPool; private ManagedBufferQueue<?, ?> currentPool = null; private boolean switchedToWebSocket = false; private WsMessageHeader currentWsMessage = null; public AppChannel(Accepted event, IOSubchannel netChannel) { super(HttpServer.this, netChannel); engine = new ServerEngine<>( new HttpRequestDecoder(), new HttpResponseEncoder()); secure = event.isSecure(); if (secure) { snis = new ArrayList<>(); for (SNIServerName sni: event.requestedServerNames()) { if (sni instanceof SNIHostName) { snis.add(((SNIHostName)sni).getAsciiName()); } } } // Allocate buffer pools byteBufferPool = new ManagedBufferQueue<>(ManagedByteBuffer::new, ByteBuffer.allocate(applicationBufferSize), ByteBuffer.allocate(applicationBufferSize)); charBufferPool = new ManagedBufferQueue<>(ManagedCharBuffer::new, CharBuffer.allocate(applicationBufferSize), CharBuffer.allocate(applicationBufferSize)); } public void handleNetInput(Input<ManagedByteBuffer> event) throws ProtocolException, InterruptedException { // Send the data from the event through the decoder. ByteBuffer in = event.buffer().backingBuffer(); ManagedBuffer<?> bodyData = null; while (in.hasRemaining()) { Decoder.Result<?> result = engine.decode(in, bodyData == null ? null : bodyData.backingBuffer(), event.isEndOfRecord()); if (result.response().isPresent()) { // Feedback required, send it respond(new Response(result.response().get())); if (result.response().get().isFinal()) { if (result.isHeaderCompleted()) { engine.currentRequest() .filter(WsCloseFrame.class::isInstance) .ifPresent(closeFrame -> { fire(new WebSocketClosed( (WsCloseFrame)closeFrame, AppChannel.this)); }); } break; } if (result.isResponseOnly()) { continue; } } if (result.isHeaderCompleted()) { if (!handleRequestHeader(engine.currentRequest().get())) { break; } } if (bodyData != null && bodyData.position() > 0) { bodyData.flip(); fire(new Input<>(bodyData, !result.isOverflow() && !result.isUnderflow()), this); } if (result.isOverflow()) { // Determine what kind of buffer we need bodyData = currentPool.acquire(); continue; } } } private boolean handleRequestHeader(MessageHeader request) { if (request instanceof HttpRequest) { HttpRequest httpRequest = (HttpRequest)request; if (httpRequest.hasPayload()) { if(httpRequest.findValue( HttpField.CONTENT_TYPE, Converters.MEDIA_TYPE) .map(f -> f.value().topLevelType() .equalsIgnoreCase("text")) .orElse(false)) { currentPool = charBufferPool; } else { currentPool = byteBufferPool; } } if (secure) { if (!snis.contains(httpRequest.host())) { if (acceptNoSni && snis.isEmpty()) { convertHostToNumerical(httpRequest); } else { sendResponse(httpRequest.response().get(), this, 421, "Misdirected Request"); return false; } } } fire(Request.fromHttpRequest(httpRequest, secure, matchLevels), this); } else if (request instanceof WsMessageHeader) { WsMessageHeader wsMessage = (WsMessageHeader)request; if (wsMessage.hasPayload()) { if (wsMessage.isTextMode()) { currentPool = charBufferPool; } else { currentPool = byteBufferPool; } } } return true; } private void convertHostToNumerical(HttpRequest request) { int port = request.port(); String host; try { InetAddress addr = InetAddress.getByName( request.host()); host = addr.getHostAddress(); if (!(addr instanceof Inet4Address)) { host = "[" + host + "]"; } } catch (UnknownHostException e) { host = "127.0.0.1"; } request.setHostAndPort(host, port); } public void handleResponse(Response event) throws InterruptedException { if (!engine.encoding().isAssignableFrom(event.response().getClass())) { return; } final MessageHeader response = event.response(); // Start sending the response @SuppressWarnings("unchecked") ServerEngine<?,MessageHeader> httpEngine = (ServerEngine<?,MessageHeader>)engine; httpEngine.encode(response); boolean hasBody = response.hasPayload(); while (true) { outBuffer = upstreamChannel().byteBufferPool().acquire(); final ManagedByteBuffer buffer = outBuffer; Codec.Result result = engine.encode( Codec.EMPTY_IN, buffer.backingBuffer(), !hasBody); if (result.isOverflow()) { fire(new Output<>(buffer, false), upstreamChannel()); continue; } if (hasBody) { // Keep buffer with incomplete response to be further // filled by Output events break; } // Response is complete if (buffer.position() > 0) { fire(new Output<>(buffer, false), upstreamChannel()); } else { buffer.unlockBuffer(); } outBuffer = null; if (result.closeConnection()) { fire(new Close(), upstreamChannel()); } break; } } public void handleWebSocketAccepted(WebSocketAccepted event) { switchedToWebSocket = true; final HttpResponse response = event.baseResponse() .setStatus(HttpStatus.SWITCHING_PROTOCOLS) .setField(HttpField.UPGRADE, new StringList("websocket")); event.addCompletedEvent( new Upgraded(event.resourceName(), "websocket")); respond(new Response(response)); } public void handleAppOutput(Output<ManagedBuffer<?>> event) throws InterruptedException { Buffer eventData = event.buffer().backingBuffer(); Buffer input; if (eventData instanceof ByteBuffer) { input = ((ByteBuffer)eventData).duplicate(); } else if(eventData instanceof CharBuffer) { input = ((CharBuffer)eventData).duplicate(); } else { return; } if (switchedToWebSocket && currentWsMessage == null) { // When switched to WebSockets, we only have Input and Output // events. Add header automatically. @SuppressWarnings("unchecked") ServerEngine<?,MessageHeader> wsEngine = (ServerEngine<?,MessageHeader>)engine; currentWsMessage = new WsMessageHeader( event.buffer().backingBuffer() instanceof CharBuffer, true); wsEngine.encode(currentWsMessage); } while (input.hasRemaining() || event.isEndOfRecord()) { if (outBuffer == null) { outBuffer = upstreamChannel().byteBufferPool().acquire(); } Codec.Result result = engine.encode(input, outBuffer.backingBuffer(), event.isEndOfRecord()); if (result.isOverflow()) { upstreamChannel().respond(new Output<>(outBuffer, false)); outBuffer = upstreamChannel().byteBufferPool().acquire(); continue; } if (event.isEndOfRecord() || result.closeConnection()) { if (outBuffer.position() > 0) { upstreamChannel().respond(new Output<>(outBuffer, false)); } else { outBuffer.unlockBuffer(); } outBuffer = null; if (result.closeConnection()) { upstreamChannel().respond(new Close()); } break; } } if (switchedToWebSocket && event.isEndOfRecord()) { currentWsMessage = null; } } public void handleClosed(Closed event) { fire(new Closed(), this); } } }
package io.syndesis.qe.bdd; import io.syndesis.qe.Component; import io.syndesis.qe.templates.FtpTemplate; import org.assertj.core.api.Assertions; import java.io.IOException; import java.sql.Time; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; import java.util.Optional; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.regex.Pattern; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; import io.fabric8.kubernetes.api.model.Pod; import io.fabric8.openshift.api.model.Build; import io.syndesis.qe.endpoints.TestSupport; import io.syndesis.qe.templates.AmqTemplate; import io.syndesis.qe.templates.SyndesisTemplate; import io.syndesis.qe.utils.DbUtils; import io.syndesis.qe.utils.LogCheckerUtils; import io.syndesis.qe.utils.OpenShiftUtils; import io.syndesis.qe.utils.SampleDbConnectionManager; import lombok.extern.slf4j.Slf4j; @Slf4j public class CommonSteps { @Given("^clean default namespace") public void cleanNamespace() { OpenShiftUtils.getInstance().cleanAndAssert(); } @Given("^clean all builds") public void cleanBuilds() { OpenShiftUtils.getInstance().getBuildConfigs().forEach(OpenShiftUtils.getInstance()::deleteBuildConfig); OpenShiftUtils.getInstance().getBuilds().forEach(OpenShiftUtils.getInstance()::deleteBuild); } @When("^deploy Syndesis from template") public void deploySyndesis() { SyndesisTemplate.deploy(); } @Then("^wait for Syndesis to become ready") public void waitForSyndeisis() { EnumSet<Component> components = EnumSet.allOf(Component.class); ExecutorService executorService = Executors.newFixedThreadPool(10); components.forEach(c -> { Runnable runnable = () -> OpenShiftUtils.xtf().waiters() .areExactlyNPodsRunning(1, "component", c.getName()) .interval(TimeUnit.SECONDS, 20) .timeout(TimeUnit.MINUTES, 12) .assertEventually(); executorService.submit(runnable); }); executorService.shutdown(); try { if (!executorService.awaitTermination(10, TimeUnit.MINUTES)) { executorService.shutdownNow(); Assertions.fail("Syndesis wasn't initilized in time"); } } catch (InterruptedException e) { Assertions.fail("Syndesis wasn't initilized in time"); } } @Then("^verify s2i build of integration \"([^\"]*)\" was finished in duration (\\d+) min$") public void verifyBuild(String integrationName, int duration) { String sanitizedName = integrationName.toLowerCase().replaceAll(" ", "-"); Optional<Build> s2iBuild = OpenShiftUtils.getInstance().getBuilds().stream().filter(b -> b.getMetadata().getName().contains(sanitizedName)).findFirst(); if (s2iBuild.isPresent()) { Build build = s2iBuild.get(); String buildPodName = build.getMetadata().getAnnotations().get("openshift.io/build.pod-name"); Optional<Pod> buildPod = OpenShiftUtils.getInstance().getPods().stream().filter(p -> p.getMetadata().getName().equals(buildPodName)).findFirst(); if (buildPod.isPresent()) { try { boolean[] patternsInLogs = LogCheckerUtils.findPatternsInLogs(buildPod.get(), Pattern.compile(".*Downloading: \\b.*")); Assertions.assertThat(patternsInLogs).containsOnly(false); } catch (IOException e) { e.printStackTrace(); } } Assertions.assertThat(build.getStatus().getPhase()).isEqualTo("Complete"); // % 1_000L is there to parse OpenShift ms format Assertions.assertThat(build.getStatus().getDuration() % 1_000L).isLessThan(duration * 60 * 1000); } else { Assertions.fail("No build found for integration with name " + sanitizedName); } } @Given("^deploy AMQ broker$") public void deployAMQBroker() throws Throwable { AmqTemplate.deploy(); } @Given("^execute SQL command \"([^\"]*)\"$") public void executeSql(String sqlCmd) { DbUtils dbUtils = new DbUtils(SampleDbConnectionManager.getInstance().getConnection()); dbUtils.readSqlOnSampleDb(sqlCmd); SampleDbConnectionManager.getInstance().closeConnection(); } @Given("^clean TODO table$") public void cleanTodoTable() { DbUtils dbUtils = new DbUtils(SampleDbConnectionManager.getInstance().getConnection()); dbUtils.deleteRecordsInTable("TODO"); SampleDbConnectionManager.getInstance().closeConnection(); } @Given("^clean application state") public void resetState() { int responseCode = TestSupport.getInstance().resetDbWithResponse(); Assertions.assertThat(responseCode).isEqualTo(204); } @Given("^deploy FTP server$") public void deployFTPServier() { FtpTemplate.deploy(); } @Given("^clean FTP server$") public void cleanFTPServier() { FtpTemplate.cleanUp(); } }
/** * The count-and-say sequence is the sequence of integers beginning as follows: * * 1, 11, 21, 1211, 111221, ... * 1 is read off as "one 1" or 11. * 11 is read off as "two 1s" or 21. * 21 is read off as "one 2, then one 1" or 1211. * Given an integer n, generate the nth sequence. * * Note: The sequence of integers will be represented as a string. * * Tags: String */ class CountAndSay { public static void main(String[] args) { System.out.println(countAndSay(1)); System.out.println(countAndSay(2)); System.out.println(countAndSay(3)); System.out.println(countAndSay(4)); System.out.println(countAndSay(5)); System.out.println(countAndSay(6)); } /** * Build from n - 1 to n * Traverse and get count of each char and append to result */ public static String countAndSay(int n) { String res = "1"; while (--n > 0) { StringBuilder sb = new StringBuilder(); char[] prev = res.toCharArray(); for (int i = 0; i < prev.length; i++) { int count = 1; // initialize current count as 1 while (i + 1 < prev.length && prev[i] == prev[i + 1]) { count++; // search for same char i++; } sb.append(count).append(prev[i]); } res = sb.toString(); } return res; } /** * Bottom-up approach */ public static String countAndSayB(int n) { if (n <= 0) return ""; if (n == 1) return "1"; int i = 2; String res = "1"; while (i <= n) { String curRes = ""; int count = 1; char prevNum = res.charAt(0); for (int j = 1; j < res.length(); j++) { char curNum = res.charAt(j); if (prevNum == curNum) { count++; } else { curRes += count; // update current result curRes += prevNum; count = 1; // reset count } prevNum = curNum; } curRes += count; // update last loop curRes += prevNum; res = curRes; // build next count i++; } return res; } }
package ifc.text; import lib.MultiPropertyTest; import com.sun.star.text.ControlCharacter; /** * Testing <code>com.sun.star.text.TextPortion</code> * service properties : * <ul> * <li><code> TextPortionType</code></li> * <li><code> ControlCharacter</code></li> * </ul> <p> * Properties testing is automated by <code>lib.MultiPropertyTest</code>. * @see com.sun.star.text.TextPortion */ public class _TextPortion extends MultiPropertyTest { /** * This property can be void, so if old value is <code> null </code> * new value must be specified. */ public void _ControlCharacter() { testProperty("ControlCharacter", new Short(ControlCharacter.LINE_BREAK), new Short(ControlCharacter.PARAGRAPH_BREAK)) ; } } //finish class _TextPortion
package org.hfoss.posit; import java.io.OutputStream; import java.util.ArrayList; import java.util.Calendar; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import org.hfoss.posit.adhoc.AdhocClientActivity; import org.hfoss.posit.provider.MyDBHelper; import org.hfoss.posit.provider.POSITProvider; import org.hfoss.posit.utilities.ImageAdapter; import org.hfoss.posit.utilities.Utils; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.ActivityNotFoundException; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.Matrix; import android.location.Criteria; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.preference.PreferenceManager; import android.provider.MediaStore; import android.provider.MediaStore.Images; import android.provider.MediaStore.MediaColumns; import android.provider.MediaStore.Images.ImageColumns; import android.provider.MediaStore.Images.Media; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.Button; import android.widget.EditText; import android.widget.Gallery; import android.widget.TextView; import android.widget.AdapterView.OnItemClickListener; /** * Handles both adding new finds as well as editing existing finds. * Includes adding and editing name, description, and barcode. Also allows user * to attach photos to the find, as well as delete everything. * */ public class FindActivity extends Activity implements OnClickListener, OnItemClickListener, LocationListener { private Find mFind; private long mFindId; private int mState; private Cursor mCursor = null; private Gallery mGallery; //list of temporary files representing pictures taken for a find //that has not been added to the database private ArrayList<Bitmap> mTempBitmaps = new ArrayList<Bitmap>(); //list of uris of new images and thumbnails being attached to the find private List<Uri> mNewImageUris = new LinkedList<Uri>(); private List<Uri> mNewImageThumbnailUris = new LinkedList<Uri>(); private double mLongitude = 0; private double mLatitude = 0; private TextView mLatitudeTextView; private TextView mLongitudeTextView; private Thread mThread; private LocationManager mLocationManager; private String valueName; private String valueDescription; private String valueId; public static boolean SAVE_CHECK=false; public static int PROJECT_ID; private static boolean IS_ADHOC = false; public int INTENT_CHECK=0;// anybody finds more suitable ways please change it public static final int STATE_EDIT = 1; public static final int STATE_INSERT= 2; public static final int BARCODE_READER= 3; public static final int CAMERA_ACTIVITY= 4; public static final int NEW_FIND_CAMERA_ACTIVITY = 7; public static final int SYNC_ACTIVITY= 12; public static final int IMAGE_VIEW = 13; private static final String TAG = "FindActivity"; private static final int CONFIRM_DELETE_DIALOG = 0; private static final int NON_UNIQUE_ID = 1; private static final int UPDATE_LOCATION = 2; private static final int CONFIRM_EXIT=3; private static final int NON_NUMERIC_ID = 4; private static final int TOO_BIG_ID = 5; private static final boolean ENABLED_ONLY = true; private static final int THUMBNAIL_TARGET_SIZE = 320; Handler updateHandler = new Handler() { /** Gets called on every message that is received */ public void handleMessage(Message msg) { switch (msg.what) { case UPDATE_LOCATION: { mLatitudeTextView.setText(" " + mLatitude); mLongitudeTextView.setText(" " + mLongitude); break; } } super.handleMessage(msg); } }; /** * Sets up the various actions for the FindActivity, which are * to insert new finds in the DB, edit existing finds, and attaching images * to the finds * @param savedInstanceState (not currently used) is to restore state. */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //finishActivity(ListFindsActivity.FIND_FROM_LIST); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); PROJECT_ID = sp.getInt("PROJECT_ID", 0); IS_ADHOC = sp.getBoolean("IS_ADHOC", false); final Intent intent = getIntent(); String action = intent.getAction(); setContentView(R.layout.add_find); mLatitudeTextView = (TextView)findViewById(R.id.latitudeText); mLongitudeTextView = (TextView)findViewById(R.id.longitudeText); mGallery = (Gallery)findViewById(R.id.picturesTaken); Button scanButton = (Button)findViewById(R.id.idBarcodeButton); scanButton.setOnClickListener(this); TextView barcodeError = (TextView)findViewById(R.id.barcodeReaderError); Button barcodeDownload = (Button)findViewById(R.id.barcodeDownloadButton); TextView barcodeRestart = (TextView)findViewById(R.id.barcodeReaderRestart); barcodeDownload.setOnClickListener(this); barcodeError.setVisibility(TextView.GONE); barcodeDownload.setVisibility(Button.GONE); barcodeRestart.setVisibility(TextView.GONE); if(!isIntentAvailable(this,"com.google.zxing.client.android.SCAN")) { scanButton.setClickable(false); barcodeError.setVisibility(TextView.VISIBLE); barcodeDownload.setVisibility(Button.VISIBLE); barcodeRestart.setVisibility(TextView.VISIBLE); } if (action.equals(Intent.ACTION_EDIT)) { doEditAction(); INTENT_CHECK=1; } else if (action.equals(Intent.ACTION_INSERT)) { doInsertAction(); SAVE_CHECK=true; } } // onCreate() @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { mTempBitmaps = savedInstanceState.getParcelableArrayList("bitmaps"); displayGallery(mFindId); super.onRestoreInstanceState(savedInstanceState); } @Override protected void onSaveInstanceState(Bundle outState) { outState.putParcelableArrayList("bitmaps", mTempBitmaps); super.onSaveInstanceState(outState); } /** * This method is used to check whether or not the user has an intent * available before an activity is actually started. This is only * invoked on the Find view to check whether or not the intent for * the barcode scanner is available. Since the barcode scanner requires * a downloadable dependency, the user will not be allowed to click the * "Read Barcode" button unless the phone is able to do so. * @param context * @param action * @return */ public static boolean isIntentAvailable(Context context, String action) { final PackageManager packageManager = context.getPackageManager(); final Intent intent = new Intent(action); List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); return list.size() > 0; } /** * Inserts a new Find. A TextView handles all the data entry. For new * Finds, both a time stamp and GPS location are fixed. */ public void doInsertAction() { mState = STATE_INSERT; TextView tView = (TextView) findViewById(R.id.timeText); tView.setText(getDateText()); TextView idView = (TextView) findViewById(R.id.idText); idView.setText(""); TextView nameView = (TextView) findViewById(R.id.nameText); nameView.setText(""); TextView descView = (TextView) findViewById(R.id.descriptionText); descView.setText(""); initializeLocationAndStartGpsThread(); } /** * Sets the Find's location to the last known location and starts * a separate thread to update GPS location. */ private void initializeLocationAndStartGpsThread() { mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE); List<String> providers = mLocationManager.getProviders(ENABLED_ONLY); if(Utils.debug) Log.i(TAG, "Enabled providers = " + providers.toString()); String provider = mLocationManager.getBestProvider(new Criteria(),ENABLED_ONLY); if(Utils.debug) Log.i(TAG, "Best provider = " + provider); setCurrentGpsLocation(null); mThread = new Thread(new MyThreadRunner()); mThread.start(); } /** * Repeatedly attempts to update the Find's location. */ class MyThreadRunner implements Runnable { public void run() { while (!Thread.currentThread().isInterrupted()) { Message m = Message.obtain(); m.what = 0; FindActivity.this.updateHandler.sendMessage(m); try { Thread.sleep(5); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } } /** * Allows editing of editable data for existing finds. For existing finds, * we retrieve the Find's data from the DB and display it in a TextView. The * Find's location and time stamp are not updated. */ private void doEditAction() { mState = STATE_EDIT; mFindId = getIntent().getLongExtra(MyDBHelper.COLUMN_IDENTIFIER, 0); if(Utils.debug) Log.i(TAG, "rowID = " + mFindId); // Instantiate a find object and retrieve its data from the DB mFind = new Find(this, mFindId); ContentValues values = mFind.getContent(); if (values == null) { Utils.showToast(this, "No values found for Find " + mFindId); mState = STATE_INSERT; } else { displayContentInView(values); } displayGallery(mFindId); } @Override protected void onResume() { super.onResume(); } @Override protected void onPause(){ super.onPause(); //finishActivity(ListFindsActivity.FIND_FROM_LIST); } /** * This method is invoked by showDialog() when a dialog window is created. It displays * the appropriate dialog box, currently a dialog to confirm that the user wants to * delete this find and a dialog to warn user that a barcode has already been entered into the system */ @Override protected Dialog onCreateDialog(int id) { switch (id) { case CONFIRM_DELETE_DIALOG: return new AlertDialog.Builder(this) .setIcon(R.drawable.alert_dialog_icon) .setTitle(R.string.alert_dialog_2) .setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // User clicked OK so do some stuff if (mFind.delete()) // Assumes find was instantiated in onCreate { Utils.showToast(FindActivity.this, R.string.deleted_from_database); finish(); } else Utils.showToast(FindActivity.this, R.string.delete_failed); //Intent intent = new Intent(FindActivity.this, ListFindsActivity.class); //startActivity(intent); //TabMain.moveTab(1); } } ) .setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { /* User clicked Cancel so do nothing */ } }) .create(); case CONFIRM_EXIT: return new AlertDialog.Builder(this) .setIcon(R.drawable.alert_dialog_icon) .setTitle(R.string.check_saving) .setPositiveButton(R.string.save, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // User clicked OK so do some stuff ContentValues contentValues = retrieveContentFromView(); if(contentValues.getAsInteger(getString(R.string.idDB)) != 0){ if (mState == STATE_INSERT) { //if this is a new find mFind = new Find(FindActivity.this); saveCameraImageAndUri(mFind, mTempBitmaps); //save all temporary media List<ContentValues> imageValues = retrieveImagesFromUris(); //get uris for all new media if (mFind.insertToDB(contentValues, imageValues)) {//insert find into database Utils.showToast(FindActivity.this, R.string.saved_to_database); } else { Utils.showToast(FindActivity.this, R.string.save_failed); } } else { if (mFind.updateToDB(contentValues)) { Utils.showToast(FindActivity.this, R.string.saved_to_database); } else { Utils.showToast(FindActivity.this, R.string.save_failed); } } finish(); //Intent in = new Intent(this, ListFindsActivity.class); //redirect to list finds //startActivity(in); /*if(mState==STATE_INSERT) TabMain.moveTab(1); else if(mState==STATE_EDIT) finish();*/ } } }).setNeutralButton(R.string.closing, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { /*if(mState==STATE_INSERT) TabMain.moveTab(1); else if(mState==STATE_EDIT)*/ finish(); } }).setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { /* User clicked Cancel so do nothing */ } }) .create(); case NON_UNIQUE_ID: return new AlertDialog.Builder(this) .setIcon(R.drawable.alert_dialog_icon) .setTitle(R.string.alert_dialog_non_unique) .setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { //do nothing } }).create(); case NON_NUMERIC_ID: return new AlertDialog.Builder(this) .setIcon(R.drawable.alert_dialog_icon) .setTitle(R.string.alert_dialog_non_numeric) .setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { //do nothing } }).create(); case TOO_BIG_ID: return new AlertDialog.Builder(this) .setIcon(R.drawable.alert_dialog_icon) .setTitle("ID must be less than 9 digits") .setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { //do nothing } }).create(); default: return null; } // switch } /** * This code checks whether or not the data has been changed. If the data has * been changed, a dialog pops up when you push the back button, reminding you * to save the data. */ private void checkSave(){ EditText eText = (EditText) findViewById(R.id.nameText); String value = eText.getText().toString(); eText = (EditText) findViewById(R.id.descriptionText); String description = eText.getText().toString(); eText = (EditText) findViewById(R.id.idText); String ID = eText.getText().toString(); if (valueName != null && valueName.equals(value) && valueDescription.equals(description) && valueId.equals(ID)) { SAVE_CHECK=false; } else { SAVE_CHECK=true; } } /** * This method is used to close the current find activity * when the back button is hit. We ran into problems with * activities running on top of each other and not finishing * and this helps close old activities. * @param keyCode is an integer representing which key is pressed * @param event is a KeyEvent that is not used here * @return a boolean telling whether or not the operation was successful */ /* * Here I use an Integer INTNET_CHECK to check weather the the action is insert or edition. * if the action is edition, it the OnKedyDown method will utilize the checkSave method to * check weather the database has been changed or not */ @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (INTENT_CHECK==1) { checkSave(); } if(keyCode == KeyEvent.KEYCODE_BACK && SAVE_CHECK == true) { showDialog(CONFIRM_EXIT); return true; } return super.onKeyDown(keyCode, event); } @Override protected void onStop() { super.onStop(); } /** * Creates the menu for this activity by inflating a menu resource file. */ @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.add_finds_menu, menu); if(mState == STATE_INSERT) menu.removeItem(R.id.delete_find_menu_item); return true; } // onCreateOptionsMenu() /** * Handles the various menu item actions. * @param featureId is unused * @param item is the MenuItem selected by the user */ @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { Intent intent; switch (item.getItemId()) { case R.id.save_find_menu_item: long start; Log.i("start",(start=System.currentTimeMillis())+""); ContentValues contentValues = retrieveContentFromView(); Log.i("after retrive", (System.currentTimeMillis()-start)+""); if (IS_ADHOC) sendAdhocFind(contentValues); Log.i("after adhoc check", (System.currentTimeMillis()-start)+""); // Don't save to database if ID is zero. // This indicates a non-numeric or invalid ID if (contentValues.getAsString(getString(R.string.idDB))==""|| contentValues.getAsString(getString(R.string.idDB))==null) return false; Log.i("after nonnumeric check", (System.currentTimeMillis()-start)+""); if (mState == STATE_INSERT) { //if this is a new find mFind = new Find(this); saveCameraImageAndUri(mFind, mTempBitmaps); //save all temporary media mTempBitmaps.clear(); List<ContentValues> imageValues = retrieveImagesFromUris(); //get uris for all new media if (mFind.insertToDB(contentValues, imageValues)) {//insert find into database Log.i("after insert", (System.currentTimeMillis()-start)+""); Utils.showToast(this, R.string.saved_to_database); } else { Utils.showToast(this, R.string.save_failed); } finish(); //onCreate(null); //TabMain.moveTab(1); } else { if (mFind.updateToDB(contentValues)) { Utils.showToast(this, R.string.saved_to_database); } else { Utils.showToast(this, R.string.save_failed); } finish(); } //Intent in = new Intent(this, ListFindsActivity.class); //redirect to list finds //startActivity(in); break; case R.id.discard_changes_menu_item: if (mState == STATE_EDIT) { displayContentInView(mFind.getContent()); } else { mTempBitmaps.clear(); onCreate(null); } break; case R.id.camera_menu_item: intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra("rowId", mFindId); if (mFind == null) { startActivityForResult(intent, NEW_FIND_CAMERA_ACTIVITY); //camera for new find } else { startActivityForResult(intent, CAMERA_ACTIVITY); //camera for existing find } break; case R.id.delete_find_menu_item: showDialog(CONFIRM_DELETE_DIALOG); break; default: return false; } return true; } // onMenuItemSelected private void sendAdhocFind(ContentValues contentValues) { Utils.showToast(this, "sending ad hoc find"); String longitude = contentValues.getAsString(getString(R.string.longitudeDB)); String latitude = contentValues.getAsString(getString(R.string.latitudeDB)); // long findId = contentValues.getAsLong(getString(R.string.idDB)); String findId = contentValues.getAsString(getString(R.string.idDB)); String name = contentValues.getAsString(getString(R.string.nameDB)); String description = contentValues.getAsString(getString(R.string.descriptionDB)); Log.i("Adhoc", "Adhoc find: "+ new Long(findId).toString()+ ":"+ longitude+ ","+ latitude); JSONObject obj = new JSONObject(); try { obj.put("findLong", longitude); obj.put("findLat", latitude); obj.put("findId", findId); obj.put("name", name); obj.put("description", description); obj.put("projectId", PROJECT_ID); } catch (JSONException e) { Log.e("JSONError", e.toString()); } Log.i("Adhoc", "Sending:"+ obj.toString()); if(AdhocClientActivity.adhocClient!=null) AdhocClientActivity.adhocClient.send(obj.toString()); else if(PositMain.mAdhocClient!=null) PositMain.mAdhocClient.send(obj.toString()); } /** * Retrieves values from the View fields and stores them as <key,value> pairs in a ContentValues. * This method is invoked from the Save menu item. It also marks the find 'unsynced' * so it will be updated to the server. * @return The ContentValues hash table. */ private ContentValues retrieveContentFromView() { ContentValues result = new ContentValues(); EditText eText = (EditText) findViewById(R.id.nameText); String value = eText.getText().toString(); result.put(getString(R.string.nameDB), value); eText = (EditText) findViewById(R.id.descriptionText); value = eText.getText().toString(); result.put(getString(R.string.descriptionDB), value); eText = (EditText) findViewById(R.id.idText); value = eText.getText().toString(); try { // result.put(getString(R.string.idDB), Long.parseLong(value)); result.put(getString(R.string.idDB), value); // if(value.length() >= 10) { // showDialog(TOO_BIG_ID); // result.put(getString(R.string.idDB), 0); } catch (NumberFormatException e) { // If user entered non-numeric ID, show an error Utils.showToast(this, "Error: ID must be numeric"); // and set id in result object to 0 result.put(getString(R.string.idDB), 0); } TextView tView = (TextView) findViewById(R.id.longitudeText); value = tView.getText().toString(); result.put(getString(R.string.longitudeDB), value); tView = (TextView) findViewById(R.id.latitudeText); value = tView.getText().toString(); result.put(getString(R.string.latitudeDB), value); tView = (TextView) findViewById(R.id.timeText); value = tView.getText().toString(); result.put(getString(R.string.timeDB), value); // Mark the find unsynched result.put(getString(R.string.syncedDB),"0"); //add project id result.put(getString(R.string.projectId), PROJECT_ID); return result; } /** * Retrieves images and thumbnails from their uris stores them as <key,value> pairs in a ContentValues, * one for each image. Each ContentValues is then stored in a list to carry all the images * @return the list of images stored as ContentValues */ private List<ContentValues> retrieveImagesFromUris() { List<ContentValues> values = new LinkedList<ContentValues>(); ListIterator<Uri> imageIt = mNewImageUris.listIterator(); ListIterator<Uri> thumbnailIt = mNewImageThumbnailUris.listIterator(); while (imageIt.hasNext() && thumbnailIt.hasNext()) { Uri imageUri = imageIt.next(); Uri thumbnailUri = thumbnailIt.next(); ContentValues result = new ContentValues(); String value = ""; if (imageUri != null) { value = imageUri.toString(); result.put(MyDBHelper.COLUMN_IMAGE_URI, value); value = thumbnailUri.toString(); result.put(MyDBHelper.COLUMN_PHOTO_THUMBNAIL_URI, value); } values.add(result); } mNewImageUris.clear(); mNewImageThumbnailUris.clear(); return values; } /** * Retrieves values from a ContentValues has table and puts them in the View. * @param contentValues stores <key, value> pairs */ private void displayContentInView(ContentValues contentValues) { EditText eText = (EditText) findViewById(R.id.nameText); eText.setText(contentValues.getAsString(getString(R.string.nameDB))); valueName=eText.getText().toString(); eText = (EditText) findViewById(R.id.descriptionText); eText.setText(contentValues.getAsString(getString(R.string.descriptionDB))); valueDescription=eText.getText().toString(); eText = (EditText) findViewById(R.id.idText); eText.setText(contentValues.getAsString(getString(R.string.idDB))); eText.setFocusable(false); valueId=eText.getText().toString(); TextView tView = (TextView) findViewById(R.id.timeText); if (mState == STATE_EDIT) { tView.setText(contentValues.getAsString(getString(R.string.timeDB))); } tView = (TextView) findViewById(R.id.longitudeText); tView.setText(contentValues.getAsString(getString(R.string.longitudeDB))); tView = (TextView) findViewById(R.id.latitudeText); tView.setText(contentValues.getAsString(getString(R.string.latitudeDB))); } /** * Handles the barcode reader button clicks. * @param v is the View where the click occurred. */ public void onClick(View v) { Intent intent; switch (v.getId()) { case R.id.idBarcodeButton: intent = new Intent("com.google.zxing.client.android.SCAN"); try { startActivityForResult(intent, BARCODE_READER); } catch(ActivityNotFoundException e) { Log.e(TAG, e.toString()); } break; case R.id.barcodeDownloadButton: intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse("market://search?q=pname:com.google.zxing.client.android")); startActivity(intent); } } /** * Invoked when one of the Activities started * from FindActivity menu, such as the BARCODE_READER or the CAMERA, finishes. * It handles the results of the Activities. RESULT_OK == -1, RESULT_CANCELED = 0 * @param requestCode is the code that launched the sub-activity * @param resultCode specifies whether the sub-activity was successful or not * @param data is an Intent storing whatever data is passed back by the sub-activity */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); int rowId; if (resultCode == RESULT_CANCELED) { return; } switch (requestCode) { case BARCODE_READER: String value = data.getStringExtra("SCAN_RESULT"); MyDBHelper dBHelper = new MyDBHelper(this); Long scannedId = null; try { scannedId = Long.parseLong(value); // idea is to catch the exception after here if it's not a number Log.i(TAG, "HERE"); Cursor cursor = dBHelper.getFindsWithIdentifier(value); Log.i(TAG, cursor.getCount()+""); if (cursor.getCount() == 0) { EditText eText = (EditText) findViewById(R.id.idText); eText.setText(value); } else showDialog(NON_UNIQUE_ID); cursor.close(); } catch(NumberFormatException e) { showDialog(NON_NUMERIC_ID); } // if(scannedId>= 1000000000) { // showDialog(TOO_BIG_ID); // break; break; case CAMERA_ACTIVITY: //for existing find: saves image to db when user clicks "attach" rowId = data.getIntExtra("rowId", -1); Bitmap tempImage = (Bitmap) data.getExtras().get("data"); mTempBitmaps.add(tempImage); saveCameraImageAndUri(mFind, mTempBitmaps); List<ContentValues> imageValues = retrieveImagesFromUris(); if (mFind.insertToDB(null, imageValues)) { Utils.showToast(this, R.string.saved_image_to_db); } else { Utils.showToast(this, R.string.save_failed); } displayGallery(mFindId); mTempBitmaps.clear(); break; case NEW_FIND_CAMERA_ACTIVITY: //for new finds: stores temporary images in a list rowId = data.getIntExtra("rowId", -1); tempImage = (Bitmap) data.getExtras().get("data"); mTempBitmaps.add(tempImage); displayGallery(mFindId); break; case IMAGE_VIEW: finish(); break; } } /** * Saves the camera images and associated bitmaps to Media storage and * save's their respective Uri's in aFind, which will save them to Db. * @param aFind the current Find we are creating or editing * @param bm the bitmap from the camera */ private void saveCameraImageAndUri(Find aFind, List<Bitmap> bitmaps) { if (bitmaps.size() == 0) { if(Utils.debug) Log.i(TAG, "No camera images to save ...exiting "); return; } ListIterator<Bitmap> it = bitmaps.listIterator(); while (it.hasNext()) { Bitmap bm = it.next(); ContentValues values = new ContentValues(); values.put(MediaColumns.TITLE, "posit image"); values.put(ImageColumns.BUCKET_DISPLAY_NAME,"posit"); values.put(ImageColumns.IS_PRIVATE, 0); values.put(MediaColumns.MIME_TYPE, "image/jpeg"); Uri imageUri = getContentResolver() .insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); if(Utils.debug) Log.i(TAG, "Saved image uri = " + imageUri.toString()); OutputStream outstream; try { outstream = getContentResolver().openOutputStream(imageUri); bm.compress(Bitmap.CompressFormat.JPEG, 70, outstream); outstream.close(); } catch (Exception e) { if(Utils.debug) Log.i(TAG, "Exception during image save " + e.getMessage()); } // Now create a thumbnail and save it int width = bm.getWidth(); int height = bm.getHeight(); int newWidth = THUMBNAIL_TARGET_SIZE; int newHeight = THUMBNAIL_TARGET_SIZE; float scaleWidth = ((float)newWidth)/width; float scaleHeight = ((float)newHeight)/height; Matrix matrix = new Matrix(); matrix.setScale(scaleWidth, scaleHeight); Bitmap thumbnailImage = Bitmap.createBitmap(bm, 0, 0,width,height,matrix,true); int imageId = Integer.parseInt(imageUri.toString() .substring(Media.EXTERNAL_CONTENT_URI.toString().length()+1)); values = new ContentValues(4); values.put(Images.Thumbnails.KIND, Images.Thumbnails.MINI_KIND); values.put(Images.Thumbnails.IMAGE_ID, imageId); values.put(Images.Thumbnails.HEIGHT, height); values.put(Images.Thumbnails.WIDTH, width); Uri thumbnailUri = getContentResolver() .insert(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, values); try { outstream = getContentResolver().openOutputStream(thumbnailUri); thumbnailImage.compress(Bitmap.CompressFormat.JPEG, 70, outstream); outstream.close(); } catch (Exception e) { if(Utils.debug) Log.i(TAG, "Exception during thumbnail save " + e.getMessage()); } // Save the Uri's // aFind.setImageUri(imageUri); // aFind.setImageThumbnailUri(thumbnailUri); mNewImageUris.add(imageUri); mNewImageThumbnailUris.add(thumbnailUri); } } /** * Queries for images for this Find and shows them in a Gallery at the bottom of the View. * @param id is the rowId of the find */ private void displayGallery(long id) { if (id != 0) { //for existing finds // Select just those images associated with this find. if ((mCursor=mFind.getImages()).getCount()>0) { finishActivity(FindActivity.IMAGE_VIEW); //mCursor = mFind.getImages(); // Returns the Uris of the images from the Posit Db mCursor.moveToFirst(); ImageAdapter adapter = new ImageAdapter(mCursor, this); mGallery.setAdapter(adapter); mGallery.setOnItemClickListener(this); } else { mCursor.close(); Utils.showToast(this, "No images to display."); } } else { //for new finds if (mTempBitmaps.size() > 0) { finishActivity(FindActivity.IMAGE_VIEW); ImageAdapter adapter = new ImageAdapter(this, mTempBitmaps); mGallery.setAdapter(adapter); mGallery.setOnItemClickListener(this); } } } /** * To detect the user clicking on the displayed images. Displays all pictures attached to this * find by creating a new activity that shows */ public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) { if (mFind != null) { try { mCursor.moveToPosition(position); String s = mCursor.getString(mCursor.getColumnIndexOrThrow(getString(R.string.imageUriDB))); if (s != null) { Uri uri = Uri.parse(s); Intent intent = new Intent(Intent.ACTION_VIEW, uri, this, ImageViewActivity.class); intent.putExtra("position",position); intent.putExtra("findId", mFindId); setResult(RESULT_OK,intent); mCursor.close(); startActivityForResult(intent, IMAGE_VIEW); } } catch (Exception e) { Log.e(TAG, e.toString()); } } else { Bitmap bm = mTempBitmaps.get(position); Intent intent = new Intent(this, ImageViewActivity.class); intent.putExtra("position",position); intent.putExtra("findId", mFindId); intent.putExtra("bitmap", bm); startActivity(intent); } } /** * This is another method to try to better handle the always * growing activity stack. I am not sure if this is ever invoked * in the current state of the project. */ @Override public void finishActivityFromChild(Activity child, int requestCode) { super.finishActivityFromChild(child, requestCode); Utils.showToast(this,"YOOOOOOOOO"); if(requestCode==IMAGE_VIEW) finish(); } /** * Returns the current date and time from the Calendar Instance * @return a string representing the current time stamp. */ private String getDateText() { Calendar cal = Calendar.getInstance(); int minute = cal.get(Calendar.MINUTE); String minStr = minute+""; if(minute < 10) minStr = "0" + minute; String dateString = cal.get(Calendar.YEAR) + "/" + cal.get(Calendar.MONTH) + "/" + cal.get(Calendar.DAY_OF_MONTH) + " " + cal.get(Calendar.HOUR_OF_DAY) + ":" + minStr; //if the minute field is only one digit, add a 0 in front of it return dateString; } /** * Invoked by the location service when phone's location changes. */ public void onLocationChanged(Location newLocation) { setCurrentGpsLocation(newLocation); } /** * Resets the GPS location whenever the provider is enabled. */ public void onProviderEnabled(String provider) { setCurrentGpsLocation(null); } /** * Resets the GPS location whenever the provider is disabled. */ public void onProviderDisabled(String provider) { if(Utils.debug) Log.i(TAG, provider + " disabled"); setCurrentGpsLocation(null); } /** * Resets the GPS location whenever the provider status changes. We * don't care about the details. */ public void onStatusChanged(String provider, int status, Bundle extras) { setCurrentGpsLocation(null); } /** * Sends a message to the update handler with either the current location or * the last known location. * @param location is either null or the current location */ private void setCurrentGpsLocation(Location location) { String bestProvider = ""; if (location == null) { mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE); List<String> providers = mLocationManager.getProviders(ENABLED_ONLY); if(Utils.debug) Log.i(TAG, "Enabled providers = " + providers.toString()); bestProvider = mLocationManager.getBestProvider(new Criteria(),ENABLED_ONLY); if (bestProvider != null && bestProvider.length() != 0) { mLocationManager.requestLocationUpdates(bestProvider, 30000, 0, this); // Every 30000 millisecs location = mLocationManager.getLastKnownLocation(bestProvider); } } if(Utils.debug) Log.i(TAG, "Best provider = |" + bestProvider + "|"); try { mLongitude = location.getLongitude(); mLatitude = location.getLatitude(); Message msg = Message.obtain(); msg.what = UPDATE_LOCATION; this.updateHandler.sendMessage(msg); } catch (NullPointerException e) { if(Utils.debug) Log.e(TAG, e.toString()); } } }
package org.voovan.tools; import org.voovan.Global; import org.voovan.tools.log.Logger; import org.voovan.tools.reflect.TReflect; import sun.misc.Cleaner; import java.io.UnsupportedEncodingException; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.nio.ByteBuffer; import java.util.Arrays; public class TByteBuffer { public static Class DIRECT_BYTE_BUFFER_CLASS = ByteBuffer.allocateDirect(0).getClass(); public static Constructor DIRECT_BYTE_BUFFER_CONSTURCTOR = getConsturctor(); static { DIRECT_BYTE_BUFFER_CONSTURCTOR.setAccessible(true); } public static Field addressField = ByteBufferField("address"); public static Field limitField = ByteBufferField("limit"); public static Field capacityField = ByteBufferField("capacity"); public static Field attField = ByteBufferField("att"); public static Field cleanerField = ByteBufferField("cleaner"); private static Constructor getConsturctor(){ try { Constructor constructor = DIRECT_BYTE_BUFFER_CLASS.getDeclaredConstructor(long.class, int.class, Object.class); constructor.setAccessible(true); return constructor; } catch (NoSuchMethodException e) { e.printStackTrace(); } return null; } private static Field ByteBufferField(String fieldName){ try { Field field = TReflect.findField(DIRECT_BYTE_BUFFER_CLASS, fieldName); field.setAccessible(true); return field; } catch (ReflectiveOperationException e) { e.printStackTrace(); } return null; } /** * ByteBuffer * @param capacity * @return ByteBuffer */ protected static ByteBuffer allocateManualReleaseBuffer(int capacity){ try { long address = (TUnsafe.getUnsafe().allocateMemory(capacity)); Deallocator deallocator = new Deallocator(address); ByteBuffer byteBuffer = (ByteBuffer) DIRECT_BYTE_BUFFER_CONSTURCTOR.newInstance(address, capacity, deallocator); Cleaner cleaner = Cleaner.create(byteBuffer, deallocator); cleanerField.set(byteBuffer, cleaner); return byteBuffer; } catch (Exception e) { Logger.error("Create ByteBufferChannel error. ", e); return null; } } /** * , ByteBuffer * @param capacity * @return ByteBuffer */ public static ByteBuffer allocateDirect(int capacity) { if(Global.NO_HEAP_MANUAL_RELEASE) { return allocateManualReleaseBuffer(capacity); } else { return ByteBuffer.allocateDirect(capacity); } } /** * byteBuffer * @param byteBuffer byteBuffer * @param newSize * @return true:, false: */ public static boolean reallocate(ByteBuffer byteBuffer, int newSize) { try { if(!byteBuffer.hasArray()) { if(getAtt(byteBuffer) == null){ throw new UnsupportedOperationException("JDK's ByteBuffer can't reallocate"); } long address = getAddress(byteBuffer); long newAddress = TUnsafe.getUnsafe().reallocateMemory(address, newSize); setAddress(byteBuffer, newAddress); }else{ byte[] hb = byteBuffer.array(); byte[] newHb = Arrays.copyOf(hb, newSize); TReflect.setFieldValue(byteBuffer, "hb", newHb); } capacityField.set(byteBuffer, newSize); return true; }catch (ReflectiveOperationException e){ Logger.error("TByteBuffer.reallocate() Error. ", e); } return false; } /** * Bytebuffer * Bytebuffer.position(), offset * @param byteBuffer byteBuffer * @param offset ByteBuffer.position * @return true:, false: */ public static boolean moveData(ByteBuffer byteBuffer, int offset) { try { if(offset==0){ return true; } if(byteBuffer.limit() == 0){ return true; } int limit = byteBuffer.limit()+offset; int position = byteBuffer.position() + offset; if(position < 0){ return false; } if(limit > byteBuffer.capacity()){ reallocate(byteBuffer, limit); } if(!byteBuffer.hasArray()) { long address = getAddress(byteBuffer); if(address!=0) { long startAddress = address + byteBuffer.position(); long targetAddress = address + position; if (address > targetAddress) { targetAddress = address; } TUnsafe.getUnsafe().copyMemory(startAddress, targetAddress, byteBuffer.remaining()); } }else{ byte[] hb = byteBuffer.array(); System.arraycopy(hb, byteBuffer.position(), hb, position, byteBuffer.remaining()); } limitField.set(byteBuffer, limit); byteBuffer.position(position); return true; }catch (ReflectiveOperationException e){ Logger.error("TByteBuffer.moveData() Error.", e); } return false; } /** * byteBuffer * bytebuffer * @param byteBuffer bytebuffer */ public static void release(ByteBuffer byteBuffer) { if(byteBuffer == null){ return; } if(!Global.NO_HEAP_MANUAL_RELEASE || byteBuffer.getClass() != DIRECT_BYTE_BUFFER_CLASS) { return; } synchronized (byteBuffer) { try { if (byteBuffer != null && !isReleased(byteBuffer)) { Object att = getAtt(byteBuffer); if (att!=null && att.getClass() == Deallocator.class) { long address = getAddress(byteBuffer); if(address!=0) { TUnsafe.getUnsafe().freeMemory(address); setAddress(byteBuffer, 0); } } } } catch (ReflectiveOperationException e) { e.printStackTrace(); } } } /** * * @param byteBuffer * @return true: , false: */ public static boolean isReleased(ByteBuffer byteBuffer){ if(!Global.NO_HEAP_MANUAL_RELEASE || byteBuffer.getClass() != DIRECT_BYTE_BUFFER_CLASS) { return false; } try { return getAddress(byteBuffer) == 0; }catch (ReflectiveOperationException e){ return true; } } /** * ByteBuffer byte * @param bytebuffer ByteBuffer * @return byte */ public static byte[] toArray(ByteBuffer bytebuffer){ if(!bytebuffer.hasArray()) { int oldPosition = bytebuffer.position(); bytebuffer.position(0); int size = bytebuffer.limit(); byte[] buffers = new byte[size]; bytebuffer.get(buffers); bytebuffer.position(oldPosition); return buffers; }else{ return Arrays.copyOfRange(bytebuffer.array(), 0, bytebuffer.limit()); } } /** * Bytebuffer * @param bytebuffer Bytebuffer * @param charset * @return */ public static String toString(ByteBuffer bytebuffer,String charset) { try { return new String(toArray(bytebuffer), charset); } catch (UnsupportedEncodingException e) { Logger.error(charset+" is not supported",e); return null; } } /** * Bytebuffer * @param bytebuffer Bytebuffer * @return */ public static String toString(ByteBuffer bytebuffer) { return toString(bytebuffer, "UTF-8"); } /** * byte * byte * @param byteBuffer Bytebuffer * @param mark byte * @return */ public static int indexOf(ByteBuffer byteBuffer, byte[] mark){ if(byteBuffer.remaining() == 0){ return -1; } int index = -1; int position = byteBuffer.position(); byte[] tmp = new byte[mark.length]; int length = byteBuffer.remaining(); for(int offset = 0; (offset + position <= length - mark.length); offset++){ byteBuffer.position(position + offset); byteBuffer.get(tmp, 0, tmp.length); if(Arrays.equals(mark, tmp)){ index = offset; break; } } byteBuffer.position(position); return index; } /** * * @param byteBuffer bytebuffer * @return */ public static Long getAddress(ByteBuffer byteBuffer) throws ReflectiveOperationException { return (Long) addressField.get(byteBuffer); } /** * * @param byteBuffer bytebuffer * @param address */ public static void setAddress(ByteBuffer byteBuffer, long address) throws ReflectiveOperationException { addressField.set(byteBuffer, address); Object att = getAtt(byteBuffer); if(att!=null && att.getClass() == Deallocator.class){ ((Deallocator) att).setAddress(address); } } /** * * @param byteBuffer bytebuffer * @return */ public static Object getAtt(ByteBuffer byteBuffer) throws ReflectiveOperationException { return attField.get(byteBuffer); } /** * * @param byteBuffer bytebuffer * @param attr */ public static void setAttr(ByteBuffer byteBuffer, Object attr) throws ReflectiveOperationException { attField.set(byteBuffer, attr); } private static class Deallocator implements Runnable { private long address; private int capacity; private Deallocator(long address) { this.address = address; } public void setAddress(long address){ this.address = address; } public void run() { if (this.address == 0) { return; } TUnsafe.getUnsafe().freeMemory(address); address = 0; } } }
package com.ctac.jpmc.game; import java.util.Collection; import java.util.Set; /** * IGrid interface can be used to represent 2D or 3D Grid * */ public interface IGrid { /** * * get all cells of a grid * * @return collection of cells */ public Collection <IGridCell> getCells (); /** * * get a specific grid cell by coordinates * * @param coordinates input coordinates * @return cell or <code>null</code> if there is no such cell */ public IGridCell getCell (int ... coordinates); /** * get Neighbors (horizontal, vertical, and diagonal) * * @param cell cell to analyze * @return set of Neighbors to the specified cell */ public Set<IGridCell> getNeighbors(IGridCell cell); }
package distributed.util; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Properties; /** * Class to store and load system settings. * * @author steffen */ public class SettingsProvider { private static SettingsProvider instance; private Properties props; //TODO Add all needed property tags private static final String USER_NAME = "user.name"; private static final String USER_GROUP = "user.group"; private static final String USER_TYPE = "user.type"; private static final String ROOT_DIR = "dir.root"; private static final String KEY_DIR = "dir.key"; private static final String PUB_KEY = "key.public"; private static final String PRI_KEY = "key.private"; private static final String DB_DIR = "dir.database"; private static final String DB_NAME = "db.name"; public static enum UserType { MODERATOR, USER; } private static final String SETTINGS_FILE = "../Settings.properties"; public synchronized static SettingsProvider getInstance() { if(instance == null) { instance = new SettingsProvider(); } return instance; } private SettingsProvider() { try { File settingsFile = new File(SETTINGS_FILE); settingsFile.createNewFile(); props = new Properties(); BufferedInputStream in = new BufferedInputStream( new FileInputStream(settingsFile)); props.load(in); in.close(); } catch(IOException e) { e.printStackTrace(); } } public void storeUserName(String userName) { props.setProperty(USER_NAME, userName); writePropertyChanges(); } public void storeUserGroup(String userGroup) { props.setProperty(USER_GROUP, userGroup); writePropertyChanges(); } /** * The type of the user. At the moment just moderator or user * are allowed; * * @param userType */ public void storeUserType(UserType userType) { props.setProperty(USER_TYPE, userType.name()); writePropertyChanges(); } public void storeRootDirectory(String rootDirectory) { //check if the root dir is already set. if so all files must be copied. String path = (String) props.get(ROOT_DIR); if(path == null || path.isEmpty()){ props.setProperty(ROOT_DIR, rootDirectory); writePropertyChanges(); } } public String getUserName() { return props.getProperty(USER_NAME, null); } public String getUserGroup() { return props.getProperty(USER_GROUP, null); } public UserType getUserType() { //TODO change the enum to set up with the string parameter String type = props.getProperty(USER_TYPE, null); if(type == null) return null; //TODO Or should client be returned? else if(type.equals("MODERATOR")) return UserType.MODERATOR; else if(type.equals("USER")) return UserType.USER; //This shall be never reached return null; } public String getRootDir() { return props.getProperty(ROOT_DIR, null); } public String getDBDir() { return props.getProperty(DB_DIR, null); } public String getKeyDir() { return props.getProperty(KEY_DIR, null); } public String getPublicKeyName() { return props.getProperty(PUB_KEY, null); } public String getPrivateKeyDir() { return props.getProperty(PRI_KEY, null); } public String getDatabaseName() { return props.getProperty(DB_NAME, null); } public String getCanonicalDatabaseFile() { StringBuilder builder = new StringBuilder(); builder.append(props.getProperty(ROOT_DIR)); builder.append(props.getProperty(DB_DIR)); builder.append(props.getProperty(DB_NAME)); return builder.toString(); //Maybe null builder for gc } private boolean writePropertyChanges() { try { File props = new File(SETTINGS_FILE); OutputStream stream = new FileOutputStream(props); this.props.store(stream, "Settings Change"); return true; } catch(IOException e) { e.printStackTrace(); return false; } } }
package com.huettermann.all; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Message extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String param = request.getParameter("param"); ServletContext context = getServletContext(); if (param == null || param.equals("")) { context.log("No message received:", new IllegalStateException("Missing parameter")); } else { context.log("Here the paramater: " + param); } PrintWriter out = null; try { out = response.getWriter(); out.println("Hello: " + param); out.flush(); out.close(); } catch (IOException io) { io.printStackTrace(); } } }
package com.hastagqq.app; import java.io.IOException; import java.util.List; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONObject; import android.content.Context; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.location.Location; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.util.Log; import android.view.Menu; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.gcm.GoogleCloudMessaging; import com.google.gson.Gson; import com.hastagqq.app.api.BasicApiResponse; import com.hastagqq.app.api.GetNewsApiResponse; import com.hastagqq.app.api.NewsApiClient; import com.hastagqq.app.model.DeviceInfo; import com.hastagqq.app.model.News; import com.hastagqq.app.util.Constants; import com.hastagqq.app.util.DBAdapter; import com.hastagqq.app.util.GPSTracker; import com.hastagqq.app.util.GsonUtil; import com.hastagqq.app.util.HttpUtil; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import android.content.Context; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.database.Cursor; import android.location.Location; import android.os.AsyncTask; import android.os.Bundle; import android.app.Activity; import android.support.v4.app.Fragment; import android.app.ListActivity; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentTransaction; import android.support.v4.widget.SimpleCursorAdapter; import android.util.Log; import android.view.Menu; import android.widget.ListView; import android.widget.Toast; import java.io.IOException; public class MainActivity extends FragmentActivity implements NewsApiClient.GetCallback, NewsApiClient.CreateCallback { private static final String TAG = MainActivity.class.getSimpleName(); private static final String PROPERTY_APP_VERSION = "appVersion"; private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000; public static final String EXTRA_MESSAGE = "message"; public static final String PROPERTY_REG_ID = "registration_id"; private String mRegId; private String mLocation; private GoogleCloudMessaging mGcm; private Fragment mNewsListFragment; private Context mContext; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (!checkPlayServices()) { Toast.makeText(this, R.string.err_no_gcm, Toast.LENGTH_LONG).show(); finish(); return; } else { mGcm = GoogleCloudMessaging.getInstance(this); mContext = getApplicationContext(); mRegId = getRegistrationId(mContext); if (mRegId.isEmpty()) { registerInBackground(); } } GPSTracker gpsTracker = new GPSTracker(MainActivity.this); mLocation = gpsTracker.getCity(); Location location = gpsTracker.getLocation(); if (location != null) Log.d(TAG, "::onCreate() -- " + location.getLatitude() + " - " + location.getLongitude()); // NewsApiClient.createNews(new News("This is the new thing", "asdf", "ortigas", "traffic"), // this); NewsApiClient.getNews("ortigas", this); FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); mNewsListFragment = new NewsListFragment(); ft.replace(R.id.fl_fragment_container, mNewsListFragment, NewsListFragment.TAG_FRAGMENT); ft.commit(); Log.d(TAG, "::onCreate() -- " + location.getLatitude() + " - " + location.getLongitude() + " - " + mLocation); // NewsApiClient.createNews(new News("This is the new thing", "asdf", "Makati City", "traffic"), // this); // NewsApiClient.getNews("Makati City", this); CreateNewsFragment createNewsFragment = new CreateNewsFragment(); Bundle args = new Bundle(); args.putString(CreateNewsFragment.EXTRAS_LOCATION, mLocation); createNewsFragment.setArguments(args); getSupportFragmentManager().beginTransaction().replace(R.id.fl_fragment_container, createNewsFragment).commit(); } @Override protected void onResume() { super.onResume(); if (!checkPlayServices()) { Toast.makeText(this, R.string.err_no_gcm, Toast.LENGTH_LONG).show(); finish(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } private boolean checkPlayServices() { int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this); if (resultCode != ConnectionResult.SUCCESS) { if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) { GooglePlayServicesUtil.getErrorDialog(resultCode, this, PLAY_SERVICES_RESOLUTION_REQUEST).show(); } else { Log.e(TAG, "This device is not supported."); finish(); } return false; } return true; } private String getRegistrationId(Context context) { final SharedPreferences prefs = getGCMPreferences(); String registrationId = prefs.getString(PROPERTY_REG_ID, ""); if (registrationId.isEmpty()) { Log.i(TAG, "Registration not found."); return ""; } int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE); int currentVersion = getAppVersion(context); if (registeredVersion != currentVersion) { Log.i(TAG, "App version changed."); return ""; } return registrationId; } private static int getAppVersion(Context context) { try { PackageInfo packageInfo = context.getPackageManager() .getPackageInfo(context.getPackageName(), 0); return packageInfo.versionCode; } catch (PackageManager.NameNotFoundException e) { // should never happen throw new RuntimeException("Could not get package name: " + e); } } private SharedPreferences getGCMPreferences() { return getSharedPreferences(MainActivity.class.getSimpleName(), Context.MODE_PRIVATE); } private void registerInBackground() { new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(Void... params) { String msg; try { if (mGcm == null) { mGcm = GoogleCloudMessaging.getInstance(MainActivity.this); } mRegId = mGcm.register(Constants.SENDER_ID); msg = "Device registered, registration ID=" + mRegId; sendRegistrationIdToBackend(); storeRegistrationId(MainActivity.this, mRegId); } catch (IOException ex) { msg = "Error :" + ex.getMessage(); } return msg; } @Override protected void onPostExecute(String msg) { // TODO } }.execute(null, null, null); } private void sendRegistrationIdToBackend() { HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(Constants.HOST + Constants.DEVICE); Gson defaultGsonParser = GsonUtil.getDefaultGsonParser(); DeviceInfo deviceInfo = new DeviceInfo(mRegId, mLocation); Log.d(TAG, "::sendRegistrationIdToBackend() -- payload " + defaultGsonParser.toJson(deviceInfo)); try { httpPost.setEntity(new StringEntity(defaultGsonParser.toJson(deviceInfo))); HttpResponse response = httpClient.execute(httpPost); BasicApiResponse basicApiResponse = HttpUtil.parseBasicApiResponse(response); Log.d(TAG, "::sendRegistrationIdToBackend() -- " + defaultGsonParser.toJson(basicApiResponse)); } catch (IOException e) { Log.e(TAG, "::postData() -- ERROR: " + e.getMessage()); } } private void storeRegistrationId(Context context, String regId) { final SharedPreferences prefs = getGCMPreferences(); int appVersion = getAppVersion(context); SharedPreferences.Editor editor = prefs.edit(); editor.putString(PROPERTY_REG_ID, regId); editor.putInt(PROPERTY_APP_VERSION, appVersion); editor.commit(); } @Override public void onGetNewsComplete(GetNewsApiResponse apiResponse) { Log.d(TAG, "::onGetNewsComplete() -- START"); /*DBAdapter db = new DBAdapter(MainActivity.this); db.open(); for (int i = 0; i < 10; i++) { long id = db.inserContact("test context " + i, "test category " + i, i, "ortigas", "test title " + i); Log.d(TAG, "::onGetNewsComplete() -- id = " + id); } db.close();*/ if (apiResponse.getNewsItems() == null) return; List<News> newss = apiResponse.getNewsItems(); Log.d(TAG, "::onGetNewsComplete() -- newss size = " + newss.size()); if (!newss.isEmpty()) { for (News news : newss) { Log.d(TAG, "::onGetNewsComplete() -- location = " + news.getLocation()); } } /*DBAdapter db = new DBAdapter(MainActivity.this); db.open(); Cursor c = db.getAllNews(); if (c.moveToFirst()) { do { Log.d(TAG, "::onGetNewsComplete() -- id = " + c.getString(c.getColumnIndex(DBAdapter.KEY_ROWID)) + ", location = " + c.getString(c.getColumnIndex(DBAdapter.KEY_LOCATION)) + ", content = " + c.getString(c.getColumnIndex(DBAdapter.KEY_CONTENT))); } while (c.moveToNext()); }*/ Log.d(TAG, "::onGetNewsComplete() -- END"); } @Override public void onCreateNewsComplete(BasicApiResponse apiResponse) { Log.d(TAG, "::onCreateNewsComplete() -- START"); Log.d(TAG, "::onCreateNewsComplete() -- " + apiResponse); Log.d(TAG, "::onCreateNewsComplete() -- END"); } }
package com.upinion.CouchBase; import android.content.Intent; import android.content.Context; import com.couchbase.lite.Document; import com.couchbase.lite.SavedRevision; import com.couchbase.lite.Mapper; import com.couchbase.lite.Query; import com.couchbase.lite.QueryEnumerator; import com.couchbase.lite.QueryRow; import com.couchbase.lite.Reducer; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContext; import com.facebook.react.bridge.Callback; import com.facebook.react.bridge.Promise; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.ReadableNativeArray; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.ReadableNativeMap; import com.facebook.react.bridge.ReadableType; import com.facebook.react.bridge.WritableArray; import com.facebook.react.bridge.WritableMap; import com.facebook.react.bridge.WritableNativeMap; import com.facebook.react.common.JavascriptException; import com.facebook.react.modules.core.DeviceEventManagerModule; import com.couchbase.lite.android.AndroidContext; import com.couchbase.lite.CouchbaseLiteException; import com.couchbase.lite.Database; import com.couchbase.lite.DocumentChange; import com.couchbase.lite.Manager; import com.couchbase.lite.replicator.Replication; import com.couchbase.lite.listener.LiteListener; import com.couchbase.lite.listener.LiteServlet; import com.couchbase.lite.listener.Credentials; import com.couchbase.lite.router.URLStreamHandlerFactory; import com.couchbase.lite.View; import com.couchbase.lite.javascript.JavaScriptViewCompiler; import com.couchbase.lite.util.Log; import com.couchbase.lite.auth.Authenticator; import com.couchbase.lite.auth.AuthenticatorFactory; import com.couchbase.lite.replicator.RemoteRequestResponseException; import com.couchbase.lite.internal.RevisionInternal; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.List; import java.util.HashMap; import java.io.IOException; import java.net.URL; import java.util.regex.Matcher; import java.util.regex.Pattern; public class CouchBase extends ReactContextBaseJavaModule { private ReactApplicationContext context; private Manager managerServer; private boolean initFailed = false; private int listenPort; protected Boolean isDebug = false; private static final String PUSH_EVENT_KEY = "couchBasePushEvent"; private static final String PULL_EVENT_KEY = "couchBasePullEvent"; private static final String DB_EVENT_KEY = "couchBaseDBEvent"; private static final String AUTH_ERROR_KEY = "couchBaseAuthError"; private static final String OFFLINE_KEY = "couchBaseOffline"; private static final String ONLINE_KEY = "couchBaseOnline"; private static final String NOT_FOUND_KEY = "couchBaseNotFound"; public static final String TAG = "CouchBase"; /** * Constructor for the Native Module * @param reactContext React context object to comunicate with React-native */ public CouchBase(ReactApplicationContext reactContext) { super(reactContext); this.context = reactContext; // Register the JavaScript view compiler View.setCompiler(new JavaScriptViewCompiler()); } /** * Returns the name of this module in React-native (javascript) */ @Override public String getName() { return TAG; } /** * Returns constants of this module in React-native to share (javascript) */ @Override public Map<String, Object> getConstants() { final Map<String, Object> constants = new HashMap<>(); constants.put("PUSH", PUSH_EVENT_KEY); constants.put("PULL", PULL_EVENT_KEY); constants.put("DBChanged", DB_EVENT_KEY); constants.put("AuthError", AUTH_ERROR_KEY); constants.put("Offline", OFFLINE_KEY); constants.put("Online", ONLINE_KEY); constants.put("NotFound", NOT_FOUND_KEY); return constants; } /** * Function to be shared to React-native, it starts a couchbase manager * @param listen_port Integer port to start server * @param userLocal String user for local server * @param passwordLocal String password for local server * @param databaseLocal String database for local server * @param onEnd Callback function to call when finish */ @ReactMethod public void serverManager(Callback onEnd) { try { this.managerServer = startCBLite(); if(onEnd != null) onEnd.invoke(); } catch (Exception e) { throw new JavascriptException(e.getMessage()); } } /** * Function to be shared to React-native, it starts a local couchbase server * @param listen_port Integer port to start server * @param userLocal String user for local server * @param passwordLocal String password for local server * @param databaseLocal String database for local server * @param onEnd Callback function to call when finish */ @ReactMethod public void serverLocal(Integer listen_port, String userLocal, String passwordLocal, Callback onEnd) { startServer(listen_port, userLocal, passwordLocal); if(onEnd != null) onEnd.invoke(this.listenPort); } /** * Function to be shared to React-native, it starts a local couchbase server and syncs with remote * @param listen_port Integer port to start server * @param userLocal String user for local server * @param passwordLocal String password for local server * @param databaseLocal String database for local server * @param remoteURL String URL to remote couchbase * @param remoteUser String user for remote server * @param remotePassword String password for remote server * @param events Boolean activate the events for push and pull * @param onEnd Callback function to call when finish */ @ReactMethod public void serverLocalRemote(Integer listen_port, String userLocal, String passwordLocal, String databaseLocal, String remoteURL, String remoteUser, String remotePassword, Boolean events, Callback onEnd) { startServer(listen_port, userLocal, passwordLocal); Manager ss = this.managerServer; if(!(databaseLocal != null && remoteURL != null && remoteUser != null && remotePassword != null)) throw new JavascriptException("CouchBase Server bad arguments"); try { URL url = new URL(remoteURL); Database db = ss.getExistingDatabase(databaseLocal); final Replication push = db.createPushReplication(url); final Replication pull = db.createPullReplication(url); pull.setContinuous(true); push.setContinuous(true); Authenticator basicAuthenticator = AuthenticatorFactory.createBasicAuthenticator(remoteUser, remotePassword); pull.setAuthenticator(basicAuthenticator); push.setAuthenticator(basicAuthenticator); if (events) { push.addChangeListener(new Replication.ChangeListener() { @Override public void changed(Replication.ChangeEvent event) { boolean offline = push.getStatus() == Replication.ReplicationStatus.REPLICATION_OFFLINE; if (offline) { WritableMap eventOffline = Arguments.createMap(); eventOffline.putString("databaseName", event.getSource().getLocalDatabase().getName()); sendEvent(context, OFFLINE_KEY, eventOffline); } else { WritableMap eventOnline = Arguments.createMap(); eventOnline.putString("databaseName", event.getSource().getLocalDatabase().getName()); sendEvent(context, ONLINE_KEY, eventOnline); } if (event.getError() != null) { Throwable lastError = event.getError(); if (lastError instanceof RemoteRequestResponseException) { RemoteRequestResponseException exception = (RemoteRequestResponseException) lastError; if (exception.getCode() == 401) { // Authentication error WritableMap eventError = Arguments.createMap(); eventError.putString("databaseName", event.getSource().getLocalDatabase().getName()); sendEvent(context, AUTH_ERROR_KEY, eventError); } else if (exception.getCode() == 404){ // Database not found error WritableMap eventError = Arguments.createMap(); eventError.putString("databaseName", event.getSource().getLocalDatabase().getName()); sendEvent(context, NOT_FOUND_KEY, eventError); } } } else { WritableMap eventM = Arguments.createMap(); eventM.putString("databaseName", event.getSource().getLocalDatabase().getName()); eventM.putString("changesCount", String.valueOf(event.getSource().getCompletedChangesCount())); eventM.putString("totalChanges", String.valueOf(event.getSource().getChangesCount())); sendEvent(context, PUSH_EVENT_KEY, eventM); } } }); pull.addChangeListener(new Replication.ChangeListener() { @Override public void changed(Replication.ChangeEvent event) { boolean offline = pull.getStatus() == Replication.ReplicationStatus.REPLICATION_OFFLINE; if (offline) { WritableMap eventOffline = Arguments.createMap(); eventOffline.putString("databaseName", event.getSource().getLocalDatabase().getName()); sendEvent(context, OFFLINE_KEY, eventOffline); } else { WritableMap eventOnline = Arguments.createMap(); eventOnline.putString("databaseName", event.getSource().getLocalDatabase().getName()); sendEvent(context, ONLINE_KEY, eventOnline); } if (event.getError() != null) { Throwable lastError = event.getError(); if (lastError instanceof RemoteRequestResponseException) { RemoteRequestResponseException exception = (RemoteRequestResponseException) lastError; if (exception.getCode() == 401) { // Authentication error WritableMap eventError = Arguments.createMap(); eventError.putString("databaseName", event.getSource().getLocalDatabase().getName()); sendEvent(context, AUTH_ERROR_KEY, eventError); } else if (exception.getCode() == 404){ // Database not found error WritableMap eventError = Arguments.createMap(); eventError.putString("databaseName", event.getSource().getLocalDatabase().getName()); sendEvent(context, NOT_FOUND_KEY, eventError); } } } else { WritableMap eventM = Arguments.createMap(); eventM.putString("databaseName", event.getSource().getLocalDatabase().getName()); eventM.putString("changesCount", String.valueOf(event.getSource().getCompletedChangesCount())); eventM.putString("totalChanges", String.valueOf(event.getSource().getChangesCount())); sendEvent(context, PULL_EVENT_KEY, eventM); } } }); db.addChangeListener(new Database.ChangeListener() { @Override public void changed(Database.ChangeEvent event) { for (DocumentChange dc : event.getChanges()) { WritableMap eventM = Arguments.createMap(); eventM.putString("databaseName", event.getSource().getName()); eventM.putString("id", dc.getDocumentId()); sendEvent(context, DB_EVENT_KEY, eventM); } } }); } push.start(); pull.start(); if (onEnd != null) onEnd.invoke(this.listenPort); }catch(Exception e){ throw new JavascriptException(e.getMessage()); } } /** * Function to be shared to React-native, it starts already created local db syncing with remote * @param databaseLocal String database for local server * @param remoteURL String URL to remote couchbase * @param remoteUser String user for remote server * @param remotePassword String password for remote server * @param events Boolean activate the events for push and pull * @param onEnd Callback function to call when finish */ @ReactMethod public void serverRemote(String databaseLocal, String remoteURL, String remoteUser, String remotePassword, Boolean events, Callback onEnd) { Manager ss = this.managerServer; if(ss == null) throw new JavascriptException("CouchBase local server needs to be started first"); if(!(databaseLocal != null && remoteURL != null && remoteUser != null && remotePassword != null)) throw new JavascriptException("CouchBase Server bad arguments"); try { URL url = new URL(remoteURL); Database db = ss.getExistingDatabase(databaseLocal); final Replication push = db.createPushReplication(url); final Replication pull = db.createPullReplication(url); pull.setContinuous(true); push.setContinuous(true); Authenticator basicAuthenticator = AuthenticatorFactory.createBasicAuthenticator(remoteUser, remotePassword); pull.setAuthenticator(basicAuthenticator); push.setAuthenticator(basicAuthenticator); if (events) { push.addChangeListener(new Replication.ChangeListener() { @Override public void changed(Replication.ChangeEvent event) { boolean offline = push.getStatus() == Replication.ReplicationStatus.REPLICATION_OFFLINE; if (offline) { WritableMap eventOffline = Arguments.createMap(); eventOffline.putString("databaseName", event.getSource().getLocalDatabase().getName()); sendEvent(context, OFFLINE_KEY, eventOffline); } else { WritableMap eventOnline = Arguments.createMap(); eventOnline.putString("databaseName", event.getSource().getLocalDatabase().getName()); sendEvent(context, ONLINE_KEY, eventOnline); } if (event.getError() != null) { Throwable lastError = event.getError(); if (lastError instanceof RemoteRequestResponseException) { RemoteRequestResponseException exception = (RemoteRequestResponseException) lastError; if (exception.getCode() == 401) { // Authentication error WritableMap eventError = Arguments.createMap(); eventError.putString("databaseName", event.getSource().getLocalDatabase().getName()); sendEvent(context, AUTH_ERROR_KEY, eventError); }else if (exception.getCode() == 404){ // Database not found error WritableMap eventError = Arguments.createMap(); eventError.putString("databaseName", event.getSource().getLocalDatabase().getName()); sendEvent(context, NOT_FOUND_KEY, eventError); } } } else { WritableMap eventM = Arguments.createMap(); eventM.putString("databaseName", event.getSource().getLocalDatabase().getName()); eventM.putString("changesCount", String.valueOf(event.getSource().getCompletedChangesCount())); eventM.putString("totalChanges", String.valueOf(event.getSource().getChangesCount())); sendEvent(context, PUSH_EVENT_KEY, eventM); } } }); pull.addChangeListener(new Replication.ChangeListener() { @Override public void changed(Replication.ChangeEvent event) { boolean offline = pull.getStatus() == Replication.ReplicationStatus.REPLICATION_OFFLINE; if (offline) { WritableMap eventOffline = Arguments.createMap(); eventOffline.putString("databaseName", event.getSource().getLocalDatabase().getName()); sendEvent(context, OFFLINE_KEY, eventOffline); } else { WritableMap eventOnline = Arguments.createMap(); eventOnline.putString("databaseName", event.getSource().getLocalDatabase().getName()); sendEvent(context, ONLINE_KEY, eventOnline); } if (event.getError() != null) { Throwable lastError = event.getError(); if (lastError instanceof RemoteRequestResponseException) { RemoteRequestResponseException exception = (RemoteRequestResponseException) lastError; if (exception.getCode() == 401) { // Authentication error WritableMap eventError = Arguments.createMap(); eventError.putString("databaseName", event.getSource().getLocalDatabase().getName()); sendEvent(context, AUTH_ERROR_KEY, eventError); }else if (exception.getCode() == 404){ // Database not found error WritableMap eventError = Arguments.createMap(); eventError.putString("databaseName", event.getSource().getLocalDatabase().getName()); sendEvent(context, NOT_FOUND_KEY, eventError); } } } else { WritableMap eventM = Arguments.createMap(); eventM.putString("databaseName", event.getSource().getLocalDatabase().getName()); eventM.putString("changesCount", String.valueOf(event.getSource().getCompletedChangesCount())); eventM.putString("totalChanges", String.valueOf(event.getSource().getChangesCount())); sendEvent(context, PULL_EVENT_KEY, eventM); } } }); db.addChangeListener(new Database.ChangeListener() { @Override public void changed(Database.ChangeEvent event) { for (DocumentChange dc : event.getChanges()) { WritableMap eventM = Arguments.createMap(); eventM.putString("databaseName", event.getSource().getName()); eventM.putString("id", dc.getDocumentId()); sendEvent(context, DB_EVENT_KEY, eventM); } } }); } push.start(); pull.start(); if (onEnd != null) onEnd.invoke(); }catch(Exception e){ throw new JavascriptException(e.getMessage()); } } /** * Function to be shared to React-native, it adds a listener for change events in database * @param databaseLocal String database for local server * @param promise Promise Promise to be returned to the JavaScript engine. */ @ReactMethod public void databaseChangeEvents(String databaseLocal, Promise promise) { Manager ss = this.managerServer; if(ss == null) throw new JavascriptException("CouchBase local server needs to be started first"); if(!(databaseLocal != null)) throw new JavascriptException("CouchBase Server bad arguments"); try { Database db = ss.getExistingDatabase(databaseLocal); db.addChangeListener(new Database.ChangeListener() { @Override public void changed(Database.ChangeEvent event) { for (DocumentChange dc : event.getChanges()) { WritableMap eventM = Arguments.createMap(); eventM.putString("databaseName", event.getSource().getName()); eventM.putString("id", dc.getDocumentId()); sendEvent(context, DB_EVENT_KEY, eventM); } } }); promise.resolve(null); }catch(Exception e){ promise.reject("NOT_OPENED", e); } } /** * Function to be shared to React-native, it starts already created local db pull replication from remote * @param databaseLocal String database for local server * @param remoteURL String URL to remote couchbase * @param remoteUser String user for remote server * @param remotePassword String password for remote server * @param events Boolean activate the events for pull * @param promise Promise Promise to be returned to the JavaScript engine. */ @ReactMethod public void serverRemotePull(String databaseLocal, String remoteURL, String remoteUser, String remotePassword, Boolean events, Promise promise) { Manager ss = this.managerServer; if(ss == null) throw new JavascriptException("CouchBase local server needs to be started first"); if(!(databaseLocal != null && remoteURL != null && remoteUser != null && remotePassword != null)) throw new JavascriptException("CouchBase Server bad arguments"); try { URL url = new URL(remoteURL); Database db = ss.getExistingDatabase(databaseLocal); final Replication pull = db.createPullReplication(url); pull.setContinuous(true); Authenticator basicAuthenticator = AuthenticatorFactory.createBasicAuthenticator(remoteUser, remotePassword); pull.setAuthenticator(basicAuthenticator); if (events) { pull.addChangeListener(new Replication.ChangeListener() { @Override public void changed(Replication.ChangeEvent event) { boolean offline = pull.getStatus() == Replication.ReplicationStatus.REPLICATION_OFFLINE; if (offline) { WritableMap eventOffline = Arguments.createMap(); eventOffline.putString("databaseName", event.getSource().getLocalDatabase().getName()); sendEvent(context, OFFLINE_KEY, eventOffline); } else { WritableMap eventOnline = Arguments.createMap(); eventOnline.putString("databaseName", event.getSource().getLocalDatabase().getName()); sendEvent(context, ONLINE_KEY, eventOnline); } if (event.getError() != null) { Throwable lastError = event.getError(); if (lastError instanceof RemoteRequestResponseException) { RemoteRequestResponseException exception = (RemoteRequestResponseException) lastError; if (exception.getCode() == 401) { // Authentication error WritableMap eventError = Arguments.createMap(); eventError.putString("databaseName", event.getSource().getLocalDatabase().getName()); sendEvent(context, AUTH_ERROR_KEY, eventError); }else if (exception.getCode() == 404){ // Database not found error WritableMap eventError = Arguments.createMap(); eventError.putString("databaseName", event.getSource().getLocalDatabase().getName()); sendEvent(context, NOT_FOUND_KEY, eventError); } } } else { WritableMap eventM = Arguments.createMap(); eventM.putString("databaseName", event.getSource().getLocalDatabase().getName()); eventM.putString("changesCount", String.valueOf(event.getSource().getCompletedChangesCount())); eventM.putString("totalChanges", String.valueOf(event.getSource().getChangesCount())); sendEvent(context, PULL_EVENT_KEY, eventM); } } }); } pull.start(); promise.resolve(null); }catch(Exception e){ promise.reject("NOT_OPENED", e); } } /** * Function to be shared to React-native, it starts already created local db push replication to remote * @param databaseLocal String database for local server * @param remoteURL String URL to remote couchbase * @param remoteUser String user for remote server * @param remotePassword String password for remote server * @param events Boolean activate the events for push * @param promise Promise Promise to be returned to the JavaScript engine. */ @ReactMethod public void serverRemotePush(String databaseLocal, String remoteURL, String remoteUser, String remotePassword, Boolean events, Promise promise) { Manager ss = this.managerServer; if(ss == null) throw new JavascriptException("CouchBase local server needs to be started first"); if(!(databaseLocal != null && remoteURL != null && remoteUser != null && remotePassword != null)) throw new JavascriptException("CouchBase Server bad arguments"); try { URL url = new URL(remoteURL); Database db = ss.getExistingDatabase(databaseLocal); final Replication push = db.createPushReplication(url); push.setContinuous(true); Authenticator basicAuthenticator = AuthenticatorFactory.createBasicAuthenticator(remoteUser, remotePassword); push.setAuthenticator(basicAuthenticator); if (events) { push.addChangeListener(new Replication.ChangeListener() { @Override public void changed(Replication.ChangeEvent event) { boolean offline = push.getStatus() == Replication.ReplicationStatus.REPLICATION_OFFLINE; if (offline) { WritableMap eventOffline = Arguments.createMap(); eventOffline.putString("databaseName", event.getSource().getLocalDatabase().getName()); sendEvent(context, OFFLINE_KEY, eventOffline); } else { WritableMap eventOnline = Arguments.createMap(); eventOnline.putString("databaseName", event.getSource().getLocalDatabase().getName()); sendEvent(context, ONLINE_KEY, eventOnline); } if (event.getError() != null) { Throwable lastError = event.getError(); if (lastError instanceof RemoteRequestResponseException) { RemoteRequestResponseException exception = (RemoteRequestResponseException) lastError; if (exception.getCode() == 401) { // Authentication error WritableMap eventError = Arguments.createMap(); eventError.putString("databaseName", event.getSource().getLocalDatabase().getName()); sendEvent(context, AUTH_ERROR_KEY, eventError); }else if (exception.getCode() == 404){ // Database not found error WritableMap eventError = Arguments.createMap(); eventError.putString("databaseName", event.getSource().getLocalDatabase().getName()); sendEvent(context, NOT_FOUND_KEY, eventError); } } } else { WritableMap eventM = Arguments.createMap(); eventM.putString("databaseName", event.getSource().getLocalDatabase().getName()); eventM.putString("changesCount", String.valueOf(event.getSource().getCompletedChangesCount())); eventM.putString("totalChanges", String.valueOf(event.getSource().getChangesCount())); sendEvent(context, PUSH_EVENT_KEY, eventM); } } }); } push.start(); promise.resolve(null); }catch(Exception e){ promise.reject("NOT_OPENED", e); } } /** * Function to be shared to React-native, compacts an already created local database * @param databaseLocal String database for local server */ @ReactMethod public void compact(String databaseLocal) { Manager ss = this.managerServer; if(ss == null) throw new JavascriptException("CouchBase local server needs to be started first"); if(databaseLocal == null) throw new JavascriptException("CouchBase Server bad arguments"); try { Database db = ss.getExistingDatabase(databaseLocal); db.compact(); }catch(Exception e){ throw new JavascriptException(e.getMessage()); } } /** * Function to be shared with React-native, it restarts push replications in order to check for 404 * @param databaseLocal String database for local server * */ @ReactMethod public void refreshReplication(String databaseLocal) { Manager ss = this.managerServer; if(ss == null) throw new JavascriptException("CouchBase local server needs to be started first"); if(databaseLocal == null) throw new JavascriptException("CouchBase Server bad arguments"); try { Database db = ss.getExistingDatabase(databaseLocal); if (db != null) { List<Replication> replications = db.getActiveReplications(); for (Replication replication : replications) { if (!replication.isPull() && replication.isRunning() && replication.getStatus() == Replication.ReplicationStatus.REPLICATION_IDLE) { replication.restart(); } } } } catch (Exception e){ throw new JavascriptException(e.getMessage()); } } /** * Enable debug log for CBL * @param debug_mode boolean debug module for develop: true for VERBOSE log, false for Default log level. * */ @ReactMethod public void enableLog(boolean debug_mode) { isDebug = new Boolean(debug_mode); } /** * Private functions to create couchbase server */ private void startServer(Integer listen_port, String userLocal, String passwordLocal) throws JavascriptException{ if(!(listen_port != null && userLocal != null && passwordLocal != null)) throw new JavascriptException("CouchBase Server bad arguments"); Manager server; try { Credentials allowedCredentials = new Credentials(userLocal, passwordLocal); URLStreamHandlerFactory.registerSelfIgnoreError(); server = startCBLite(); listenPort = startCBLListener( listen_port, server, allowedCredentials); } catch (Exception e) { throw new JavascriptException(e.getMessage()); } this.managerServer = server; } private Manager startCBLite() throws IOException { if (this.isDebug){ Manager.enableLogging(TAG, Log.VERBOSE); Manager.enableLogging(Log.TAG, Log.VERBOSE); Manager.enableLogging(Log.TAG_SYNC, Log.VERBOSE); Manager.enableLogging(Log.TAG_SYNC_ASYNC_TASK, Log.VERBOSE); Manager.enableLogging(Log.TAG_BATCHER, Log.VERBOSE); Manager.enableLogging(Log.TAG_QUERY, Log.VERBOSE); Manager.enableLogging(Log.TAG_VIEW, Log.VERBOSE); Manager.enableLogging(Log.TAG_CHANGE_TRACKER, Log.VERBOSE); Manager.enableLogging(Log.TAG_BLOB_STORE, Log.VERBOSE); Manager.enableLogging(Log.TAG_DATABASE, Log.VERBOSE); Manager.enableLogging(Log.TAG_LISTENER, Log.VERBOSE); Manager.enableLogging(Log.TAG_MULTI_STREAM_WRITER, Log.VERBOSE); Manager.enableLogging(Log.TAG_REMOTE_REQUEST, Log.VERBOSE); Manager.enableLogging(Log.TAG_ROUTER, Log.VERBOSE); } return new Manager( new AndroidContext(this.context), Manager.DEFAULT_OPTIONS); } private int startCBLListener(int listenPort, Manager manager, Credentials allowedCredentials) { LiteListener listener = new LiteListener(manager, listenPort, allowedCredentials); int boundPort = listener.getListenPort(); Thread thread = new Thread(listener); thread.start(); return boundPort; } /** * Function to send: push pull events */ private void sendEvent(ReactContext reactContext, String eventName, WritableMap params) { reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) .emit(eventName, params); } private static WritableMap mapToWritableMap(Map <String, Object> map) { WritableMap wm = Arguments.createMap(); for (Map.Entry<String, Object> entry : map.entrySet()) { if (entry.getValue() instanceof Boolean) { wm.putBoolean(entry.getKey(), ((Boolean) entry.getValue()).booleanValue()); } else if (entry.getValue() instanceof Integer) { wm.putInt(entry.getKey(), ((Integer) entry.getValue()).intValue()); } else if (entry.getValue() instanceof Double) { wm.putDouble(entry.getKey(), ((Double) entry.getValue()).doubleValue()); } else if (entry.getValue() instanceof Float){ wm.putDouble(entry.getKey(), ((Float) entry.getValue()).doubleValue()); } else if (entry.getValue() instanceof Long){ wm.putDouble(entry.getKey(), ((Long) entry.getValue()).doubleValue()); } else if (entry.getValue() instanceof String) { wm.putString(entry.getKey(), ((String) entry.getValue())); } else if (entry.getValue() instanceof LinkedHashMap) { wm.putMap(entry.getKey(), CouchBase.mapToWritableMap((LinkedHashMap) entry.getValue())); } else if (entry.getValue() instanceof WritableMap) { wm.putMap(entry.getKey(), (WritableMap) entry.getValue()); } else if (entry.getValue() instanceof WritableArray) { wm.putArray(entry.getKey(), (WritableArray) entry.getValue()); } else if (entry.getValue() instanceof ArrayList) { wm.putArray(entry.getKey(), CouchBase.arrayToWritableArray(((ArrayList) entry.getValue()).toArray())); } else if (entry.getValue() instanceof Object[]) { wm.putArray(entry.getKey(), CouchBase.arrayToWritableArray((Object[]) entry.getValue())); } else { wm.putNull(entry.getKey()); } } return wm; } private static WritableArray arrayToWritableArray(Object[] array) { WritableArray wa = Arguments.createArray(); for (Object o : array) { if (o instanceof Map) { wa.pushMap(CouchBase.mapToWritableMap((Map) o)); } else if (o instanceof WritableMap) { wa.pushMap((WritableMap) o); } else if (o instanceof String) { wa.pushString((String) o); } else if (o instanceof Boolean) { wa.pushBoolean(((Boolean) o).booleanValue()); } else if (o instanceof Double) { wa.pushDouble(((Double) o).doubleValue()); } else if (o instanceof Float) { wa.pushDouble(((Float) o).doubleValue()); } else if (o instanceof Long) { wa.pushDouble(((Long) o).doubleValue()); } else if (o instanceof Integer) { wa.pushInt(((Integer) o).intValue()); } else if (o instanceof WritableArray) { wa.pushArray((WritableArray) o); } else if (o instanceof Object[]) { wa.pushArray(CouchBase.arrayToWritableArray((Object[])o)); } else { wa.pushNull(); } } return wa; } /** * Creates a database. * @param database String Database name. * @param promise Promise Promise to be returned to the JavaScript engine. */ @ReactMethod public void createDatabase(String database, Promise promise) { try { Manager ss = this.managerServer; Database db = ss.getDatabase(database); promise.resolve(null); } catch (CouchbaseLiteException e) { promise.reject("COUCHBASE_ERROR", e); } catch (Exception e) { promise.reject("NOT_OPENED", e); } } /** * Destroys a database. * @param database String Database name. * @param promise Promise Promise to be returned to the JavaScript engine. */ @ReactMethod public void destroyDatabase(String database, Promise promise) { Manager ss = this.managerServer; try { Database db = ss.getExistingDatabase(database); db.delete(); promise.resolve(null); } catch (CouchbaseLiteException e) { promise.reject("COUCHBASE_ERROR", e); } catch (Exception e) { promise.reject("NOT_OPENED", e); } } /** * Gets an existing document from the database. * @param database String Database name. * @param docId String Document id. * @param promise Promise Promise to be returned to the JavaScript engine. */ @ReactMethod public void getDocument(String database, String docId, Promise promise) { Manager ss = this.managerServer; Database db = null; try { db = ss.getExistingDatabase(database); Map<String, Object> properties = null; Pattern pattern = Pattern.compile("^_local/(.+)"); Matcher matcher = pattern.matcher(docId); // If it matches, it is a local document. if (matcher.find()) { String localDocId = matcher.group(1); properties = db.getExistingLocalDocument(localDocId); } else { Document doc = db.getExistingDocument(docId); if (doc != null) { properties = doc.getCurrentRevision().getProperties(); } } if (properties != null) { WritableMap result = CouchBase.mapToWritableMap(properties); promise.resolve(result); } else { promise.resolve(Arguments.createMap()); } } catch (CouchbaseLiteException e) { promise.reject("COUCHBASE_ERROR", e); } catch (Exception e) { promise.reject("NOT_OPENED", e); } } /** * Gets all the existing documents from the database. * @param database String Database name. * @param docIds ReadableArray JavaScript array containing the keys. * @param promise Promise Promise to be returned to the JavaScript engine. */ @ReactMethod public void getAllDocuments(String database, ReadableArray docIds, Promise promise) { Manager ss = this.managerServer; Database db = null; try { db = ss.getExistingDatabase(database); WritableArray results = Arguments.createArray(); if (docIds == null || docIds.size() == 0) { Query query = db.createAllDocumentsQuery(); query.setAllDocsMode(Query.AllDocsMode.ALL_DOCS); Iterator<QueryRow> it = query.run(); while (it.hasNext()) { QueryRow row = it.next(); WritableMap m = Arguments.createMap(); WritableMap m2 = Arguments.createMap(); m2.putString("rev", row.getDocumentRevisionId()); m.putString("key", String.valueOf(row.getKey())); m.putString("_id", String.valueOf(row.getKey())); m.putMap("doc", CouchBase.mapToWritableMap((Map) row.getValue())); m.putMap("value", m2); results.pushMap(m); } } else { Pattern pattern = Pattern.compile("^_local/(.+)"); for (int i = 0; i < docIds.size(); i++) { Map<String, Object> properties = null; String docId = docIds.getString(i); Matcher matcher = pattern.matcher(docId); WritableMap m = Arguments.createMap(); // If it matches, it is a local document. if (matcher.find()) { String localDocId = matcher.group(1); properties = db.getExistingLocalDocument(localDocId); } else { Document doc = db.getExistingDocument(docId); if (doc != null) { properties = doc.getProperties(); WritableMap m2 = Arguments.createMap(); m2.putString("rev", doc.getCurrentRevisionId()); m.putMap("value", m2); } } if (properties != null) { m.putString("key", String.valueOf(docId)); m.putString("_id", String.valueOf(docId)); m.putMap("doc", CouchBase.mapToWritableMap(properties)); results.pushMap(m); } } } WritableMap ret = Arguments.createMap(); ret.putArray("rows", results); ret.putInt("total_rows", results.size()); promise.resolve(ret); } catch (CouchbaseLiteException e) { promise.reject("COUCHBASE_ERROR", e); } catch (Exception e) { promise.reject("NOT_OPENED", e); } } /** * Gets all the documents returned by the given view. * @param database String Database name. * @param design String Design document where the view can be found. * @param viewName String Name of the view to be queried. * @param params ReadableMap JavaScript object containing the extra parameters to pass to the view. * @param docIds ReadableArray JavaScript array containing the keys. * @param forceRebuild Force the rebuild of the view before querying it. * @param promise Promise Promise to be returned to the JavaScript engine. */ @ReactMethod public void getView(String database, String design, String viewName, ReadableMap params, ReadableArray docIds, Promise promise) { Manager ss = managerServer; Database db = null; View view = null; try { db = ss.getExistingDatabase(database); view = db.getExistingView(viewName); if (view == null || (view != null && view.getMap() == null)) { Document viewDoc = db.getExistingDocument("_design/" + design); if (viewDoc == null) { promise.reject("NOT_FOUND", "The document _design/" + design + " could not be found."); return; } Map<String, Object> views = null; try { views = (Map<String, Object>) viewDoc.getProperty("views"); } catch (Exception e) { promise.reject("NOT_FOUND", "The views could not be retrieved.", e); return; } @SuppressWarnings("unchecked") Map<String, Object> viewDefinition = (Map<String, Object>) views.get(viewName); if (viewDefinition == null) { promise.reject("NOT_FOUND", "The view " + viewName + " could not be found."); return; } Mapper mapper = View.getCompiler().compileMap((String) viewDefinition.get("map"), "javascript"); String version = (String)viewDefinition.get("version"); if (mapper == null) { promise.reject("COMPILE_ERROR", "The map function of " + viewName + "could not be compiled."); return; } view = db.getView(viewName); if (viewDefinition.containsKey("reduce")) { Reducer reducer = View.getCompiler().compileReduce((String) viewDefinition.get("reduce"), "javascript"); if (reducer == null) { promise.reject("COMPILE_ERROR", "The reduce function of " + viewName + "could not be compiled."); return; } view.setMapReduce(mapper, reducer, version != null ? version : "1.1"); } else { view.setMap(mapper, version != null ? version : "1.1"); } } else { view.updateIndex(); } Query query = view.createQuery(); if (params != null) { if (params.hasKey("startkey")) { switch (params.getType("startkey")) { case Array: ReadableNativeArray array = (ReadableNativeArray)params.getArray("startkey"); query.setStartKey(array.toArrayList()); break; case String: query.setStartKey(params.getString("startkey")); break; case Number: query.setStartKey(params.getInt("startkey")); break; } } if (params.hasKey("endkey")) { switch (params.getType("startkey")) { case Array: ReadableNativeArray array = (ReadableNativeArray)params.getArray("endkey"); query.setEndKey(array.toArrayList()); break; case String: query.setStartKey(params.getString("endkey")); break; case Number: query.setStartKey(params.getInt("endkey")); break; } } if (params.hasKey("descending")) query.setDescending(params.getBoolean("descending")); if (params.hasKey("limit")) query.setLimit(params.getInt("limit")); if (params.hasKey("skip")) query.setSkip(params.getInt("skip")); if (params.hasKey("group")) query.setGroupLevel(params.getInt("group")); } if (docIds != null && docIds.size() > 0) { List<Object> keys = new ArrayList<Object>(); for (int i = 0; i < docIds.size(); i++) { keys.add(docIds.getString(i).toString()); } query.setKeys(keys); } QueryEnumerator it = query.run(); WritableArray results = Arguments.createArray(); for (int i = 0; i < it.getCount(); i++) { QueryRow row = it.getRow(i); WritableMap m = Arguments.createMap(); m.putString("key", row.getKey() != null ? String.valueOf(row.getKey()) : null); m.putMap("value", CouchBase.mapToWritableMap((Map<String,Object>)row.getValue())); results.pushMap(m); } WritableMap ret = Arguments.createMap(); ret.putArray("rows", results); ret.putInt("offset", params != null && params.hasKey("skip") ? params.getInt("skip") : 0); ret.putInt("total_rows", view.getTotalRows()); if (params != null && params.hasKey("update_seq") && params.getBoolean("update_seq") == true) { ret.putInt("update_seq", Long.valueOf(it.getSequenceNumber()).intValue()); } promise.resolve(ret); } catch (CouchbaseLiteException e) { promise.reject("COUCHBASE_ERROR", e); if (view != null) view.delete(); } catch (Exception e) { promise.reject("NOT_OPENED", e); if (view != null) view.delete(); } } /** * Puts a document in the database. * @param database String Database name. * @param docId String Document id. * @param document Object Document params. * @param promise Promise Promise to be returned to the JavaScript engine. */ @ReactMethod public void putDocument(String database, String docId, ReadableMap document, Promise promise) { Manager ss = this.managerServer; Database db = null; try { db = ss.getExistingDatabase(database); Map<String, Object> properties = ((ReadableNativeMap) document).toHashMap(); Pattern pattern = Pattern.compile("^_local/(.+)"); Matcher matcher = pattern.matcher(docId); // If it matches, it is a local document. if (matcher.find()) { String localDocId = matcher.group(1); db.putLocalDocument(localDocId, properties); promise.resolve(null); } else { Document doc = db.getDocument(docId); if (doc != null) { doc.putProperties(properties); promise.resolve(null); } else { promise.reject("MISSING_DOCUMENT", "Could not create/update document"); } } } catch (CouchbaseLiteException e) { promise.reject("COUCHBASE_ERROR", e); } catch (Exception e) { promise.reject("NOT_OPENED", e); } } }
package uk.co.alt236.easycursor; import java.util.Arrays; import android.database.Cursor; import android.database.CursorWrapper; import android.util.Log; public class EasyCursor extends CursorWrapper{ private static final String TAG = "EasyCursor"; private final static int COLUMN_NOT_PRESENT = -1; public static final String DEFAULT_STRING = null; public static final int DEFAULT_INT = 0; public static final long DEFAULT_LONG = 0L; public static final float DEFAULT_FLOAT = 0.0F; public static final double DEFAULT_DOUBLE = 0.0D; public static final boolean DEFAULT_BOOLEAN = false; private final EasyQueryModel mModel; private boolean mDebugEnabled; public EasyCursor(final Cursor cursor){ super(cursor); mModel = null; } public EasyCursor(final Cursor cursor, final EasyQueryModel model) { super(cursor); mModel = model; } /** * Performs the necessary calculations to assess the value of a boolean * * The default logic used to calculate the boolean is the following: * if (value_as_int == 1) ? true : false; * * @param columnNumber the number of the column containing the value to assess * @return */ protected boolean calcBoolean(int columnNumber){ final int value = getInt(columnNumber); return (value == 1) ? true : false; } public byte[] getBlob(final String columnName) { return getBlob(getColumnIndexOrThrow(columnName)); } public boolean getBoolean(final String columnName) { final int columnNumber = getColumnIndexOrThrow(columnName); return calcBoolean(columnNumber); } public double getDouble(final String columnName) { return getDouble(getColumnIndexOrThrow(columnName)); } public float getFloat(final String columnName) { return getFloat(getColumnIndexOrThrow(columnName)); } public int getInt(final String columnName) { return getInt(getColumnIndexOrThrow(columnName)); } public long getLong(final String columnName) { return getLong(getColumnIndexOrThrow(columnName)); } /** * Gets the {@link EasyQueryModel} which produced this cursor (if any). * If this cursor was not the produced via an {@link EasyQueryModel}, * the result is null; * * @return the query model */ public EasyQueryModel getQueryModel() { return mModel; } public String getString(final String columnName) { return getString(getColumnIndexOrThrow(columnName)); } protected boolean isColumnPresent(final String columnName, final int columnNo){ if(columnNo == COLUMN_NOT_PRESENT){ if(mDebugEnabled){ Log.w(TAG, "Column '" + columnName + "' is not present in Cursor - " + getPosition() + "/" + getCount()); } return false; } else { return true; } } public boolean isDebugEnabled(){ return mDebugEnabled; } /** * Extracts the contents of a cursors Column as a Boolean. * If the column does not exist, it will return null; * * The logic is defined in {@link #calcBoolean(int)} * * @param columnName the name of the cursor column that we want to get the value from * @return the value from cursor if the column exists, {@value #DEFAULT_BOOLEAN} otherwise */ public boolean optBoolean(final String columnName) { return optBoolean(columnName, DEFAULT_BOOLEAN); } /** * Extracts the contents of a cursors Column as a Boolean. * If the column does not exist, it will return the fallback value; * * The logic is defined in {@link #calcBoolean(int)} * * @param columnName the column name * @param fallback the value to return if the cursor does not exist * @return the value from cursor if the column exists, null otherwise */ public boolean optBoolean(final String columnName, boolean fallback) { final int columnNo = getColumnIndex(columnName); if (isColumnPresent(columnName, columnNo)) { return calcBoolean(columnNo); } else { return fallback; } } /** * Extracts the contents of a cursors Column as a Boolean. * If the column does not exist, it will return null. * * Use this if you want to know if the column did not exist. * * The logic is defined in {@link #calcBoolean(int)} * * @param columnName the column name * @return the value from cursor if the column exists, null otherwise */ public Boolean optBooleanAsWrapperType(final String columnName) { final int columnNo = getColumnIndex(columnName); if (isColumnPresent(columnName, columnNo)) { return calcBoolean(columnNo) ? Boolean.TRUE : Boolean.FALSE; } else { return null; } } public double optDouble(final String columnName) { return optDouble(columnName, DEFAULT_DOUBLE); } /** * Extracts the contents of a cursors Column as a double. * If the column does not exist, it will return the fallback value; * * @param columnName the column name * @param fallback the value to return if the cursor does not exist * @return the value from cursor if the column exists, the fallback otherwise */ public double optDouble(final String columnName, double fallback) { final int columnNo = getColumnIndex(columnName); if (isColumnPresent(columnName, columnNo)) { return getDouble(columnNo); } else { return fallback; } } /** * Extracts the contents of a cursors Column as a Double. * If the column does not exist, it will return null; * * Use this if you want to know if the column did not exist. * * @param columnName the column name * @return the value from cursor if the column exists, null otherwise */ public Double optDoubleAsWrapperType(final String columnName) { final int columnNo = getColumnIndex(columnName); if (isColumnPresent(columnName, columnNo)) { return getDouble(columnNo); } else { return null; } } /** * Extracts the contents of a cursors Column as a float. * * @param columnName the name of the cursor column that we want to get the value from * @return the value from cursor if the column exists, {@value #DEFAULT_FLOAT} otherwise. */ public float optFloat(final String columnName) { return optFloat(columnName, DEFAULT_FLOAT); } /** * Extracts the contents of a cursors Column as a float. * If the column does not exist, it will return the fallback value; * * @param columnName the column name * @param fallback the value to return if the cursor does not exist * @return the value from cursor if the column exists, the fallback otherwise */ public float optFloat(final String columnName, float fallback) { final int columnNo = getColumnIndex(columnName); if (isColumnPresent(columnName, columnNo)) { return getFloat(columnNo); } else { return fallback; } } /** * Extracts the contents of a cursors Column as a Float. * If the column does not exist, it will return null; * * Use this if you want to know if the column did not exist. * * @param columnName the column name * @return the value from cursor if the column exists, null otherwise */ public Float optFloatAsWrapperType(final String columnName) { final int columnNo = getColumnIndex(columnName); if (isColumnPresent(columnName, columnNo)) { return getFloat(columnNo); } else { return null; } } /** * Extracts the contents of a cursors Column as an int. * * @param columnName the name of the cursor column that we want to get the value from * @return the value from cursor if the column exists, {@value #DEFAULT_INT} otherwise. */ public int optInt(final String columnName) { return optInt(columnName, DEFAULT_INT); } /** * Extracts the contents of a cursors Column as an int. * If the column does not exist, it will return the fallback value; * * @param columnName the column name * @param fallback the value to return if the cursor does not exist * @return the value from cursor if the column exists, the fallback otherwise */ public int optInt(final String columnName, int fallback) { final int columnNo = getColumnIndex(columnName); if (isColumnPresent(columnName, columnNo)) { return getInt(columnNo); } else { return fallback; } } /** * Extracts the contents of a cursors Column as an Integer. * If the column does not exist, it will return null; * * Use this if you want to know if the column did not exist. * * @param columnName the column name * @return the value from cursor if the column exists, null otherwise */ public Integer optIntAsWrapperType(final String columnName) { final int columnNo = getColumnIndex(columnName); if (isColumnPresent(columnName, columnNo)) { return getInt(columnNo); } else { return null; } } /** * Extracts the contents of a cursors Column as a long. * * @param columnName the name of the cursor column that we want to get the value from * @return the value from cursor if the column exists, {@value #DEFAULT_LONG} otherwise. */ public long optLong(final String columnName) { return optLong(columnName, DEFAULT_LONG); } /** * Extracts the contents of a cursors Column as a long. * If the column does not exist, it will return the fallback value; * * @param columnName the column name * @param fallback the value to return if the cursor does not exist * @return the value from cursor if the column exists, the fallback otherwise */ public long optLong(final String columnName, long fallback) { final int columnNo = getColumnIndex(columnName); if (isColumnPresent(columnName, columnNo)) { return getLong(columnNo); } else { return fallback; } } /** * Extracts the contents of a cursors Column as a Long. * If the column does not exist, it will return null; * * Use this if you want to know if the column did not exist. * * @param columnName the column name * @return the value from cursor if the column exists, null otherwise */ public Long optLongAsWrapperType(final String columnName) { final int columnNo = getColumnIndex(columnName); if (isColumnPresent(columnName, columnNo)) { return getLong(columnNo); } else { return null; } } /** * Extracts the contents of a cursors Column as a String. * If the column does not exist, it will return {@value #DEFAULT_STRING}; * * @param columnName the name of the cursor column that we want to get the value from * @return the value from cursor if the column exists, {@value #DEFAULT_STRING} otherwise. */ public String optString(final String columnName) { return optString(columnName, DEFAULT_STRING); } /** * Extracts the contents of a cursors Column as a String. * If the column does not exist, it will return the fallback value; * * Note that this only checks if the column exists. If your fallback is not null, * you can still get a null back if the column content is null. * * @param columnName the column name * @param fallback the value to return if the cursor does not exist * @return the value from cursor if the column exists, the fallback otherwise */ public String optString(final String columnName, final String fallback) { final int columnNo = getColumnIndex(columnName); if (isColumnPresent(columnName, columnNo)) { return getString(columnNo); } else { return fallback; } } public void setDebugEnabled(boolean enabled){ mDebugEnabled = enabled; } @Override public String toString() { return "EasyCursor [mModel=" + mModel + ", mDebugEnabled=" + mDebugEnabled + ", isClosed()=" + isClosed() + ", getCount()=" + getCount() + ", getColumnCount()=" + getColumnCount() + ", getColumnNames()=" + Arrays.toString(getColumnNames()) + ", getPosition()=" + getPosition() + "]"; } }
package com.gdxjam; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.assets.AssetDescriptor; import com.badlogic.gdx.assets.AssetErrorListener; import com.badlogic.gdx.assets.AssetManager; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.NinePatch; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.graphics.g2d.TextureAtlas.AtlasRegion; import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator; import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator.FreeTypeFontParameter; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.badlogic.gdx.utils.Disposable; public class Assets implements Disposable, AssetErrorListener { public static final String TAG = Assets.class.getSimpleName(); private static Assets instance; public static AssetManager manager; public static Assets getInstance() { if (instance == null) { instance = new Assets(); } return instance; } public static AssetManager getManager() { return manager; } public static final String TEXTURE_ATLAS_OBJECTS = "assets.atlas"; public static final String SKIN = "skin/uiskin.json"; public AssetHotkey hotkey; public Assets() { manager = new AssetManager(); manager.setErrorListener(this); // set asset manager error handler loadAssets(); Gdx.app.debug(TAG, "# of assets loaded: " + manager.getAssetNames().size); for (String a : manager.getAssetNames()) { Gdx.app.debug(TAG, "asset: " + a); TextureAtlas atlas = manager.get(TEXTURE_ATLAS_OBJECTS); hotkey = new AssetHotkey(atlas); } } public void loadAssets() { manager.load(TEXTURE_ATLAS_OBJECTS, TextureAtlas.class); manager.load(SKIN, Skin.class); manager.load("minimal.pack", TextureAtlas.class); manager.finishLoading(); } @Override public void error(AssetDescriptor asset, Throwable throwable) { String filename = asset.fileName; Gdx.app.error(TAG, "Couldn't load asset '" + filename + "'", (Exception) throwable); } @Override public void dispose() { manager.dispose(); } public class AssetFonts { public final BitmapFont small; public final BitmapFont medium; public final BitmapFont large; public AssetFonts() { FreeTypeFontGenerator generator = new FreeTypeFontGenerator( Gdx.files.internal("fonts/emulogic.ttf")); FreeTypeFontParameter parameter = new FreeTypeFontParameter(); parameter.size = 12; small = generator.generateFont(parameter); // font size 12 pixels parameter.size = 16; medium = generator.generateFont(parameter); parameter.size = 32; large = generator.generateFont(parameter); generator.dispose(); // don't forget to dispose to avoid memory // leaks! } } public class AssetHotkey { public final AtlasRegion left; public final NinePatch button; public AtlasRegion middle; public AtlasRegion right; public AssetHotkey(TextureAtlas atlas) { left = atlas.findRegion("hotkeyleft"); button = new NinePatch(atlas.findRegion("hotkey")); right = atlas.findRegion("hotkeyright"); middle = atlas.findRegion("middlehotkey"); } } }
package org.jboss.xnio; import java.io.Closeable; import java.io.IOException; import java.io.InterruptedIOException; import java.net.DatagramSocket; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.URI; import java.nio.channels.Channel; import java.nio.channels.Selector; import java.util.concurrent.CancellationException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicReference; import java.util.zip.ZipFile; import org.jboss.xnio.channels.StreamChannel; import org.jboss.xnio.log.Logger; import java.util.logging.Handler; /** * General I/O utility methods. * * @apiviz.exclude */ public final class IoUtils { private static final Executor NULL_EXECUTOR = new Executor() { private final String string = String.format("null executor <%s>", Integer.toHexString(hashCode())); public void execute(final Runnable command) { // no operation } public String toString() { return string; } }; private static final Executor DIRECT_EXECUTOR = new Executor() { private final String string = String.format("direct executor <%s>", Integer.toHexString(hashCode())); public void execute(final Runnable command) { command.run(); } public String toString() { return string; } }; private static final IoHandler<Channel> NULL_HANDLER = new IoHandler<Channel>() { private final String string = String.format("null handler <%s>", Integer.toHexString(hashCode())); public void handleOpened(final Channel channel) { } public void handleReadable(final Channel channel) { } public void handleWritable(final Channel channel) { } public void handleClosed(final Channel channel) { } public String toString() { return string; } }; private static final IoHandlerFactory<Channel> NULL_HANDLER_FACTORY = new IoHandlerFactory<Channel>() { private final String string = String.format("null handler factory <%s>", Integer.toHexString(hashCode())); public IoHandler<Channel> createHandler() { return NULL_HANDLER; } public String toString() { return string; } }; private static final Closeable NULL_CLOSEABLE = new Closeable() { private final String string = String.format("null closeable <%s>", Integer.toHexString(hashCode())); public void close() throws IOException { // no operation } public String toString() { return string; } }; private IoUtils() {} /** * Create a persistent connection using a channel source. The provided handler will handle the connection. The {@code reconnectExecutor} will * be used to execute a reconnect task in the event that the connection fails or is lost or terminated. If you wish * to impose a time delay on reconnect, use the {@link org.jboss.xnio.IoUtils#delayedExecutor(java.util.concurrent.ScheduledExecutorService, long, java.util.concurrent.TimeUnit) delayedExecutor()} method * to create a delayed executor. If you do not want to auto-reconnect use the {@link org.jboss.xnio.IoUtils#nullExecutor()} method to * create a null executor. If you want auto-reconnect to take place immediately, use the {@link IoUtils#directExecutor()} method * to create a direct executor. * * @param channelSource the client to connect on * @param handler the handler for the connection * @param reconnectExecutor the executor that should execute the reconnect task * @param <T> the channel type * @return a handle which can be used to terminate the connection */ public static <T extends StreamChannel> Closeable createConnection(final ChannelSource<T> channelSource, final IoHandler<? super T> handler, final Executor reconnectExecutor) { final Connection<T> connection = new Connection<T>(channelSource, handler, reconnectExecutor); connection.connect(); return connection; } /** * Create a delayed executor. This is an executor that executes tasks after a given time delay with the help of the * provided {@code ScheduledExecutorService}. To get an executor for this method, use one of the methods on the * {@link java.util.concurrent.Executors} class. * * @param scheduledExecutorService the executor service to use to schedule the task * @param delay the time delay before reconnect * @param unit the unit of time to use * @return an executor that delays execution */ public static Executor delayedExecutor(final ScheduledExecutorService scheduledExecutorService, final long delay, final TimeUnit unit) { return new Executor() { public void execute(final Runnable command) { scheduledExecutorService.schedule(command, delay, unit); } }; } /** * Get the direct executor. This is an executor that executes the provided task in the same thread. * * @return a direct executor */ public static Executor directExecutor() { return DIRECT_EXECUTOR; } /** * Get the null executor. This is an executor that never actually executes the provided task. * * @return a null executor */ public static Executor nullExecutor() { return NULL_EXECUTOR; } /** * Get a closeable executor wrapper for an {@code ExecutorService}. The given timeout is used to determine how long * the {@code close()} method will wait for a clean shutdown before the executor is shut down forcefully. * * @param executorService the executor service * @param timeout the timeout * @param unit the unit for the timeout * @return a new closeable executor */ public static CloseableExecutor closeableExecutor(final ExecutorService executorService, final long timeout, final TimeUnit unit) { return new CloseableExecutor() { public void close() throws IOException { executorService.shutdown(); try { if (executorService.awaitTermination(timeout, unit)) { return; } executorService.shutdownNow(); throw new IOException("Executor did not shut down cleanly (killed)"); } catch (InterruptedException e) { Thread.currentThread().interrupt(); executorService.shutdownNow(); throw new InterruptedIOException("Interrupted while awaiting executor shutdown"); } } public void execute(final Runnable command) { executorService.execute(command); } }; } /** * Get the null closeable. This is a simple {@code Closeable} instance that does nothing when its {@code close()} * method is invoked. * * @return the null closeable */ public static Closeable nullCloseable() { return NULL_CLOSEABLE; } /** * Get the null handler. This is a handler whose handler methods all return without taking any action. * * @return the null handler */ public static IoHandler<Channel> nullHandler() { return NULL_HANDLER; } /** * Get the null handler factory. This is a handler factory that returns the null handler. * * @return the null handler factory */ public static IoHandlerFactory<Channel> nullHandlerFactory() { return NULL_HANDLER_FACTORY; } /** * Get a singleton handler factory that returns the given handler one time only. * * @param handler the handler to return * @return a singleton handler factory */ public static <T extends Channel> IoHandlerFactory<T> singletonHandlerFactory(final IoHandler<T> handler) { final AtomicReference<IoHandler<T>> reference = new AtomicReference<IoHandler<T>>(handler); return new IoHandlerFactory<T>() { public IoHandler<? super T> createHandler() { final IoHandler<T> handler = reference.getAndSet(null); if (handler == null) { throw new IllegalStateException("Handler already taken from singleton handler factory"); } return handler; } }; } private static final Logger closeLog = Logger.getLogger("org.jboss.xnio.safe-close"); /** * Close a resource, logging an error if an error occurs. * * @param resource the resource to close */ public static void safeClose(final Closeable resource) { try { if (resource != null) { resource.close(); } } catch (Throwable t) { closeLog.trace(t, "Closing resource failed"); } } /** * Close a resource, logging an error if an error occurs. * * @param resource the resource to close */ public static void safeClose(final Socket resource) { try { if (resource != null) { resource.close(); } } catch (Throwable t) { closeLog.trace(t, "Closing resource failed"); } } /** * Close a resource, logging an error if an error occurs. * * @param resource the resource to close */ public static void safeClose(final DatagramSocket resource) { try { if (resource != null) { resource.close(); } } catch (Throwable t) { closeLog.trace(t, "Closing resource failed"); } } /** * Close a resource, logging an error if an error occurs. * * @param resource the resource to close */ public static void safeClose(final Selector resource) { try { if (resource != null) { resource.close(); } } catch (Throwable t) { closeLog.trace(t, "Closing resource failed"); } } /** * Close a resource, logging an error if an error occurs. * * @param resource the resource to close */ public static void safeClose(final ServerSocket resource) { try { if (resource != null) { resource.close(); } } catch (Throwable t) { closeLog.trace(t, "Closing resource failed"); } } /** * Close a resource, logging an error if an error occurs. * * @param resource the resource to close */ public static void safeClose(final ZipFile resource) { try { if (resource != null) { resource.close(); } } catch (Throwable t) { closeLog.trace(t, "Closing resource failed"); } } /** * Close a resource, logging an error if an error occurs. * * @param resource the resource to close */ public static void safeClose(final Handler resource) { try { if (resource != null) { resource.close(); } } catch (Throwable t) { closeLog.trace(t, "Closing resource failed"); } } /** * Close a future resource, logging an error if an error occurs. Attempts to cancel the operation if it is * still in progress. * * @param futureResource the resource to close */ public static void safeClose(final IoFuture<? extends Closeable> futureResource) { futureResource.cancel().addNotifier(closingNotifier(), null); } private static final IoFuture.Notifier<Object, Closeable> ATTACHMENT_CLOSING_NOTIFIER = new IoFuture.Notifier<Object, Closeable>() { public void notify(final IoFuture<?> future, final Closeable attachment) { IoUtils.safeClose(attachment); } }; private static final IoFuture.Notifier<Closeable, Void> CLOSING_NOTIFIER = new IoFuture.HandlingNotifier<Closeable, Void>() { public void handleDone(final Closeable result, final Void attachment) { IoUtils.safeClose(result); } }; /** * Get a notifier that closes the attachment. * * @return a notifier which will close its attachment */ public static IoFuture.Notifier<Object, Closeable> attachmentClosingNotifier() { return ATTACHMENT_CLOSING_NOTIFIER; } /** * Get a notifier that closes the result. * * @return a notifier which will close the result of the operation (if successful) */ public static IoFuture.Notifier<Closeable, Void> closingNotifier() { return CLOSING_NOTIFIER; } /** * Get a notifier that runs the supplied action. * * @param runnable the notifier type * @param <T> the future type (not used) * @return a notifier which will run the given command */ public static <T> IoFuture.Notifier<T, Void> runnableNotifier(final Runnable runnable) { return new IoFuture.Notifier<T, Void>() { public void notify(final IoFuture<? extends T> future, final Void attachment) { runnable.run(); } }; } /** * Get a {@code java.util.concurrent}-style {@code Future} instance wrapper for an {@code IoFuture} instance. * * @param ioFuture the {@code IoFuture} to wrap * @return a {@code Future} */ public static <T> Future<T> getFuture(final IoFuture<T> ioFuture) { return new Future<T>() { public boolean cancel(final boolean mayInterruptIfRunning) { ioFuture.cancel(); return ioFuture.await() == IoFuture.Status.CANCELLED; } public boolean isCancelled() { return ioFuture.getStatus() == IoFuture.Status.CANCELLED; } public boolean isDone() { return ioFuture.getStatus() == IoFuture.Status.DONE; } public T get() throws InterruptedException, ExecutionException { try { return ioFuture.getInterruptibly(); } catch (IOException e) { throw new ExecutionException(e); } } public T get(final long timeout, final TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { try { if (ioFuture.awaitInterruptibly(timeout, unit) == IoFuture.Status.WAITING) { throw new TimeoutException("Operation timed out"); } return ioFuture.getInterruptibly(); } catch (IOException e) { throw new ExecutionException(e); } } public String toString() { return String.format("java.util.concurrent.Future wrapper <%s> for %s", Integer.toHexString(hashCode()), ioFuture); } }; } private static final IoFuture.Notifier<Object, CountDownLatch> COUNT_DOWN_NOTIFIER = new IoFuture.Notifier<Object, CountDownLatch>() { public void notify(final IoFuture<?> future, final CountDownLatch latch) { latch.countDown(); } }; public static void awaitAll(IoFuture<?>... futures) { final int len = futures.length; final CountDownLatch cdl = new CountDownLatch(len); for (IoFuture<?> future : futures) { future.addNotifier(COUNT_DOWN_NOTIFIER, cdl); } boolean intr = false; try { while (cdl.getCount() > 0L) { try { cdl.await(); } catch (InterruptedException e) { intr = true; } } } finally { if (intr) { Thread.currentThread().interrupt(); } } } public static void awaitAllInterruptibly(IoFuture<?>... futures) throws InterruptedException { final int len = futures.length; final CountDownLatch cdl = new CountDownLatch(len); for (IoFuture<?> future : futures) { future.addNotifier(COUNT_DOWN_NOTIFIER, cdl); } cdl.await(); } /** * Create an {@code IoFuture} which wraps another {@code IoFuture}, but returns a different type. * * @param parent the original {@code IoFuture} * @param type the class of the new {@code IoFuture} * @param <I> the type of the original result * @param <O> the type of the wrapped result * @return a wrapper {@code IoFuture} */ public static <I, O> IoFuture<? extends O> cast(final IoFuture<I> parent, final Class<O> type) { return new CastingIoFuture<O, I>(parent, type); } // nested classes private static final Logger connLog = Logger.getLogger("org.jboss.xnio.connection"); private static final class Connection<T extends StreamChannel> implements Closeable { private final ChannelSource<T> channelSource; private final IoHandler<? super T> handler; private final Executor reconnectExecutor; private volatile boolean stopFlag = false; private volatile IoFuture<? extends T> currentFuture; private final NotifierImpl<?> notifier = new NotifierImpl<Void>(); private final HandlerImpl handlerWrapper = new HandlerImpl(); private final ReconnectTask reconnectTask = new ReconnectTask(); private Connection(final ChannelSource<T> channelSource, final IoHandler<? super T> handler, final Executor reconnectExecutor) { this.channelSource = channelSource; this.handler = handler; this.reconnectExecutor = reconnectExecutor; } private void connect() { closeLog.trace("Establishing connection"); final IoFuture<? extends T> ioFuture = channelSource.open(handlerWrapper); ioFuture.addNotifier(notifier, null); currentFuture = ioFuture; } public void close() throws IOException { stopFlag = true; final IoFuture<? extends T> future = currentFuture; if (future != null) { future.cancel(); } } public String toString() { return String.format("persistent connection <%s> via %s", Integer.toHexString(hashCode()), channelSource); } private final class NotifierImpl<A> extends IoFuture.HandlingNotifier<T, A> { public void handleCancelled(final A attachment) { connLog.trace("Connection cancelled"); } public void handleFailed(final IOException exception, final A attachment) { connLog.trace(exception, "Connection failed"); } public void handleDone(final T result, final A attachment) { connLog.trace("Connection established"); } public void notify(final IoFuture<? extends T> future, final A attachment) { super.notify(future, attachment); if (! stopFlag) { reconnectExecutor.execute(reconnectTask); } return; } } private final class HandlerImpl implements IoHandler<T> { public void handleOpened(final T channel) { handler.handleOpened(channel); } public void handleReadable(final T channel) { handler.handleReadable(channel); } public void handleWritable(final T channel) { handler.handleWritable(channel); } public void handleClosed(final T channel) { try { connLog.trace("Connection closed"); if (! stopFlag) { reconnectExecutor.execute(reconnectTask); } } finally { handler.handleClosed(channel); } } public String toString() { return String.format("persistent connection handler <%s> wrapping %s", Integer.toHexString(hashCode()), handler); } } private final class ReconnectTask implements Runnable { public void run() { if (! stopFlag) { connect(); } } public String toString() { return String.format("reconnect task <%s> for %s", Integer.toHexString(hashCode()), Connection.this); } } } private static class CastingIoFuture<O, I> implements IoFuture<O> { private final IoFuture<I> parent; private final Class<O> type; private CastingIoFuture(final IoFuture<I> parent, final Class<O> type) { this.parent = parent; this.type = type; } public IoFuture<O> cancel() { parent.cancel(); return this; } public Status getStatus() { return parent.getStatus(); } public Status await() { return parent.await(); } public Status await(final long time, final TimeUnit timeUnit) { return parent.await(time, timeUnit); } public Status awaitInterruptibly() throws InterruptedException { return parent.awaitInterruptibly(); } public Status awaitInterruptibly(final long time, final TimeUnit timeUnit) throws InterruptedException { return parent.awaitInterruptibly(time, timeUnit); } public O get() throws IOException, CancellationException { return type.cast(parent.get()); } public O getInterruptibly() throws IOException, InterruptedException, CancellationException { return type.cast(parent.getInterruptibly()); } public IOException getException() throws IllegalStateException { return parent.getException(); } public <A> IoFuture<O> addNotifier(final Notifier<? super O, A> notifier, final A attachment) { parent.<A>addNotifier(new Notifier<I, A>() { public void notify(final IoFuture<? extends I> future, final A attachment) { notifier.notify((IoFuture<O>)CastingIoFuture.this, attachment); } }, attachment); return this; } } /** * Get a URI connector which connects to the Internet address specified in the given URI. * * @param original the Internet address connector * @param defaultPort the default port to use if none is given in the URI * @return the URI connector * * @since 1.3 */ public static <T extends Channel> BoundConnector<URI, T> inetUriConnector(final BoundConnector<InetSocketAddress, T> original, final int defaultPort) { return new BoundConnector<URI, T>() { public FutureConnection<URI, T> connectTo(final URI dest, final IoHandler<? super T> ioHandler) { final FutureConnection<InetSocketAddress, T> futureConnection = original.connectTo(getSockAddr(dest), ioHandler); return new UriFutureConnection<T>(futureConnection); } public ChannelSource<T> createChannelSource(final URI dest) { return original.createChannelSource(getSockAddr(dest)); } private InetSocketAddress getSockAddr(final URI dest) { final String destHost = dest.getHost(); final int destPort = dest.getPort(); final InetSocketAddress destSockAddr = new InetSocketAddress(destHost, destPort == -1 ? defaultPort : destPort); return destSockAddr; } }; } private static class UriFutureConnection<T extends Channel> implements FutureConnection<URI, T> { private final FutureConnection<InetSocketAddress, T> futureConnection; private UriFutureConnection(final FutureConnection<InetSocketAddress, T> futureConnection) { this.futureConnection = futureConnection; } public URI getLocalAddress() { throw new UnsupportedOperationException(); } public FutureConnection<URI, T> cancel() { futureConnection.cancel(); return this; } public Status getStatus() { return futureConnection.getStatus(); } public Status await() { return futureConnection.await(); } public Status await(final long time, final TimeUnit timeUnit) { return futureConnection.await(time, timeUnit); } public Status awaitInterruptibly() throws InterruptedException { return futureConnection.awaitInterruptibly(); } public Status awaitInterruptibly(final long time, final TimeUnit timeUnit) throws InterruptedException { return futureConnection.awaitInterruptibly(time, timeUnit); } public T get() throws IOException, CancellationException { return futureConnection.get(); } public T getInterruptibly() throws IOException, InterruptedException, CancellationException { return futureConnection.getInterruptibly(); } public IOException getException() throws IllegalStateException { return futureConnection.getException(); } public <A> IoFuture<T> addNotifier(final Notifier<? super T, A> aNotifier, final A attachment) { return futureConnection.addNotifier(aNotifier, attachment); } } /** * Get a bound connector for a certain source address. * * @param connector the connector * @param src the source address * @param <A> the address type * @param <T> the channel type * @return the bound connector * * @since 1.3 */ public static <A, T extends Channel> BoundConnector<A, T> bindConnector(final Connector<A, T> connector, final A src) { return new BoundConnector<A, T>() { public FutureConnection<A, T> connectTo(final A dest, final IoHandler<? super T> ioHandler) { return connector.connectTo(src, dest, ioHandler); } public ChannelSource<T> createChannelSource(final A dest) { return connector.createChannelSource(src, dest); } }; } }
package it.negusweb.starterkit.classes.helper; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.support.v7.app.AlertDialog; /** UIHelper @author Fabrizio Caldarelli @version 2 */ public class UIHelper { // Show waiter public static ProgressDialog showWaiter(Context ctx) { return showWaiter(ctx, null); } public static ProgressDialog showWaiter(Context ctx, String message) { String msg = (message!=null)?message: ctx.getString(R.string.uihelper_waiter_default_message); ProgressDialog pd = new ProgressDialog(ctx); pd.setMessage(msg); pd.setIndeterminate(true); pd.setCancelable(false); pd.setCanceledOnTouchOutside(false); pd.show(); return pd; } // Hide waiter public static void hideWaiter(ProgressDialog pd) { try { if (pd != null) { pd.hide(); pd.dismiss(); } } catch(Exception excp) { } pd = null; } // ShowAlertOK public static AlertDialog showAlertOK(Context ctx, String title, String message, DialogInterface.OnClickListener okTapped) { AlertDialog ad = new AlertDialog.Builder(ctx) .setTitle(title) .setMessage(message) .setPositiveButton(R.string.uihelper_alertok_ok, okTapped) .create(); ad.show(); return ad; } public static AlertDialog showAlertYesNo(Context ctx, String title, String message, final UIHelperAlertYesNoListener listener) { AlertDialog ad = new AlertDialog.Builder(ctx) .setTitle(title) .setMessage(message) .setPositiveButton(R.string.uihelper_alertok_yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { if(listener!=null) listener.uiHelperAlertYesNoResponse(true); } }) .setPositiveButton(R.string.uihelper_alertok_no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { if(listener!=null) listener.uiHelperAlertYesNoResponse(false); } }) .create(); ad.show(); return ad; } public interface UIHelperAlertYesNoListener { void uiHelperAlertYesNoResponse(boolean response); } }
package com.oldterns.vilebot.handlers.user; import ca.szc.keratin.bot.annotation.HandlerContainer; import ca.szc.keratin.core.event.message.recieve.ReceivePrivmsg; import com.oldterns.vilebot.Vilebot; import com.oldterns.vilebot.db.KarmaDB; import com.oldterns.vilebot.util.BaseNick; import net.engio.mbassy.listener.Handler; import java.nio.file.Files; import java.nio.file.Paths; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.regex.Matcher; import java.util.regex.Pattern; @HandlerContainer public class Omgword { private static final Pattern QUESTION_PATTERN = Pattern.compile( "!omgword" ); private static final Pattern ANSWER_PATTERN = Pattern.compile( "!answer (.*)" ); private static final String WORD_LIST_PATH = Vilebot.getConfig().get("OmgwordList"); private static final String OMGWORD_CHANNEL = Vilebot.getConfig().get("OmgwordChannel"); private ArrayList<String> words = loadWords(); private OmgwordGame currentGame; private String word; private String scrambled; private static final Random random = new SecureRandom(); private static final long TIMEOUT = 30000L; private static ExecutorService timer = Executors.newScheduledThreadPool(1); @Handler public void omgword(ReceivePrivmsg event) { String text = event.getText(); Matcher questionMatcher = QUESTION_PATTERN.matcher(text); Matcher answerMatcher = ANSWER_PATTERN.matcher(text); try { if (questionMatcher.matches() && shouldStartGame(event)) { startGame(event); } else if (answerMatcher.matches() && shouldStartGame(event)) { String answer = answerMatcher.group(1); finishGame(event, answer); } } catch(Exception e) { e.printStackTrace(); System.exit(1); } } private boolean shouldStartGame(ReceivePrivmsg event) { String actualChannel = event.getChannel(); if (OMGWORD_CHANNEL.equals(actualChannel)) { return true; } event.reply("To play Omgword join: " + OMGWORD_CHANNEL); return false; } private synchronized void startGame(ReceivePrivmsg event) throws Exception { if (currentGame != null) { event.reply(currentGame.getAlreadyPlayingString()); } else { currentGame = new OmgwordGame(); event.reply(currentGame.getIntroString()); startTimer(event); } } private void startTimer(final ReceivePrivmsg event) { timer.submit(new Runnable() { @Override public void run() { try { Thread.sleep(TIMEOUT); timeoutTimer(event); } catch (InterruptedException e) { e.printStackTrace(); } } }); } private void timeoutTimer(ReceivePrivmsg event) { String message = currentGame.getTimeoutString(); event.reply(message); currentGame = null; } private void stopTimer() { timer.shutdownNow(); timer = Executors.newFixedThreadPool(1); } private synchronized void finishGame(ReceivePrivmsg event, String answer) { String answerer = BaseNick.toBaseNick(event.getSender()); if (currentGame != null) { if (currentGame.isCorrect(answer)) { stopTimer(); event.reply(String.format("Congrats %s, you win %d karma!", answerer, currentGame.getStakes())); KarmaDB.modNounKarma(answerer, currentGame.getStakes()); currentGame = null; } else { event.reply(String.format("Sorry %s! That is incorrect, you lose %d karma.", answerer, currentGame.getStakes())); KarmaDB.modNounKarma(answerer, -1 * currentGame.getStakes()); } } else { event.reply("No active game. Start a new one with !omgword"); } } private ArrayList<String> loadWords() { try { ArrayList<String> words = new ArrayList<>(); List<String> lines = Files.readAllLines(Paths.get(WORD_LIST_PATH)); for (String line : lines) { words.addAll(Arrays.asList(line.split(" "))); } return words; } catch (Exception e) { System.exit(1); } return null; } private class OmgwordGame { public String getAlreadyPlayingString() { return "A game is already in progress! Your word is: " + scrambled; } public String getIntroString() { word = ""; int index = random.nextInt(words.size() - 1); word = words.get(index); scrambled = word; char[] chars = words.get(index).toCharArray(); while (scrambled.equals(word)) { shuffleArray(chars); scrambled = new String(chars); } return "Welcome to omgword!\nFor " + getStakes() + " karma:\n" + scrambled +"\n30 seconds on the clock."; } public boolean isCorrect(String answer) { return answer.equals(word); } public String getTimeoutString() { return "Game over! The correct answer was: " + word; } public int getStakes() { return (int) Math.ceil(word.length()/2); } } private static void shuffleArray(char[] array) { char temp; int index; Random random = new Random(); for (int i = array.length - 1; i > 0; i index = random.nextInt(i + 1); temp = array[index]; array[index] = array[i]; array[i] = temp; } } }
package integration.tests; import static org.junit.Assert.assertEquals; import gr.ntua.vision.monitoring.VismoConfiguration; import gr.ntua.vision.monitoring.VismoVMInfo; import gr.ntua.vision.monitoring.dispatch.VismoEventDispatcher; import gr.ntua.vision.monitoring.events.MonitoringEvent; import gr.ntua.vision.monitoring.notify.VismoEventRegistry; import gr.ntua.vision.monitoring.rules.CTORule; import gr.ntua.vision.monitoring.rules.VismoRulesEngine; import gr.ntua.vision.monitoring.service.ClusterHeadNodeFactory; import gr.ntua.vision.monitoring.service.VismoService; import gr.ntua.vision.monitoring.sinks.EventSink; import gr.ntua.vision.monitoring.sinks.InMemoryEventSink; import gr.ntua.vision.monitoring.zmq.ZMQFactory; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.zeromq.ZContext; public class CTORuleTest { @SuppressWarnings("serial") private static final Properties p = new Properties() { { setProperty("cloud.name", "visioncloud.eu"); setProperty("cloud.heads", "10.0.2.211, 10.0.2.212"); setProperty("cluster.name", "vision-1"); setProperty("cluster.head", "10.0.2.211"); setProperty("producers.point", "tcp://127.0.0.1:56429"); setProperty("consumers.port", "56430"); setProperty("udp.port", "56431"); setProperty("cluster.head.port", "56432"); setProperty("cloud.head.port", "56433"); setProperty("mon.group.addr", "228.5.6.7"); setProperty("mon.group.port", "12345"); setProperty("mon.ping.period", "60000"); setProperty("startup.rules", ""); } }; private static final int PERIOD = 500; private static final String TOPIC = "cto"; final ArrayList<MonitoringEvent> eventStore = new ArrayList<MonitoringEvent>(); private VismoConfiguration conf; private FakeObjectService obs; private VismoService service; private ZMQFactory socketFactory; /** * @throws IOException */ @Before public void setUp() throws IOException { conf = new VismoConfiguration(p); socketFactory = new ZMQFactory(new ZContext()); obs = new FakeObjectService(new VismoEventDispatcher(socketFactory, conf, "fake-obs"), new Random(3331)); service = (VismoService) new ClusterHeadNodeFactory(conf, socketFactory) { /** * @see gr.ntua.vision.monitoring.service.ClusterHeadNodeFactory#getEventSinks() */ @Override protected List< ? extends EventSink> getEventSinks() { final List<EventSink> sinks = new ArrayList<EventSink>(); sinks.addAll(super.getEventSinks()); sinks.add(new InMemoryEventSink(eventStore)); return sinks; } /** * @see gr.ntua.vision.monitoring.service.ClusterHeadNodeFactory#submitRules(gr.ntua.vision.monitoring.rules.VismoRulesEngine) */ @Override protected void submitRules(final VismoRulesEngine engine) { new CTORule(engine, TOPIC, PERIOD).submit(); super.submitRules(engine); } }.build(new VismoVMInfo()); } /** * @throws InterruptedException */ @Test public void shouldReceiveCTOAggregationResult() throws InterruptedException { final VismoEventRegistry reg = new VismoEventRegistry(socketFactory, "tcp://127.0.0.1:" + conf.getConsumersPort()); final CountDownLatch latch = new CountDownLatch(1); final ConsumerHandler handler = new ConsumerHandler(latch, 1); reg.register(TOPIC, handler); service.start(); sendEvents(10); latch.await(6 * PERIOD / 5, TimeUnit.MILLISECONDS); assertGotExpectedEvent(handler); } @After public void tearDown() { if (service != null) service.halt(); } /** * @param handler */ private void assertGotExpectedEvent(final ConsumerHandler handler) { assertEquals(1, handler.getNoReceivedEvents()); assertEquals(TOPIC, eventStore.get(eventStore.size() - 1).topic()); } /** * @param no */ private void sendEvents(final int no) { for (int i = 0; i < no; ++i) obs.putEvent("ntua", "bill", "foo-container", "bar-object").send(); } }
// Implements the game of Craps logic public class CrapsGame { private int point = 0; private int result = 0; /** * Calculates the result of the next dice roll in the Craps game. * The parameter total is the sum of dots on two dice. * point is set to the saved total, if the game continues, * or 0, if the game has ended. * Returns 1 if player won, -1 if player lost, * 0 if player continues rolling. */ public int processRoll(int total) { if (point == 0) { if (total == 7 || total == 11) { result = 1; point = 0; } else if (total == 2 || total == 3 || total == 12) { result = -1; point = 0; } else { point = total; result = 0; } } else { result = 0; if (total == 7) { result = -1; point = 0; } else if (point == total) { result = 1; point = 0; } else { result = 0; point = total; } } return result; } /** * Returns the saved point */ public int getPoint() { return point; } }
package com.sometrik.framework; import java.util.ArrayList; import java.util.Iterator; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.Typeface; import android.graphics.drawable.BitmapDrawable; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.LinearLayout; public class FWSimpleList extends LinearLayout implements NativeCommandHandler { private FrameWork frame; private FrameLayout.LayoutParams defaultListParams; private ArrayList<Sheet> sheets = new ArrayList<Sheet>(); private ArrayList<String> sheetMemory = new ArrayList<String>(); private int tableSize = 1; public FWSimpleList(FrameWork frame) { super(frame); this.frame = frame; defaultListParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT); defaultListParams.setMargins(0, 10, 0, 10); setOrientation(LinearLayout.VERTICAL); setDividerDrawable(frame.getResources().getDrawable(android.R.drawable.divider_horizontal_bright)); this.setBackgroundColor(Color.rgb(255, 255, 255)); } @Override public void onScreenOrientationChange(boolean isLandscape) { // TODO Auto-generated method stub } @Override public void addChild(View view) { view.setLayoutParams(defaultListParams); Sheet sheet = new Sheet((ViewGroup)view); sheets.add(sheet); if (sheetMemory.size() >= sheets.size()) { Log.d("adapter", "setting sheetMemory"); sheet.name.setText(sheetMemory.get(sheets.size() - 1)); } else { sheet.name.setText("TITLE"); } addView(sheet.layout); } private ArrayList<Sheet> getEnabledSheets() { ArrayList<Sheet> enabledSheets = new ArrayList<Sheet>(); for (Sheet sheet : sheets) { if (!sheet.disabled) { enabledSheets.add(sheet); } } return enabledSheets; } private ArrayList<Sheet> getDisabledSheets(){ ArrayList<Sheet> disabledSheets = new ArrayList<Sheet>(); for (Sheet sheet : sheets) { if (sheet.disabled) { disabledSheets.add(sheet); } } return disabledSheets; } @Override public void addOption(int optionId, String text) { // System.out.println("setting sheet " + sheetPosition + " " + title + " " + sheets.size()); if (optionId < sheets.size()) { sheets.get(optionId).name.setText(text);; } sheetMemory.add(optionId, text); } @Override public void addColumn(String text, int columnType) { } @Override public void addData(String text, int row, int column, int sheet) { // TODO Auto-generated method stub } @Override public void setValue(String v) { } @Override public void setImage(byte[] bytes) { // TODO Auto-generated method stub } @Override public void setValue(int v) { // TODO Auto-generated method stub } @Override public void reshape(int value, int size) { if (value < sheets.size()) { ViewGroup layout = sheets.get(value).layout; //add one because title layout won't be resized size++; if (layout.getChildCount() == size) { return; } ArrayList<View> viewsToBeRemoved = new ArrayList<View>(); for (int i = size; i < layout.getChildCount(); i++) { View view = layout.getChildAt(i); viewsToBeRemoved.add(view); } Iterator<View> i = viewsToBeRemoved.iterator(); while (i.hasNext()) { View v = i.next(); if (v instanceof FWImageView) { Bitmap drawable = ((BitmapDrawable) v.getBackground()).getBitmap(); if (drawable != null) { drawable.recycle(); } } frame.removeViewFromList(v.getId()); layout.removeView(v); } } else { ViewGroup layout = sheets.get(value).layout; for (int i = 0; i < layout.getChildCount(); i++) { } return; } // invalidate(); } @Override public void reshape(int size) { this.tableSize = size; ArrayList<Sheet> enabledSheets = getEnabledSheets(); if (size == enabledSheets.size()) { return; } if (size < enabledSheets.size()) { for (int i = size; i < enabledSheets.size(); i++) { System.out.println("removing sheet " + i); sheets.get(i).disable(); // sheets.get(i).layout.setVisibility(GONE); // removeView(sheets.get(i).layout); } } if (size > enabledSheets.size()) { ArrayList<Sheet> disabledSheets = getDisabledSheets(); int difference = size - enabledSheets.size(); for (int i = 0; i < difference; i++) { Sheet disabledSheet = disabledSheets.get(i); disabledSheet.enable(); // disabledSheet.disabled = false; // sheets.get(i).layout.setVisibility(VISIBLE); // addView(disabledSheet.layout); } } // updateLayout(); invalidate(); } // private void updateLayout() { // this.removeAllViews(); // ArrayList<Sheet> enabledSheets = getEnabledSheets(); // for (Sheet sheet : enabledSheets) { // addView(sheet.layout); // invalidate(); @Override public void setViewEnabled(Boolean enabled) { // TODO Auto-generated method stub } @Override public void setViewVisibility(boolean visible) { if (visible) { this.setVisibility(VISIBLE); } else { this.setVisibility(GONE); } } @Override public void setStyle(String key, String value) { if (key.equals("divider")) { if (value.equals("middle")) { this.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE); } else if (value.equals("end")) { this.setShowDividers(LinearLayout.SHOW_DIVIDER_END); } else if (value.equals("beginning")) { this.setShowDividers(LinearLayout.SHOW_DIVIDER_BEGINNING); } } else if (key.equals("color")) { this.setBackgroundColor(Color.parseColor(value)); } else if (key.equals("width")) { FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) getLayoutParams(); if (value.equals("wrap-content")) { params.width = LinearLayout.LayoutParams.WRAP_CONTENT; } else if (value.equals("match-parent")) { params.width = LinearLayout.LayoutParams.MATCH_PARENT; } else { final float scale = getContext().getResources().getDisplayMetrics().density; int pixels = (int) (Integer.parseInt(value) * scale + 0.5f); params.width = pixels; } setLayoutParams(params); } else if (key.equals("height")) { FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) getLayoutParams(); if (value.equals("wrap-content")) { params.height = LinearLayout.LayoutParams.WRAP_CONTENT; } else if (value.equals("match-parent")) { params.height = LinearLayout.LayoutParams.MATCH_PARENT; } else { final float scale = getContext().getResources().getDisplayMetrics().density; int pixels = (int) (Integer.parseInt(value) * scale + 0.5f); params.height = pixels; } setLayoutParams(params); } } @Override public void setError(boolean hasError, String errorText) { // TODO Auto-generated method stub } @Override public void clear() { reshape(0); } @Override public void flush() { // TODO Auto-generated method stub } @Override public int getElementId() { return getId(); } private class Sheet { private ViewGroup layout; private FWTextView name; private int restrictedSize = 1; private boolean disabled = false; private void disable() { disabled = true; // layout.setVisibility(GONE); } private void enable() { disabled = false; // layout.setVisibility(VISIBLE); // for (int i = 0; i < layout.getChildCount(); i++) { // layout.getChildAt(i).setVisibility(VISIBLE);; } private Sheet(ViewGroup view) { name = new FWTextView(frame); // name.setBackgroundDrawable(frame.getResources().getDrawable(android.R.drawable.dialog_holo_light_frame)); name.setTextSize(24); name.setTypeface(null, Typeface.BOLD); name.setLayoutParams(defaultListParams); final float scale = getContext().getResources().getDisplayMetrics().density; int pixels = (int) (41 * scale + 0.5f); name.setHeight(pixels); // name.setBackgroundDrawable(backgroundColor); layout = view; view.addView(name); } } }
package nctu.fintech.appmate; import android.support.annotation.NonNull; import android.util.Base64; import android.util.Log; import com.google.code.regexp.Pattern; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.Map; class DbCore { final URL url; final boolean useAuth; final String username; final String authStr; /** * Create a {@link DbCore} instance. * * @param host host domain * @param username username * @param password password */ DbCore(String host, String username, String password) { // anti-foolish if (host == null || host.isEmpty()) { throw new IllegalArgumentException("illegal host name"); } // parse host string Map<String, String> matcher = Pattern.compile ( "^(?:https?:\\/\\/)?(?:(?<auth>(?<user>[\\w-]+):\\w+)@)?(?<host>[\\w\\d-]+(?:\\.[\\w\\d-]+)+(?::\\d+)?)", Pattern.CASE_INSENSITIVE ) .matcher(host) .namedGroups(); // set host String cleanHost = matcher.get("host"); if (cleanHost == null) { throw new IllegalArgumentException("host domain not found"); } // set base url URL url; try { url = new URL("http://" + cleanHost + "/api/"); } catch (MalformedURLException e) { throw new IllegalArgumentException("illegal host domain", e); } // check auth assigned String authStrFromHost = matcher.get("auth"); boolean isHostSetAuth = authStrFromHost != null; boolean isParamSetAuth = username != null && !username.isEmpty(); if (isHostSetAuth && isParamSetAuth) { throw new UnsupportedOperationException("more than 1 authentication parameter is assigned"); } else if (isParamSetAuth) { this.url = url; this.useAuth = true; this.username = username; this.authStr = genAuthStr(username + ":" + password); } else if (isHostSetAuth) { this.url = url; this.useAuth = true; this.username = matcher.get("user"); this.authStr = genAuthStr(authStrFromHost); } else { this.url = url; this.useAuth = false; this.username = null; this.authStr = null; } } /** * Alias of {@link DbCore#DbCore(String, String, String)} * * @param host host domain */ DbCore(String host) { this(host, null, null); } DbCore(DbCore core) { this.url = core.url; this.useAuth = core.useAuth; this.username = core.username; this.authStr = core.authStr; } /** * create a null instance */ DbCore() { this.url = null; this.useAuth = false; this.username = null; this.authStr = null; } /** * Generate the string used in HTTP header {@code Authorization}. * THIS METHOD SHOULD ONLY USE BY CONSTRUCTOR * * @param auth_string user name and password pair, set in {@code user:password} format * @return HTTP basic authentication string */ private static String genAuthStr(String auth_string) { String auth_encoded = Base64.encodeToString(auth_string.getBytes(), Base64.DEFAULT); return "Basic " + auth_encoded; } /** * Create a {@link HttpURLConnection} instance * * @param url url to open * @return a {@link HttpURLConnection} instance, with auth header is set when authentication is required */ HttpURLConnection openUrl(URL url) throws IOException { // open connection HttpURLConnection con = (HttpURLConnection) url.openConnection(); // set properties con.setRequestProperty("accept", "application/json"); con.setRequestProperty("accept-charset", "utf-8"); if (useAuth) { con.setRequestProperty("Authorization", authStr); } return con; } /** * Create a {@link HttpURLConnection} instance indicate to {@link DbCore#url} * * @return a {@link HttpURLConnection} instance */ HttpURLConnection openUrl() throws IOException { return openUrl(url); } /** * Process request content upstream. * * @param con {@link HttpURLConnection} instance * @param tuple data to be upload * @throws IOException */ static void sendRequest(HttpURLConnection con, Tuple tuple) throws IOException { // initialize String boundary = "Boundary" + Long.toHexString(System.currentTimeMillis()); // set property con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); con.setDoOutput(true); boundary = "\r\n--" + boundary; // build content to be uploaded StringBuilder builder = new StringBuilder(); for (Map.Entry<String, String> p : tuple.entrySet()) { // boundary builder.append(boundary); // field name builder.append("\r\nContent-Disposition: form-data; name=\""); builder.append(p.getKey()); builder.append('"'); //TODO filename!? // start upload builder.append("\r\n\r\n"); builder.append(p.getValue()); } builder.append(boundary); builder.append(" // upstream try (DataOutputStream writer = new DataOutputStream(con.getOutputStream())) { writer.writeUTF(builder.toString()); } } /** * Get response content. * * @param con a {@link HttpURLConnection} * @return response content * @throws IOException */ @NonNull static String getResponse(HttpURLConnection con) throws IOException { // check response code int code = con.getResponseCode(); if (code < HttpURLConnection.HTTP_OK || code >= HttpURLConnection.HTTP_MULT_CHOICE) { Log.e(DbCore.class.getName(), "unexpected HTTP response code received: " + code); } // read response StringBuilder builder = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()))) { String in; while ((in = reader.readLine()) != null) { builder.append(in); } } return builder.toString(); } }
package gameEngine; import gameAuthoring.mainclasses.AuthorController; import gameAuthoring.mainclasses.Constants; import gameAuthoring.scenes.actorBuildingScenes.TowerUpgradeGroup; import gameAuthoring.scenes.levelBuilding.EnemyCountPair; import gameAuthoring.scenes.pathBuilding.buildingPanes.BuildingPane; import gameAuthoring.scenes.pathBuilding.buildingPanes.towerRegions.Tile; import gameEngine.actors.BaseActor; import gameEngine.actors.BaseEnemy; import gameEngine.actors.BaseProjectile; import gameEngine.actors.BaseTower; import gameEngine.actors.InfoObject; import gameEngine.levels.BaseLevel; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Observable; import java.util.Observer; import java.util.Queue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Collectors; import javafx.animation.KeyFrame; import javafx.animation.Timeline; import javafx.beans.property.DoubleProperty; import javafx.beans.property.SimpleDoubleProperty; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Node; import javafx.scene.image.ImageView; import javafx.scene.layout.GridPane; import javafx.scene.layout.Pane; import javafx.util.Duration; import utilities.GSON.GSONFileReader; import utilities.GSON.GSONFileWriter; import utilities.GSON.objectWrappers.DataWrapper; import utilities.GSON.objectWrappers.GameStateWrapper; import utilities.GSON.objectWrappers.GeneralSettingsWrapper; import utilities.JavaFXutilities.imageView.CenteredImageView; import utilities.errorPopup.ErrorPopup; public class SingleThreadedEngineManager implements Observer, UpdateInterface, InformationInterface { private static final int FPS = 30; private static final double ONE_SECOND_IN_MILLIS = 1000.0; private static final double FRAME_DURATION = 1000.0 / 30; private double myLastUpdateTime; private Timeline myTimeline; private double myUpdateRate; private AtomicBoolean myReadyToPlay; protected RangeRestrictedCollection<BaseTower> myTowerGroup; private RangeRestrictedCollection<BaseEnemy> myEnemyGroup; private RangeRestrictedCollection<BaseProjectile> myProjectileGroup; private double duration; private List<BaseLevel> myLevels; private BaseLevel myCurrentLevel; private int myCurrentLevelIndex; private GridPane myValidRegions; private SimpleDoubleProperty myGold; private Map<String, BaseTower> myPrototypeTowerMap; private double myIntervalBetweenEnemies; private Queue<BaseEnemy> myEnemiesToAdd; private SimpleDoubleProperty myHealth; private SimpleDoubleProperty myEarthquakeMagnitude; private Map<Node, BaseTower> myNodeToTower; private Collection<TowerInfoObject> myTowerInformation; protected GSONFileReader myFileReader; protected GSONFileWriter myFileWriter; private TowerTileGrid myTowerLocationByGrid; private GridPane myTowerTiles; private double myFieldWidth; private double myFieldHeight; private boolean myPausedFlag; private String myCurrentGameName; private SimpleDoubleProperty myCurrentLevelProperty; private SimpleDoubleProperty myWinStatus; public SingleThreadedEngineManager () { myReadyToPlay = new AtomicBoolean(false); myEnemyGroup = new RangeRestrictedCollection<>(); myTowerGroup = new RangeRestrictedCollection<>(); myProjectileGroup = new RangeRestrictedCollection<>(); myValidRegions = new GridPane(); myTowerInformation = new ArrayList<>(); myEnemiesToAdd = new LinkedList<>(); myTimeline = createTimeline(); myCurrentLevelIndex = -1; myNodeToTower = new HashMap<>(); myPrototypeTowerMap = new HashMap<>(); myFileReader = new GSONFileReader(); myFileWriter = new GSONFileWriter(); myUpdateRate = 1; myGold = new SimpleDoubleProperty(); myHealth = new SimpleDoubleProperty(); myLastUpdateTime = -1; myPausedFlag = true; myEarthquakeMagnitude = new SimpleDoubleProperty(); myTowerLocationByGrid = new TowerTileGrid(20, 20); myCurrentLevelProperty = new SimpleDoubleProperty(1); myWinStatus = new SimpleDoubleProperty(0); } public void setEarthquakeMagnitude (double magnitude) { myEarthquakeMagnitude.set(magnitude); } @Override public double getEarthquakeMagnitude () { return myEarthquakeMagnitude.get(); } @Override public GridPane getReferencePane () { return myTowerTiles; } @Override public TowerTileGrid getExistingTowerTiles () { return myTowerLocationByGrid; } public SingleThreadedEngineManager (Pane engineGroup) { this(); addGroups(engineGroup); } protected void addGroups (Pane engineGroup) { engineGroup.getChildren().add(myTowerGroup); engineGroup.getChildren().add(myProjectileGroup); engineGroup.getChildren().add(myEnemyGroup); myFieldWidth = engineGroup.getWidth(); myFieldHeight = engineGroup.getHeight(); } @Override public double getMyGold () { return myGold.get(); } public DoubleProperty getGoldProperty () { return myGold; } @Override public void setMyGold (double value) { myGold.set(value); } @Override public double getMyHealth () { return myHealth.get(); } public DoubleProperty getHealthProperty () { return myHealth; } @Override public void setMyHealth (double value) { myHealth.set(value); } public void revertToOriginalSpeed () { changeRunSpeed(1); } public void changeRunSpeed (double magnitude) { if (magnitude > 0.0) { myUpdateRate = magnitude; } } public String getTowerName (ImageView node) { BaseTower tower = myNodeToTower.get(node); return tower == null ? null : tower.toString(); } public void removeTower (ImageView node) { BaseTower tower = myNodeToTower.get(node); myNodeToTower.remove(node); myTowerGroup.remove(tower); setTowerTileStatus(tower, false); } public ImageView addTower (String identifier, double x, double y) { BaseTower prototypeTower = myPrototypeTowerMap.get(identifier); BaseTower newTower = (BaseTower) prototypeTower.copy(); CenteredImageView newTowerNode = newTower.getNode(); newTowerNode.setXCenter(x); newTowerNode.setYCenter(y); newTowerNode.setVisible(true); myTowerGroup.add(newTower); myNodeToTower.put(newTowerNode, newTower); setTowerTileStatus(newTower, true); newTower.addObserver(this); return newTowerNode; } private void setTowerTileStatus (BaseTower tower, boolean towerTileStatus) { Node towerNode = tower.getNode(); Collection<Node> towerTiles = getIntersectingTowerTileNode(towerNode, myTowerTiles.getChildren()); for (Node tileNode : towerTiles) { Tile tile = (Tile) tileNode; int row = tile.getRow(); int col = tile.getColumn(); myTowerLocationByGrid.setTowerTile(row, col, towerTileStatus); } } private Collection<Node> getIntersectingTowerTileNode (Node towerNode, Collection<Node> nodeList) { List<Node> towerTiles = nodeList.stream() .filter(node -> node.intersects(towerNode.getBoundsInLocal())) .collect(Collectors.toList()); return towerTiles; } private Timeline createTimeline () { EventHandler<ActionEvent> frameEvent = new EventHandler<ActionEvent>() { @Override public void handle (ActionEvent event) { if (myReadyToPlay.get()) { double frameStart = System.currentTimeMillis(); double adjustedUpdateInterval = FRAME_DURATION / myUpdateRate; if (myUpdateRate >= 1.0 || frameStart - myLastUpdateTime >= adjustedUpdateInterval) { myLastUpdateTime = frameStart; double updatedTime = System.currentTimeMillis(); do { double updateStart = System.currentTimeMillis(); gameUpdate(); double updateEnd = System.currentTimeMillis(); updatedTime += Math.max(updateEnd - updateStart, adjustedUpdateInterval); } while (updatedTime - frameStart < FRAME_DURATION); } myTowerLocationByGrid.setAsNotChanged(); } } }; KeyFrame keyFrame = new KeyFrame(Duration.millis(FRAME_DURATION), frameEvent); Timeline timeline = new Timeline(FPS, keyFrame); timeline.setCycleCount(Timeline.INDEFINITE); return timeline; } private void gameUpdate () { addEnemies(); updateActors(myTowerGroup); updateActors(myEnemyGroup); updateActors(myProjectileGroup); duration if (myEnemyGroup.getChildren().size() <= 0) { onLevelEnd(); } myTowerGroup.clearAndExecuteRemoveBuffer(); myEnemyGroup.clearAndExecuteRemoveBuffer(); myProjectileGroup.clearAndExecuteRemoveBuffer(); if(myHealth.get() <= 0){ onGameEnd(); } } private void onGameEnd() { myHealth.set(0); myWinStatus.set(-1); pause(); } protected void onLevelEnd () { duration = 0; pause(); myProjectileGroup.clear(); if( myLevels != null ) { loadNextLevel(); } } private void addEnemies () { if (duration <= 0) { duration += myIntervalBetweenEnemies; BaseEnemy enemy = myEnemiesToAdd.poll(); if (enemy == null) return; enemy.addObserver(this); myEnemyGroup.add(enemy); } } private void updateActors ( RangeRestrictedCollection<? extends BaseActor> actorGroup) { for (BaseActor actor : actorGroup) { if (actor.isDead()) { actorGroup.addActorToRemoveBuffer(actor); } else { actor.update(this); } if (!isInRangeOfField(actor)) { actor.died(); } } } private boolean isInRangeOfField (BaseActor actor) { double actorX = actor.getX(); double actorY = actor.getY(); return 0 <= actorX && actorX <= myFieldWidth && 0 <= actorY && actorY <= myFieldHeight; } private InfoObject getRequiredInformation (BaseActor actor) { Collection<Class<? extends BaseActor>> infoTypes = actor.getTypes(); List<BaseActor> enemyList = new ArrayList<>(); List<BaseActor> towerList = new ArrayList<>(); List<BaseActor> projectileList = new ArrayList<>(); for (Class<? extends BaseActor> infoType : infoTypes) { if (BaseEnemy.class.isAssignableFrom(infoType)) { enemyList = myEnemyGroup.getActorsInRange(actor); } if (BaseTower.class.isAssignableFrom(infoType)) { towerList = myTowerGroup.getActorsInRange(actor); } if (BaseProjectile.class.isAssignableFrom(infoType)) { projectileList = myProjectileGroup.getActorsInRange(actor); } } return new InfoObject(enemyList, towerList, projectileList, myTowerLocationByGrid, myTowerTiles); } @Override public List<BaseActor> getRequiredActors (BaseActor actor, Class<? extends BaseActor> infoType) { List<BaseActor> list = new ArrayList<>(); if (BaseEnemy.class.isAssignableFrom(infoType)) { list = myEnemyGroup.getActorsInRange(actor); } if (BaseTower.class.isAssignableFrom(infoType)) { list = myTowerGroup.getActorsInRange(actor); } if (BaseProjectile.class.isAssignableFrom(infoType)) { list = myProjectileGroup.getActorsInRange(actor); } return list; } public boolean checkNewPath () { return myTowerLocationByGrid.hasBeenChanged(); } public void pause () { myTimeline.pause(); myPausedFlag = true; } public void resume () { myTimeline.play(); myPausedFlag = false; } public Collection<TowerInfoObject> getAllTowerTypeInformation () { if (!myReadyToPlay.get()) { return null; } return myTowerInformation; } public void initializeGame (String directory) { String[] splitDirectory = directory.split("/"); myCurrentGameName = splitDirectory[splitDirectory.length - 1]; myTowerGroup.clear(); myEnemyGroup.clear(); myProjectileGroup.clear(); String correctedDirectory = directory += "/"; myReadyToPlay.set(false); loadTowers(correctedDirectory); loadLevelFile(correctedDirectory); loadLocations(correctedDirectory); loadGameSettings(correctedDirectory); myReadyToPlay.set(true); loadNextLevel(); } private void loadGameSettings (String directory) { GeneralSettingsWrapper settingsWrapper = myFileReader.readGeneralSettingsWrapper(directory); myGold.set(settingsWrapper.getStartingCash()); myHealth.set(settingsWrapper.getStartingHealth()); } private void loadLocations (String dir) { boolean[][] validRegions = myFileReader .readTowerRegionsFromGameDirectory(dir); myTowerLocationByGrid = new TowerTileGrid(validRegions.length, validRegions[0].length); myValidRegions = createGameSizedGridPane(); myTowerTiles = createGameSizedGridPane(); for (int row = 0; row < validRegions.length; row++) { for (int col = 0; col < validRegions[0].length; col++) { if (validRegions[row][col]) { Tile tile = new Tile(row, col); tile.setVisible(false); myValidRegions.add(tile, col, row); } Tile towerTile = new Tile(row, col); towerTile.setVisible(false); myTowerTiles.add(towerTile, col, row); } } } private GridPane createGameSizedGridPane () { GridPane pane = new GridPane(); pane.setPrefSize(BuildingPane.DRAW_SCREEN_WIDTH, AuthorController.SCREEN_HEIGHT); return pane; } public boolean validateTower (double x, double y) { return !(listCollidesWith(myTowerGroup.getChildren(), x, y)) && listCollidesWith(myValidRegions.getChildren(), x, y); } private boolean listCollidesWith (List<Node> list, double x, double y) { return list.stream().filter(node -> node.contains(x, y)).count() > 0; } public boolean checkGold (TowerInfoObject towerInfoObject) { return towerInfoObject.getBuyCost() <= myGold.get(); } public void loadTowers (String directory) { List<TowerUpgradeGroup> availableTowers = myFileReader .readTowersFromGameDirectory(directory); for (TowerUpgradeGroup towerGroup : availableTowers) { TowerInfoObject prevInfoObject = null; for (BaseTower tower : towerGroup) { String towerName = tower.toString(); myPrototypeTowerMap.put(towerName, tower); TowerInfoObject currentInfoObject = new TowerInfoObject( towerName, tower.getImagePath(), tower.getBuyCost(), tower.getSellCost(), tower.getRangeProperty()); if (prevInfoObject != null) { prevInfoObject.setNextTower(currentInfoObject); } else { myTowerInformation.add(currentInfoObject); } prevInfoObject = currentInfoObject; } if (prevInfoObject != null) { prevInfoObject.setNextTower(new NullTowerInfoObject()); } } } private void loadLevelFile (String directory) { myLevels = myFileReader.readLevelsFromGameDirectory(directory); } private void loadNextLevel () { myCurrentLevelIndex += 1; if (myCurrentLevelIndex < myLevels.size()) { myCurrentLevelProperty.set(myCurrentLevelIndex + 1); loadLevel(myLevels.get(myCurrentLevelIndex)); } else { myWinStatus.set(1); } } public SimpleDoubleProperty getWinStatus() { return myWinStatus; } public SimpleDoubleProperty getCurrentLevelProperty() { return myCurrentLevelProperty; } public void loadLevel (BaseLevel level) { int levelDuration = level.getDuration(); Collection<EnemyCountPair> enemies = level.getEnemyCountPairs(); for (EnemyCountPair enemyPair : enemies) { BaseEnemy enemy = enemyPair.getMyEnemy(); for (int count = 0; count < enemyPair.getMyNumEnemies(); count++) { BaseEnemy newEnemy = (BaseEnemy) enemy.copy(); myEnemiesToAdd.add(newEnemy); } } myIntervalBetweenEnemies = levelDuration * FPS / myEnemiesToAdd.size(); myCurrentLevel = level; } public void loadAuthoringLevel (BaseLevel level) { pause(); myEnemyGroup.clear(); myEnemiesToAdd.clear(); loadLevel(level); myReadyToPlay.set(true); } @Override public void update (Observable o, Object arg) { if (arg instanceof updateObject) { ((updateObject) arg).update(this); } else if (o instanceof BaseActor && arg != null) { if (arg instanceof BaseTower) { myTowerGroup.add((BaseTower) arg); } else if (arg instanceof BaseEnemy) { myTowerGroup.add((BaseTower) arg); } else if (arg instanceof BaseProjectile) { myProjectileGroup.add((BaseProjectile) arg); } } } public void saveState (String directory, String fileName) { if (myPausedFlag) { String joinedFileName = directory + "/" + fileName + ".json"; try { List<DataWrapper> wrappedTowers = wrapTowers(); GameStateWrapper gameState = new GameStateWrapper( myCurrentGameName, myCurrentLevelIndex, myHealth.get(), myGold.get(), wrappedTowers); myFileWriter.writeGameStateToJSon(joinedFileName, gameState); } catch (Exception ex) { new ErrorPopup("Error writing state"); } } } private List<DataWrapper> wrapTowers () { ArrayList<DataWrapper> wrappedTowers = new ArrayList<>(); for (BaseTower tower : myTowerGroup) { DataWrapper wrappedTower = new DataWrapper(tower); wrappedTowers.add(wrappedTower); } return wrappedTowers; } public void clear () { if (myPausedFlag) { myTowerGroup.clear(); myEnemyGroup.clear(); myProjectileGroup.clear(); myLastUpdateTime = -1; myEnemiesToAdd.clear(); myNodeToTower.clear(); myTowerInformation.clear(); } } public void loadState (String gameFile) { if (myPausedFlag) { try { clear(); GameStateWrapper gameState = myFileReader .readGameStateFromJSon(gameFile); if (gameState.getName().equals(myCurrentGameName)) { myGold.set(gameState.getMoney()); myHealth.set(gameState.getHealth()); myCurrentLevelIndex = gameState.getLevel(); myCurrentLevelProperty.set(myCurrentLevelIndex + 1); loadLevel(myLevels.get(myCurrentLevelIndex)); List<DataWrapper> towers = gameState.getTowerWrappers(); for (DataWrapper wrappedTower : towers) { addTower(wrappedTower.getName(), wrappedTower.getX(), wrappedTower.getY()); } } else { new ErrorPopup("Save state does not correspond to this game"); } } catch (Exception ex) { new ErrorPopup("Problem loading save file"); } } } public ImageView upgrade (ImageView n, String name) { removeTower(n); return addTower(name, ((CenteredImageView) n).getXCenter(), ((CenteredImageView) n).getYCenter()); } public void sellTower (ImageView n) { myGold.set(myNodeToTower.get(n).getSellCost() + myGold.get()); removeTower(n); } }
package com.exedio.cope.lib; import com.exedio.cope.lib.IntegrityViolationException; import com.exedio.cope.lib.Cope; import com.exedio.cope.testmodel.FirstSub; import com.exedio.cope.testmodel.SecondSub; public class HierarchyTest extends DatabaseLibTest { public void testHierarchy() throws IntegrityViolationException { final FirstSub firstItem = new FirstSub(0); deleteOnTearDown(firstItem); assertID(0, firstItem); assertEquals(0, firstItem.getSuperInt()); assertEquals(null, firstItem.getFirstSubString()); firstItem.setSuperInt(2); assertEquals(2, firstItem.getSuperInt()); assertEquals(null, firstItem.getFirstSubString()); firstItem.setFirstSubString("firstSubString"); assertEquals(2, firstItem.getSuperInt()); assertEquals("firstSubString", firstItem.getFirstSubString()); firstItem.passivate(); assertEquals(2, firstItem.getSuperInt()); assertEquals("firstSubString", firstItem.getFirstSubString()); final SecondSub secondItem = new SecondSub(2); deleteOnTearDown(secondItem); assertID(1, secondItem); assertEquals(2, secondItem.getSuperInt()); assertEquals(null, secondItem.getFirstSubString()); final SecondSub secondItem2 = new SecondSub(3); deleteOnTearDown(secondItem2); assertID(2, secondItem2); final FirstSub firstItem2 = new FirstSub(4); deleteOnTearDown(firstItem2); assertID(3, firstItem2); assertEquals(list(firstItem), firstItem.TYPE.search(Cope.equal(firstItem.firstSubString, "firstSubString"))); assertEquals(list(), firstItem.TYPE.search(Cope.equal(firstItem.firstSubString, "firstSubStringX"))); } }
package edu.uml.cs.isense.api; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ConnectException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Iterator; import java.util.Locale; import java.util.Random; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.entity.mime.content.StringBody; import org.json.JSONArray; import org.json.JSONObject; import edu.uml.cs.isense.objects.RDataSet; import edu.uml.cs.isense.objects.RPerson; import edu.uml.cs.isense.objects.RProject; import edu.uml.cs.isense.objects.RProjectField; /** * A class which allows Android applications to interface with the iSENSE * website. Given a singleton instance of this class, functions can be called * through an AsyncTask. * * @author Nick Ver Voort, Jeremy Poulin, and Mike Stowell of the iSENSE * Android-Development Team * */ public class API { private final String version_major = "4"; private final String version_minor = "1"; private String version; private static API instance = null; private String baseURL = ""; private final String publicURL = "http://isenseproject.org/api/v1"; private final String devURL = "http://rsense-dev.cs.uml.edu/api/v1"; String authToken = ""; RPerson currentUser; private boolean usingLive = true; public static final int CREATED_AT = 0; public static final int UPDATED_AT = 1; private String email, password; public enum TargetType { PROJECT, DATA_SET }; /** * Constructor not to be called by a user of the API Users should call * getInstance instead, which will call this constructor if necessary */ private API() { baseURL = publicURL; } /** * Gets the one instance of the API class (instead of recreating a new one * every time). Functions as a constructor if the current instance is null. * * @return current or new API */ public static API getInstance() { if (instance == null) { instance = new API(); } return instance; } /** * Log in to iSENSE. Stores email and password variables so authenticated * functions later will work * * @param p_email * The email address of the user to log in as * @param p_password * The password of the user to log in as */ public RPerson createSession(String p_email, String p_password) { String reqResult = ""; try { reqResult = makeRequest(baseURL, "users/myInfo", "email=" + URLEncoder.encode(p_email, "UTF-8") + "&password=" + URLEncoder.encode(p_password, "UTF-8"), "GET", null); JSONObject j = new JSONObject(reqResult); if (j.getString("name") != null) { email = p_email; password = p_password; RPerson you = new RPerson(); you.name = j.getString("name"); you.gravatar = j.getString("gravatar"); currentUser = you; you.successfulLogin = true; return you; } else { // not a valid person so get error message RPerson you = new RPerson(); JSONObject jobj = new JSONObject(reqResult); you.serverErrorMessage = jobj.getString("msg"); return you; } } catch (Exception e) { // Something went wrong so create a new RPerson object with // default values and get the error message from the server try { RPerson you = new RPerson(); JSONObject jobj = new JSONObject(reqResult); you.serverErrorMessage = jobj.getString("msg"); return you; } catch (Exception e2) { try { RPerson you = new RPerson(); JSONObject jobj = new JSONObject(reqResult); you.serverErrorMessage = jobj.getString("error"); return you; } catch (Exception e3) { RPerson you = new RPerson(); return you; } } } } /** * Log out of iSENSE */ public void deleteSession() { email = ""; password = ""; currentUser = null; } public RPerson getCurrentUser() { return currentUser; } /** * Verifies whether a given contributor key will work for a project * * @param projectId * @param conKey * @return True is the key is valid for that project, false if it is not */ public boolean validateKey(int projectId, String conKey) { // FIX this function will never be implemented, remove it and rework // apps to not need it return true; } /** * Retrieves multiple projects off of iSENSE. * * @param page * Which page of results to start from. 1-indexed * @param perPage * How many results to display per page * @param descending * Whether to display the results in descending order (true) or * ascending order (false) * @param search * A string to search all projects for * @return An ArrayList of Project objects */ public ArrayList<RProject> getProjects(int page, int perPage, boolean descending, int sortOn, String search) { ArrayList<RProject> result = new ArrayList<RProject>(); try { String order = descending ? "DESC" : "ASC"; String sortMode = ""; if (sortOn == CREATED_AT) { sortMode = "created_at"; } else { sortMode = "updated_at"; } String reqResult = makeRequest(baseURL, "projects", "page=" + page + "&per_page=" + perPage + "&sort=" + sortMode + "&order=" + order + "&search=" + URLEncoder.encode(search, "UTF-8"), "GET", null); JSONArray j = new JSONArray(reqResult); for (int i = 0; i < j.length(); i++) { JSONObject inner = j.getJSONObject(i); RProject proj = new RProject(); proj.project_id = inner.getInt("id"); proj.name = inner.getString("name"); proj.url = inner.getString("url"); proj.hidden = inner.getBoolean("hidden"); proj.featured = inner.getBoolean("featured"); proj.like_count = inner.getInt("likeCount"); proj.timecreated = inner.getString("createdAt"); proj.owner_name = inner.getString("ownerName"); proj.owner_url = inner.getString("ownerUrl"); result.add(proj); } } catch (Exception e) { e.printStackTrace(); } return result; } /** * Retrieves information about a single project on iSENSE * * @param projectId * The ID of the project to retrieve * @return A Project object or null if none is found */ public RProject getProject(int projectId) { RProject proj = new RProject(); try { String reqResult = makeRequest(baseURL, "projects/" + projectId, "", "GET", null); JSONObject j = new JSONObject(reqResult); proj.project_id = j.getInt("id"); proj.name = j.getString("name"); proj.url = j.getString("url"); proj.hidden = j.getBoolean("hidden"); proj.featured = j.getBoolean("featured"); proj.like_count = j.getInt("likeCount"); proj.timecreated = j.getString("createdAt"); proj.owner_name = j.getString("ownerName"); proj.owner_url = j.getString("ownerUrl"); } catch (Exception e) { e.printStackTrace(); return null; } return proj; } /** * Creates a new project on iSENSE. The Field objects in the second * parameter must have at a type and a name, and can optionally have a unit. * This is an authenticated function. * * @param projectName * The name of the new project to be created * @param fields * An ArrayList of field objects that will become the fields on * iSENSE. * @return The ID of the created project */ public UploadInfo createProject(String projectName, ArrayList<RProjectField> fields) { UploadInfo info = new UploadInfo(); String projResult = ""; String fieldResult = ""; try { JSONObject postData = new JSONObject(); postData.put("email", email); postData.put("password", password); postData.put("project_name", projectName); projResult = makeRequest(baseURL, "projects", "", "POST", postData); JSONObject jobj = new JSONObject(projResult); info.projectId = jobj.getInt("id"); // Add Fields to Project for (RProjectField rpf : fields) { JSONObject mField = new JSONObject(); mField.put("project_id", info.projectId); mField.put("field_type", rpf.type); mField.put("name", rpf.name); mField.put("unit", rpf.unit); JSONObject postData2 = new JSONObject(); postData2.put("email", email); postData2.put("password", password); postData2.put("field", mField); fieldResult = makeRequest(baseURL, "fields", "", "POST", postData2); JSONObject fieldObj = new JSONObject(fieldResult); // Failed to add field to project, return failure and error // message if (fieldObj.getInt("id") == -1) { try { info.errorMessage = fieldObj.getString("msg"); info.success = false; return info; } catch (Exception e2) { try { info.errorMessage = fieldObj.getString("error"); info.success = false; return info; } catch (Exception e3) { info.errorMessage = projResult; } } } } info.success = true; return info; } catch (Exception e) { try { JSONObject jobj = new JSONObject(projResult); info.errorMessage = jobj.getString("msg"); } catch (Exception e2) { try { JSONObject jobj = new JSONObject(projResult); info.errorMessage = jobj.getString("error"); } catch (Exception e3) { info.errorMessage = projResult; } } } info.projectId = -1; info.success = false; return info; } public boolean deleteProject(int projectId) { try { makeRequest(baseURL, "projects/" + projectId, "authenticity_token=" + URLEncoder.encode(authToken, "UTF-8"), "DELETE", null); return true; } catch (Exception e) { e.printStackTrace(); } return false; } /** * Gets all of the fields associated with a project. * * @param projectId * The unique ID of the project whose fields you want to see * @return An ArrayList of ProjectField objects */ public ArrayList<RProjectField> getProjectFields(int projectId) { ArrayList<RProjectField> rpfs = new ArrayList<RProjectField>(); try { String reqResult = makeRequest(baseURL, "projects/" + projectId, "?recur=true", "GET", null); JSONObject j = new JSONObject(reqResult); JSONArray j2 = j.getJSONArray("fields"); for (int i = 0; i < j2.length(); i++) { JSONObject inner = j2.getJSONObject(i); RProjectField rpf = new RProjectField(); rpf.field_id = inner.getInt("id"); rpf.name = inner.getString("name"); rpf.type = inner.getInt("type"); rpf.unit = inner.getString("unit"); rpf.restrictions = new ArrayList<String>(); System.out.println("Restrictions " + inner.get("restrictions")); rpfs.add(rpf); } } catch (Exception e) { e.printStackTrace(); } return rpfs; } /** * Retrieve a data set from iSENSE, with it's data field filled in The * internal data set will be converted to column-major format, to make it * compatible with the uploadDataSet function * * @param dataSetId * The unique ID of the data set to retrieve from iSENSE * @return A DataSet object */ public RDataSet getDataSet(int dataSetId) { RDataSet result = new RDataSet(); try { String reqResult = makeRequest(baseURL, "data_sets/" + dataSetId, "recur=true", "GET", null); JSONObject j = new JSONObject(reqResult); result.ds_id = j.getInt("id"); result.name = j.getString("name"); result.url = j.getString("url"); result.timecreated = j.getString("createdAt"); result.fieldCount = j.getInt("fieldCount"); result.datapointCount = j.getInt("datapointCount"); result.data = rowsToCols(new JSONObject().put("data", j.getJSONArray("data"))); System.out.println(result.data); result.project_id = j.getJSONObject("project").getInt("id"); } catch (Exception e) { e.printStackTrace(); } return result; } /** * Gets all the data sets associated with a project The data sets returned * by this function do not have their data field filled. * * @param projectId * The project ID whose data sets you want * @return An ArrayList of Data Set objects, with their data fields left * null */ public ArrayList<RDataSet> getDataSets(int projectId) { ArrayList<RDataSet> result = new ArrayList<RDataSet>(); try { String reqResult = makeRequest(baseURL, "projects/" + projectId, "recur=true", "GET", null); JSONObject j = new JSONObject(reqResult); JSONArray dataSets = j.getJSONArray("dataSets"); for (int i = 0; i < dataSets.length(); i++) { RDataSet rds = new RDataSet(); JSONObject inner = dataSets.getJSONObject(i); rds.ds_id = inner.getInt("id"); rds.name = inner.getString("name"); rds.hidden = inner.getBoolean("hidden"); rds.url = inner.getString("url"); rds.timecreated = inner.getString("createdAt"); rds.fieldCount = inner.getInt("fieldCount"); rds.datapointCount = inner.getInt("datapointCount"); result.add(rds); } } catch (Exception e) { e.printStackTrace(); } return result; } /** * Upload a dataset to iSENSE while logged in * * @param projectId * The ID of the project to upload data to * @param data * The data to be uploaded. Must be in column-major format to * upload correctly * @param datasetName * The name of the dataset * @return The integer ID of the newly uploaded dataset, or -1 if upload * fails */ public UploadInfo uploadDataSet(int projectId, JSONObject data, String datasetName) { UploadInfo info = new UploadInfo(); datasetName += appendedTimeStamp(); String reqResult = ""; JSONObject requestData = new JSONObject(); try { requestData.put("email", email); requestData.put("password", password); requestData.put("title", datasetName); requestData.put("data", data); reqResult = makeRequest(baseURL, "projects/" + projectId + "/jsonDataUpload", "", "POST", requestData); JSONObject jobj = new JSONObject(reqResult); info.dataSetId = jobj.getInt("id"); if (jobj.getInt("id") != -1) { info.success = true; } return info; } catch (Exception e) { try { JSONObject jobj = new JSONObject(reqResult); info.errorMessage = jobj.getString("msg"); } catch (Exception e2) { try { JSONObject jobj = new JSONObject(reqResult); info.errorMessage = jobj.getString("error"); } catch (Exception e3) { info.errorMessage = reqResult; } } } info.success = false; info.dataSetId = -1; return info; } /** * Upload a dataset to iSENSE with a contributor key * * @param projectId * The ID of the project to upload data to * @param data * The data to be uploaded. Must be in column-major format to * upload correctly * @param dataName * The Dataset name * @param conKey * The Contributor Key * @param conName * The Contributor name * @return The integer ID of the newly uploaded dataset, or -1 if upload * fails */ public UploadInfo uploadDataSet(int projectId, JSONObject data, String dataName, String conKey, String conName) { UploadInfo info = new UploadInfo(); JSONObject requestData = new JSONObject(); String reqResult = ""; try { requestData.put("contribution_key", conKey); requestData.put("contributor_name", conName); requestData.put("data", data); requestData.put("title", dataName + appendedTimeStamp()); reqResult = makeRequest(baseURL, "projects/" + projectId + "/jsonDataUpload", "", "POST", requestData); JSONObject jobj = new JSONObject(reqResult); info.dataSetId = jobj.getInt("id"); if (jobj.getInt("id") != -1) { info.success = true; } return info; } catch (Exception e) { try { JSONObject jobj = new JSONObject(reqResult); info.errorMessage = jobj.getString("msg"); } catch (Exception e2) { try { JSONObject jobj = new JSONObject(reqResult); info.errorMessage = jobj.getString("error"); } catch (Exception e3) { info.errorMessage = reqResult; } } } info.success = false; info.dataSetId = -1; return info; } /** * Append new rows of data to the end of an existing data set ** This * currently works for horrible reasons regarding how the website handles * edit data sets ** Will fix hopefully --J * * @param dataSetId * The ID of the data set to append to * @param newData * The new data to append * * @return success or failure */ public UploadInfo appendDataSetData(int dataSetId, JSONObject newData) { UploadInfo info = new UploadInfo(); String reqResult = ""; JSONObject requestData = new JSONObject(); try { requestData.put("email", email); requestData.put("password", password); requestData.put("id", dataSetId); requestData.put("data", newData); reqResult = makeRequest(baseURL, "data_sets/" + "/append", "", "POST", requestData); JSONObject jobj = new JSONObject(reqResult); info.dataSetId = jobj.getInt("id"); if (jobj.getInt("id") != -1) { info.success = true; } return info; } catch (Exception e) { try { JSONObject jobj = new JSONObject(reqResult); info.errorMessage = jobj.getString("msg"); } catch (Exception e2) { try { JSONObject jobj = new JSONObject(reqResult); info.errorMessage = jobj.getString("error"); } catch (Exception e3) { info.errorMessage = reqResult; } } } info.success = false; info.dataSetId = -1; return info; } public UploadInfo createKey(String project, String keyname, String key) { UploadInfo info = new UploadInfo(); String reqResult = ""; JSONObject requestData = new JSONObject(); JSONObject contrib_key = new JSONObject(); try { contrib_key.put("project_id", project); contrib_key.put("name", keyname); contrib_key.put("key", key); requestData.put("email", email); requestData.put("password", password); requestData.put("contrib_key", contrib_key); reqResult = makeRequest(baseURL, "projects/" + project + "/add_key", "", "POST", requestData); JSONObject jobj = new JSONObject(reqResult); System.out.println(reqResult.toString()); if (jobj.getString("msg").equals("Success")) { info.success = true; } return info; } catch (Exception e) { try { JSONObject jobj = new JSONObject(reqResult); info.errorMessage = jobj.getString("msg"); } catch (Exception e2) { try { JSONObject jobj = new JSONObject(reqResult); info.errorMessage = jobj.getString("error"); } catch (Exception e3) { info.errorMessage = reqResult; } } } info.success = false; info.dataSetId = -1; return info; } /** * Uploads a file to the media section of a project while logged in * * @param dataId * The ID of the thing you're uploading to * @param mediaToUpload * The file to upload * @param ttype * The type of the target (project or dataset) * @return The media object ID for the media uploaded or -1 if upload fails */ public UploadInfo uploadMedia(int dataId, File mediaToUpload, TargetType ttype) { UploadInfo info = new UploadInfo(); String output = ""; try { URL url = new URL(baseURL + "/media_objects/"); HttpURLConnection connection = (HttpURLConnection) url .openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); MultipartEntity entity = new MultipartEntity(); entity.addPart( "upload", new FileBody(mediaToUpload, URLConnection .guessContentTypeFromName(mediaToUpload.getName()))); entity.addPart("email", new StringBody(email)); entity.addPart("password", new StringBody(password)); entity.addPart("type", new StringBody( (ttype == TargetType.PROJECT) ? "project" : "data_set")); entity.addPart("id", new StringBody("" + dataId)); connection.setRequestProperty("Content-Type", entity .getContentType().getValue()); connection.setRequestProperty("Accept", "application/json"); OutputStream out = connection.getOutputStream(); try { entity.writeTo(out); } finally { out.close(); } InputStream in = null; try { int response = connection.getResponseCode(); if (response >= 200 && response < 300) { in = new BufferedInputStream(connection.getInputStream()); } else { in = new BufferedInputStream(connection.getErrorStream()); } } catch (FileNotFoundException e) { e.printStackTrace(); info.mediaId = -1; info.success = false; info.errorMessage = "No Connection"; return info; } try { ByteArrayOutputStream bo = new ByteArrayOutputStream(); int i = in.read(); while (i != -1) { bo.write(i); i = in.read(); } output = bo.toString(); System.out.println("Returning from uploadProjectMedia: " + output); JSONObject jobj = new JSONObject(output); info.mediaId = jobj.getInt("id"); if (jobj.getInt("id") != -1) { info.success = true; } return info; } catch (Exception e) { try { JSONObject jobj = new JSONObject(output); info.errorMessage = jobj.getString("msg"); info.mediaId = -1; info.success = false; return info; } catch (Exception e2) { JSONObject jobj = new JSONObject(output); info.errorMessage = jobj.getString("error"); info.mediaId = -1; info.success = false; return info; } } finally { in.close(); } } catch (Exception e) { e.printStackTrace(); } info.mediaId = -1; info.success = false; return info; } /** * Uploads a file to the media section of a project with a contributor key * * @param projectId * The ID of the thing you're uploading to * @param mediaToUpload * The file to upload * @param ttype * The type of the target (project or dataset) * @param conKey * The contributor key * @param conName * The contributor name * @return The media object ID for the media uploaded or -1 if upload fails */ public UploadInfo uploadMedia(int projectId, File mediaToUpload, TargetType ttype, String conKey, String conName) { UploadInfo info = new UploadInfo(); String output = ""; try { URL url = new URL(baseURL + "/media_objects/"); HttpURLConnection connection = (HttpURLConnection) url .openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); MultipartEntity entity = new MultipartEntity(); entity.addPart( "upload", new FileBody(mediaToUpload, URLConnection .guessContentTypeFromName(mediaToUpload.getName()))); entity.addPart("contribution_key", new StringBody(conKey)); entity.addPart("contributor_name", new StringBody(conName)); entity.addPart("type", new StringBody( (ttype == TargetType.PROJECT) ? "project" : "data_set")); entity.addPart("id", new StringBody("" + projectId)); connection.setRequestProperty("Content-Type", entity .getContentType().getValue()); connection.setRequestProperty("Accept", "application/json"); OutputStream out = connection.getOutputStream(); try { entity.writeTo(out); } finally { out.close(); } InputStream in = null; try { int response = connection.getResponseCode(); if (response >= 200 && response < 300) { in = new BufferedInputStream(connection.getInputStream()); } else { in = new BufferedInputStream(connection.getErrorStream()); } } catch (FileNotFoundException e) { e.printStackTrace(); info.errorMessage = "No Connection"; info.mediaId = -1; return info; } try { ByteArrayOutputStream bo = new ByteArrayOutputStream(); int i = in.read(); while (i != -1) { bo.write(i); i = in.read(); } output = bo.toString(); System.out.println("Returning from uploadProjectMedia: " + output); JSONObject jobj = new JSONObject(output); info.mediaId = jobj.getInt("id"); if (jobj.getInt("id") != -1) { info.success = true; } return info; } catch (Exception e) { try { JSONObject jobj = new JSONObject(output); info.errorMessage = jobj.getString("msg"); info.mediaId = -1; return info; } catch (Exception e2) { JSONObject jobj = new JSONObject(output); info.errorMessage = jobj.getString("error"); info.mediaId = -1; return info; } } finally { in.close(); } } catch (Exception e) { e.printStackTrace(); } info.mediaId = -1; info.success = false; return info; } /** * Makes an HTTP request and for JSON-formatted data. This call is blocking, * and so functions that call this function must not be run on the UI * thread. * * @param baseURL * The base of the URL to which the request will be made * @param path * The path to append to the request URL * @param parameters * Parameters separated by ampersands (&) * @param reqType * The request type as a string (i.e. GET or POST) * @return A String dump of a JSONObject representing the requested data */ private String makeRequest(String baseURL, String path, String parameters, String reqType, JSONObject postData) { byte[] mPostData = null; int mstat = 0; try { URL url = new URL(baseURL + "/" + path + "?" + parameters); System.out.println("Connect to: " + url); HttpURLConnection urlConnection = (HttpURLConnection) url .openConnection(); if (!reqType.equals("GET")) { urlConnection.setDoOutput(true); } urlConnection.setRequestMethod(reqType); urlConnection.setRequestProperty("Accept", "application/json"); // urlConnection.setDoOutput(true); if (postData != null) { System.out.println("Post data: " + postData); mPostData = postData.toString().getBytes(); urlConnection.setRequestProperty("Content-Length", Integer.toString(mPostData.length)); urlConnection.setRequestProperty("Content-Type", "application/json"); OutputStream out = urlConnection.getOutputStream(); out.write(mPostData); out.close(); } mstat = urlConnection.getResponseCode(); InputStream in; System.out.println("Status: " + mstat); if (mstat >= 200 && mstat < 300) { in = new BufferedInputStream(urlConnection.getInputStream()); } else { in = new BufferedInputStream(urlConnection.getErrorStream()); } try { ByteArrayOutputStream bo = new ByteArrayOutputStream(); int i = in.read(); while (i != -1) { bo.write(i); i = in.read(); } return bo.toString(); } catch (IOException e) { return ""; } finally { in.close(); } } catch (ConnectException ce) { System.err .println("Connection failed: ENETUNREACH (network not reachable)"); ce.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return "Error: status " + mstat; } /** * Switched the API instance between using the public iSENSE and the * developer iSENSE * * @param use * Whether or not to use the developer iSENSE */ public void useDev(boolean use) { baseURL = use ? devURL : publicURL; usingLive = !use; } /** * Returns whether or not the API is using dev mode. * * @return True if the API is using the development website, false * otherwise. */ public boolean isLive() { return usingLive; } /** * Directly set the base URL, rather than using the dev or production URLs * * @param newUrl * The URL to use as a base */ public void setBaseUrl(String newUrl) { baseURL = newUrl + "/api/v1"; usingLive = false; } /** * Reformats a row-major JSONObject into a column-major one * * @param original * The row-major formatted JSONObject * @return A column-major reformatted version of the original JSONObject */ public JSONObject rowsToCols(JSONObject original) { JSONObject reformatted = new JSONObject(); try { JSONArray inner = original.getJSONArray("data"); for (int i = 0; i < inner.length(); i++) { JSONObject innermost = (JSONObject) inner.get(i); Iterator<?> keys = innermost.keys(); while (keys.hasNext()) { String currKey = (String) keys.next(); JSONArray currArray = new JSONArray(); if (reformatted.has(currKey)) { currArray = reformatted.getJSONArray(currKey); } currArray.put(innermost.get(currKey)); // currArray.put(innermost.getInt(currKey)); reformatted.put(currKey, currArray); } } } catch (Exception e) { e.printStackTrace(); } return reformatted; } /** * Creates a unique date and timestamp used to append to data sets uploaded * to the iSENSE website to ensure every data set has a unique identifier. * * @return A pretty formatted date and timestamp */ private String appendedTimeStamp() { SimpleDateFormat dateFormat = new SimpleDateFormat( "MM/dd/yy, HH:mm:ss.SSS", Locale.US); Calendar cal = Calendar.getInstance(); Random r = new Random(); int rMicroseconds = r.nextInt(1000); String microString = ""; if (rMicroseconds < 10) microString = "00" + rMicroseconds; else if (rMicroseconds < 100) microString = "0" + rMicroseconds; else microString = "" + rMicroseconds; return " - " + dateFormat.format(cal.getTime()) + microString; } /** * Gets the current API version * * @return API version in MAJOR.MINOR format */ public String getVersion() { version = version_major + "." + version_minor; return version; } }
package com.parc.ccn.data.content; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import javax.xml.stream.XMLStreamException; import com.parc.ccn.config.ConfigurationException; import com.parc.ccn.data.ContentName; import com.parc.ccn.data.ContentObject; import com.parc.ccn.data.content.LinkReference.LinkObject; import com.parc.ccn.data.security.KeyLocator; import com.parc.ccn.data.security.PublisherPublicKeyDigest; import com.parc.ccn.data.util.CCNEncodableObject; import com.parc.ccn.data.util.GenericXMLEncodable; import com.parc.ccn.data.util.XMLDecoder; import com.parc.ccn.data.util.XMLEncodable; import com.parc.ccn.data.util.XMLEncoder; import com.parc.ccn.library.CCNLibrary; /** * Mapping from a collection to the underlying XML representation. * Basically a collection is a content object containing * a List of names and optionally some content authentication * information to specify whose value for each name * to take. * @author smetters * */ public class CollectionData extends GenericXMLEncodable implements XMLEncodable { /** * This should eventually be called Collection, and the Collection class deleted. */ public static class CollectionObject extends CCNEncodableObject<CollectionData> { /** * Write constructor. Doesn't save until you call save, in case you want to tweak things first. * @param name * @param data * @param library * @throws ConfigurationException * @throws IOException */ public CollectionObject(ContentName name, CollectionData data, CCNLibrary library) throws IOException { super(CollectionData.class, name, data, library); } public CollectionObject(ContentName name, CollectionData data, PublisherPublicKeyDigest publisher, KeyLocator keyLocator, CCNLibrary library) throws IOException { super(CollectionData.class, name, data, publisher, keyLocator, library); } /** * Read constructor -- opens existing object. * @param name * @param library * @throws XMLStreamException * @throws IOException * @throws ClassNotFoundException */ public CollectionObject(ContentName name, PublisherPublicKeyDigest publisher, CCNLibrary library) throws IOException, XMLStreamException { super(CollectionData.class, name, publisher, library); } public CollectionObject(ContentName name, CCNLibrary library) throws IOException, XMLStreamException { super(CollectionData.class, name, (PublisherPublicKeyDigest)null, library); } public CollectionObject(ContentObject firstBlock, CCNLibrary library) throws IOException, XMLStreamException { super(CollectionData.class, firstBlock, library); } public LinkedList<LinkReference> contents() { if (null == data()) return null; return data().contents(); } } protected static final String COLLECTION_ELEMENT = "Collection"; protected LinkedList<LinkReference> _contents = new LinkedList<LinkReference>(); public CollectionData() { } public CollectionData clone() { return new CollectionData(_contents); } public CollectionData(java.util.Collection<LinkReference> contents) { _contents.addAll(contents); // should we clone each? } public CollectionData(LinkReference [] contents) { if (contents != null) { for (int i=0; i < contents.length; ++i) { _contents.add(contents[i]); } } } public LinkedList<LinkReference> contents() { return _contents; } public LinkReference get(int i) { return contents().get(i); } public void add(LinkReference content) { _contents.add(content); } public void add(ArrayList<LinkReference> contents) { _contents.addAll(contents); } public LinkReference remove(int i) { return _contents.remove(i); } public boolean remove(LinkReference content) { return _contents.remove(content); } public boolean remove(LinkObject content) { return _contents.remove(content.getReference()); } public void removeAll() { _contents.clear(); } public int size() { return _contents.size(); } /** * XML format: * @throws XMLStreamException * */ public void decode(XMLDecoder decoder) throws XMLStreamException { _contents.clear(); decoder.readStartElement(COLLECTION_ELEMENT); LinkReference link = null; while (decoder.peekStartElement(LinkReference.LINK_ELEMENT)) { link = new LinkReference(); link.decode(decoder); add(link); } decoder.readEndElement(); } public void encode(XMLEncoder encoder) throws XMLStreamException { if (!validate()) { throw new XMLStreamException("Cannot encode " + this.getClass().getName() + ": field values missing."); } encoder.writeStartElement(COLLECTION_ELEMENT); Iterator<LinkReference> linkIt = contents().iterator(); while (linkIt.hasNext()) { LinkReference link = linkIt.next(); link.encode(encoder); } encoder.writeEndElement(); } public boolean validate() { return (null != contents()); } @Override public int hashCode() { final int PRIME = 31; int result = 1; result = PRIME * result + ((_contents == null) ? 0 : _contents.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final CollectionData other = (CollectionData) obj; if (_contents == null) { if (other._contents != null) return false; } else if (!_contents.equals(other._contents)) return false; return true; } }
package com.wegas.core.ejb; import com.wegas.core.persistence.game.Game; import com.wegas.core.persistence.game.GameModel; import com.wegas.core.persistence.game.Game_; import com.wegas.core.persistence.game.Team; import com.wegas.core.security.ejb.RoleFacade; import com.wegas.core.security.ejb.UserFacade; import com.wegas.core.security.persistence.Role; import java.util.ArrayList; import java.util.Collection; import javax.ejb.EJB; import javax.ejb.LocalBean; import javax.ejb.Stateless; import javax.persistence.*; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; /** * * @author Francois-Xavier Aeberhard <fx@red-agent.com> */ @Stateless @LocalBean public class GameFacade extends AbstractFacadeImpl<Game> { @EJB private GameModelFacade gameModelEntityFacade; @EJB private RoleFacade roleFacade; @EJB private TeamFacade teamFacade; @EJB private UserFacade userFacade; @PersistenceContext(unitName = "wegasPU") private EntityManager em; public GameFacade() { super(Game.class); } /** * Search for a game with token * * @param token * @return first game found or null */ public Game findByToken(String token) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery cq = cb.createQuery(); Root<Game> game = cq.from(Game.class); cq.where(cb.equal(game.get(Game_.token), token)); Query q = em.createQuery(cq); Game g; try { g = (Game) q.getSingleResult(); } catch (NoResultException ex) { g = null; } catch (NonUniqueResultException ex) { g = (Game) q.getResultList().get(0); } return g; // If there is more than one game with this token, use the 1st one //return (Game) q.getSingleResult(); } /** * * @param gameModelId * @param game */ public void create(Long gameModelId, Game game) { if (game.getToken() == null || game.getToken().equals("") || this.findByToken(game.getToken()) != null || teamFacade.findByToken(game.getToken()) != null) { game.setToken(Helper.genToken(10)); } GameModel gameModel = gameModelEntityFacade.find(gameModelId); gameModel.addGame(game); userFacade.getCurrentUser().getMainAccount().addPermission("Game:Edit:g" + game.getId()); userFacade.getCurrentUser().getMainAccount().addPermission("Game:View:g" + game.getId()); super.create(game); } @Override public Game update(final Long entityId, Game entity) { if (entity.getToken() == null || entity.getToken().equals("") || (this.findByToken(entity.getToken()) != null && this.findByToken(entity.getToken()).getId().compareTo(entity.getId()) != 0) || teamFacade.findByToken(entity.getToken()) != null) { entity.setToken(Helper.genToken(10)); } return super.update(entityId, entity); } @Override public void remove(Game entity) { for(Team t : entity.getTeams()){ teamFacade.remove(t); } super.remove(entity); userFacade.deleteUserPermissionByInstance("g" + entity.getId()); userFacade.deleteAllRolePermissionsById("g" + entity.getId()); } /** * * @return */ @Override public EntityManager getEntityManager() { return em; } /** * Metod return all public games * * @param userId * @return Collection<Game> */ public Collection<Game> getPublicGames(Long userId) { Role pRolle = roleFacade.findByName("Public"); Collection<Game> registerdGame = userFacade.registeredGames(userId); Collection<Game> games = new ArrayList<>(); for (String permission : pRolle.getPermissions()) { String splitedPermission[] = permission.split(":g"); String f = splitedPermission[1].substring(0, 1); if (!f.equals("m") && splitedPermission[0].equals("Game:View")) { Game g = this.find(Long.parseLong(splitedPermission[1])); this.em.detach(g); boolean registerd = false; for (Game aRegisterdG : registerdGame) { if (g.equals(aRegisterdG)) { registerd = true; break; } } if (!registerd) { g.setName(g.getGameModel().getName() + " : " + g.getName()); games.add(g); } } } return games; } }
package org.jetel.component; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.lang.ref.WeakReference; import java.net.URL; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.nio.charset.Charset; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeMap; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.dom4j.io.SAXContentHandler; import org.jetel.data.DataField; import org.jetel.data.DataRecord; import org.jetel.data.Defaults; import org.jetel.data.StringDataField; import org.jetel.data.sequence.Sequence; import org.jetel.exception.AttributeNotFoundException; import org.jetel.exception.BadDataFormatException; import org.jetel.exception.ComponentNotReadyException; import org.jetel.exception.ConfigurationProblem; import org.jetel.exception.ConfigurationStatus; import org.jetel.exception.ConfigurationStatus.Priority; import org.jetel.exception.ConfigurationStatus.Severity; import org.jetel.exception.JetelException; import org.jetel.exception.XMLConfigurationException; import org.jetel.graph.Node; import org.jetel.graph.OutputPort; import org.jetel.graph.Result; import org.jetel.graph.TransformationGraph; import org.jetel.metadata.DataFieldMetadata; import org.jetel.metadata.DataRecordMetadata; import org.jetel.sequence.PrimitiveSequence; import org.jetel.util.AutoFilling; import org.jetel.util.ReadableChannelIterator; import org.jetel.util.file.FileURLParser; import org.jetel.util.file.FileUtils; import org.jetel.util.property.ComponentXMLAttributes; import org.jetel.util.property.PropertyRefResolver; import org.jetel.util.property.RefResFlag; import org.jetel.util.string.StringUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * <h3>XMLExtract Component</h3> * * <!-- Provides the logic to parse a xml file and filter to different ports based on * a matching element. The element and all children will be turned into a * Data record --> * * <table border="1"> * <th>Component:</th> * <tr><td><h4><i>Name:</i></h4></td> * <td>XMLExtract</td></tr> * <tr><td><h4><i>Category:</i></h4></td> * <td></td></tr> * <tr><td><h4><i>Description:</i></h4></td> * <td>Provides the logic to parse a xml file and filter to different ports based on * a matching element. The element and all children will be turned into a * Data record.</td></tr> * <tr><td><h4><i>Inputs:</i></h4></td> * <td>0</td></tr> * <tr><td><h4><i>Outputs:</i></h4></td> * <td>Output port[0] defined/connected. Depends on mapping definition.</td></tr> * <tr><td><h4><i>Comment:</i></h4></td> * <td></td></tr> * </table> * <br> * <table border="1"> * <th>XML attributes:</th> * <tr><td><b>type</b></td><td>"XML_EXTRACT"</td></tr> * <tr><td><b>id</b></td><td>component identification</td> * <tr><td><b>sourceUri</b></td><td>location of source XML data to process</td> * <tr><td><b>useNestedNodes</b></td><td><b>true</b> if nested unmapped XML elements will be used as data source; <b>false</b> if will be ignored</td> * <tr><td><b>mapping</b></td><td>&lt;mapping&gt;</td> * </tr> * </table> * * Provides the logic to parse a xml file and filter to different ports based on * a matching element. The element and all children will be turned into a * Data record.<br> * Mapping attribute contains mapping hierarchy in XML form. DTD of mapping:<br> * <code> * &lt;!ELEMENT Mappings (Mapping*)&gt;<br> * * &lt;!ELEMENT Mapping (Mapping*)&gt;<br> * &lt;!ATTLIST Mapping<br> * &nbsp;element NMTOKEN #REQUIRED<br> * &nbsp;&nbsp;//name of binded XML element<br> * &nbsp;outPort NMTOKEN #IMPLIED<br> * &nbsp;&nbsp;//name of output port for this mapped XML element<br> * &nbsp;parentKey NMTOKEN #IMPLIED<br> * &nbsp;&nbsp;//field name of parent record, which is copied into field of the current record<br> * &nbsp;&nbsp;//passed in generatedKey atrribute<br> * &nbsp;generatedKey NMTOKEN #IMPLIED<br> * &nbsp;&nbsp;//see parentKey comment<br> * &nbsp;sequenceField NMTOKEN #IMPLIED<br> * &nbsp;&nbsp;//field name, which will be filled by value from sequence<br> * &nbsp;&nbsp;//(can be used to generate new key field for relative records)<br> * &nbsp;sequenceId NMTOKEN #IMPLIED<br> * &nbsp;&nbsp;//we can supply sequence id used to fill a field defined in a sequenceField attribute<br> * &nbsp;&nbsp;//(if this attribute is omited, non-persistent PrimitiveSequence will be used)<br> * &nbsp;xmlFields NMTOKEN #IMPLIED<br> * &nbsp;&nbsp;//comma separeted xml element names, which will be mapped on appropriate record fields<br> * &nbsp;&nbsp;//defined in cloverFields attribute<br> * &nbsp;cloverFields NMTOKEN #IMPLIED<br> * &nbsp;&nbsp;//see xmlFields comment<br> * &gt;<br> * </code> * All nested XML elements will be recognized as record fields and mapped by name * (except elements serviced by other nested Mapping elements), if you prefere other mapping * xml fields and clover fields than 'by name', use xmlFields and cloveFields attributes * to setup custom fields mapping. 'useNestedNodes' component attribute defines * if also child of nested xml elements will be mapped on the current clover record. * Record from nested Mapping element could be connected via key fields with parent record produced * by parent Mapping element (see parentKey and generatedKey attribute notes). * In case that fields are unsuitable for key composing, extractor could fill * one or more fields with values comming from sequence (see sequenceField and sequenceId attribute). * * For example: given an xml file:<br> * <code> * &lt;myXML&gt; <br> * &nbsp;&lt;phrase&gt; <br> * &nbsp;&nbsp;&lt;text&gt;hello&lt;/text&gt; <br> * &nbsp;&nbsp;&lt;localization&gt; <br> * &nbsp;&nbsp;&nbsp;&lt;chinese&gt;how allo yee dew ying&lt;/chinese&gt; <br> * &nbsp;&nbsp;&nbsp;&lt;german&gt;wie gehts&lt;/german&gt; <br> * &nbsp;&nbsp;&lt;/localization&gt; <br> * &nbsp;&lt;/phrase&gt; <br> * &nbsp;&lt;locations&gt; <br> * &nbsp;&nbsp;&lt;location&gt; <br> * &nbsp;&nbsp;&nbsp;&lt;name&gt;Stormwind&lt;/name&gt; <br> * &nbsp;&nbsp;&nbsp;&lt;description&gt;Beautiful European architecture with a scenic canal system.&lt;/description&gt; <br> * &nbsp;&nbsp;&lt;/location&gt; <br> * &nbsp;&nbsp;&lt;location&gt; <br> * &nbsp;&nbsp;&nbsp;&lt;name&gt;Ironforge&lt;/name&gt; <br> * &nbsp;&nbsp;&nbsp;&lt;description&gt;Economic capital of the region with a high population density.&lt;/description&gt; <br> * &nbsp;&nbsp;&lt;/location&gt; <br> * &nbsp;&lt;/locations&gt; <br> * &nbsp;&lt;someUselessElement&gt;...&lt;/someUselessElement&gt; <br> * &nbsp;&lt;someOtherUselessElement/&gt; <br> * &nbsp;&lt;phrase&gt; <br> * &nbsp;&nbsp;&lt;text&gt;bye&lt;/text&gt; <br> * &nbsp;&nbsp;&lt;localization&gt; <br> * &nbsp;&nbsp;&nbsp;&lt;chinese&gt;she yee lai ta&lt;/chinese&gt; <br> * &nbsp;&nbsp;&nbsp;&lt;german&gt;aufweidersehen&lt;/german&gt; <br> * &nbsp;&nbsp;&lt;/localization&gt; <br> * &nbsp;&lt;/phrase&gt; <br> * &lt;/myXML&gt; <br> * </code> Suppose we want to pull out "phrase" as one datarecord, * "localization" as another datarecord, and "location" as the final datarecord * and ignore the useless elements. First we define the metadata for the * records. Then create the following mapping in the graph: <br> * <code> * &lt;node id="myId" type="com.lrn.etl.job.component.XMLExtract"&gt; <br> * &nbsp;&lt;attr name="mapping"&gt;<br> * &nbsp;&nbsp;&lt;Mapping element="phrase" outPort="0" sequenceField="id"&gt;<br> * &nbsp;&nbsp;&nbsp;&lt;Mapping element="localization" outPort="1" parentKey="id" generatedKey="parent_id"/&gt;<br> * &nbsp;&nbsp;&lt;/Mapping&gt; <br> * &nbsp;&nbsp;&lt;Mapping element="location" outPort="2"/&gt;<br> * &nbsp;&lt;/attr&gt;<br> * &lt;/node&gt;<br> * </code> Port 0 will get the DataRecords:<br> * 1) id=1, text=hello<br> * 2) id=2, text=bye<br> * Port 1 will get:<br> * 1) parent_id=1, chinese=how allo yee dew ying, german=wie gehts<br> * 2) parent_id=2, chinese=she yee lai ta, german=aufwiedersehen<br> * Port 2 will get:<br> * 1) name=Stormwind, description=Beautiful European architecture with a scenic * canal system.<br> * 2) name=Ironforge, description=Economic capital of the region with a high * population density.<br> * <hr> * Issue: Enclosing elements having values are not supported.<br> * i.e. <br> * <code> * &lt;x&gt; <br> * &lt;y&gt;z&lt;/y&gt;<br> * xValue<br> * &lt;/x&gt;<br> * </code> there will be no column x with value xValue.<br> * Issue: Namespaces are not considered.<br> * i.e. <br> * <code> * &lt;ns1:x&gt;xValue&lt;/ns1:x&gt;<br> * &lt;ns2:x&gt;xValue2&lt;/ns2:x&gt;<br> * </code> will be considered the same x. * * @author KKou */ public class XMLExtract extends Node { // Logger private static final Log LOG = LogFactory.getLog(XMLExtract.class); // xml attributes public static final String XML_SOURCEURI_ATTRIBUTE = "sourceUri"; private static final String XML_USENESTEDNODES_ATTRIBUTE = "useNestedNodes"; private static final String XML_MAPPING_ATTRIBUTE = "mapping"; private static final String XML_CHARSET_ATTRIBUTE = "charset"; // mapping attributes private static final String XML_MAPPING = "Mapping"; private final static String XML_MAPPING_URL_ATTRIBUTE = "mappingURL"; private static final String XML_ELEMENT = "element"; private static final String XML_OUTPORT = "outPort"; private static final String XML_PARENTKEY = "parentKey"; private static final String XML_GENERATEDKEY = "generatedKey"; private static final String XML_XMLFIELDS = "xmlFields"; private static final String XML_CLOVERFIELDS = "cloverFields"; private static final String XML_SEQUENCEFIELD = "sequenceField"; private static final String XML_SEQUENCEID = "sequenceId"; private static final String XML_SKIP_ROWS_ATTRIBUTE = "skipRows"; private static final String XML_NUMRECORDS_ATTRIBUTE = "numRecords"; private static final String XML_TRIM_ATTRIBUTE = "trim"; private static final String XML_VALIDATE_ATTRIBUTE = "validate"; private static final String XML_XML_FEATURES_ATTRIBUTE = "xmlFeatures"; /** MiSho Experimental Templates */ private static final String XML_TEMPLATE_ID = "templateId"; private static final String XML_TEMPLATE_REF = "templateRef"; private static final String XML_TEMPLATE_DEPTH = "nestedDepth"; private static final String FEATURES_DELIMETER = ";"; private static final String FEATURES_ASSIGN = ":="; // component name public final static String COMPONENT_TYPE = "XML_EXTRACT"; // from which input port to read private final static int INPUT_PORT = 0; public static final String PARENT_MAPPING_REFERENCE_PREFIX = ".."; public static final String PARENT_MAPPING_REFERENCE_SEPARATOR = "/"; public static final String PARENT_MAPPING_REFERENCE_PREFIX_WITHSEPARATOR = PARENT_MAPPING_REFERENCE_PREFIX + PARENT_MAPPING_REFERENCE_SEPARATOR; public static final String ELEMENT_VALUE_REFERENCE = "."; // Map of elementName => output port private Map<String, Mapping> m_elementPortMap = new HashMap<String, Mapping>(); // Where the XML comes from private InputSource m_inputSource; // input file private String inputFile; private ReadableChannelIterator readableChannelIterator; // can I use nested nodes for mapping processing? private boolean useNestedNodes = true; // global skip and numRecords private int skipRows=0; // do not skip rows by default private int numRecords = -1; // autofilling support private AutoFilling autoFilling = new AutoFilling(); private String xmlFeatures; private boolean validate; private String charset = Defaults.DataParser.DEFAULT_CHARSET_DECODER; private boolean trim = true; private String mappingURL; private String mapping; private NodeList mappingNodes; private TreeMap<String, Mapping> declaredTemplates = new TreeMap<String, Mapping>(); /** * SAX Handler that will dispatch the elements to the different ports. */ private class SAXHandler extends SAXContentHandler { // depth of the element, used to determine when we hit the matching // close element private int m_level = 0; // flag set if we saw characters, otherwise don't save the column (used // to set null values) private boolean m_hasCharacters = false; //flag to skip text value immediately after end xml tag, for instance //<root> // <subtag>text</subtag> // another text //</root> //"another text" will be ignored private boolean m_grabCharacters = true; // buffer for node value private StringBuilder m_characters = new StringBuilder(); // the active mapping private Mapping m_activeMapping = null; private Set<String> cloverAttributes; /** * @param cloverAttributes */ public SAXHandler(Set<String> cloverAttributes) { super(); this.cloverAttributes = cloverAttributes; } /** * @see org.xml.sax.ContentHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes) */ public void startElement(String prefix, String namespace, String localName, Attributes attributes) throws SAXException { m_level++; m_grabCharacters = true; // store value of parent of currently starting element (if appropriate) if (m_activeMapping != null && m_hasCharacters && m_level == m_activeMapping.getLevel() + 1) { if (m_activeMapping.descendantRefernces.containsKey(ELEMENT_VALUE_REFERENCE)) { m_activeMapping.descendantRefernces.put(ELEMENT_VALUE_REFERENCE, trim ? m_characters.toString().trim() : m_characters.toString()); } processCharacters(null, true); } // Regardless of starting element type, reset the length of the buffer and flag m_characters.setLength(0); m_hasCharacters = false; Mapping mapping = null; if (m_activeMapping == null) { mapping = m_elementPortMap.get(localName); } else if (useNestedNodes || m_activeMapping.getLevel() == m_level - 1) { mapping = m_activeMapping.getChildMapping(localName); } if (mapping != null) { // We have a match, start converting all child nodes into // the DataRecord structure m_activeMapping = mapping; m_activeMapping.setLevel(m_level); // clear cached values of xml fields referenced by descendants (there may be values from previously read element of this m_activemapping) for (Entry<String, String> e : m_activeMapping.descendantRefernces.entrySet()) { e.setValue(null); } if (mapping.getOutRecord() != null) { //sequence fields initialization String sequenceFieldName = m_activeMapping.getSequenceField(); if(sequenceFieldName != null && m_activeMapping.getOutRecord().hasField(sequenceFieldName)) { Sequence sequence = m_activeMapping.getSequence(); DataField sequenceField = m_activeMapping.getOutRecord().getField(sequenceFieldName); if(sequenceField.getType() == DataFieldMetadata.INTEGER_FIELD) { sequenceField.setValue(sequence.nextValueInt()); } else if(sequenceField.getType() == DataFieldMetadata.LONG_FIELD || sequenceField.getType() == DataFieldMetadata.DECIMAL_FIELD || sequenceField.getType() == DataFieldMetadata.NUMERIC_FIELD) { sequenceField.setValue(sequence.nextValueLong()); } else { sequenceField.fromString(sequence.nextValueString()); } } m_activeMapping.prepareDoMap(); m_activeMapping.incCurrentRecord4Mapping(); // This is the closing element of the matched element that // triggered the processing // That should be the end of this record so send it off to the // next Node if (runIt) { try { DataRecord outRecord = m_activeMapping.getOutRecord(); String[] generatedKey = m_activeMapping.getGeneratedKey(); String[] parentKey = m_activeMapping.getParentKey(); if (parentKey != null) { //if generatedKey is a single array, all parent keys are concatenated into generatedKey field //I know it is ugly code... if(generatedKey.length != parentKey.length && generatedKey.length != 1) { LOG.warn(getId() + ": XML Extract Mapping's generatedKey and parentKey attribute has different number of field."); m_activeMapping.setGeneratedKey(null); m_activeMapping.setParentKey(null); } else { for(int i = 0; i < parentKey.length; i++) { boolean existGeneratedKeyField = (outRecord != null) && (generatedKey.length == 1 ? outRecord.hasField(generatedKey[0]) : outRecord.hasField(generatedKey[i])); boolean existParentKeyField = m_activeMapping.getParent().getOutRecord() != null && m_activeMapping.getParent().getOutRecord().hasField(parentKey[i]); if (!existGeneratedKeyField) { LOG.warn(getId() + ": XML Extract Mapping's generatedKey field was not found. generatedKey: " + (generatedKey.length == 1 ? generatedKey[0] : generatedKey[i]) + " of element " + m_activeMapping.m_element + ", outPort: " + m_activeMapping.m_outPort); m_activeMapping.setGeneratedKey(null); m_activeMapping.setParentKey(null); } else if (!existParentKeyField) { LOG.warn(getId() + ": XML Extract Mapping's parentKey field was not found. parentKey: " + parentKey[i] + " of element " + m_activeMapping.m_element + ", outPort: " + m_activeMapping.m_outPort); m_activeMapping.setGeneratedKey(null); m_activeMapping.setParentKey(null); } else { // both outRecord and m_activeMapping.getParrent().getOutRecord are not null // here, because of if-else if-else chain DataField generatedKeyField = generatedKey.length == 1 ? outRecord.getField(generatedKey[0]) : outRecord.getField(generatedKey[i]); DataField parentKeyField = m_activeMapping.getParent().getOutRecord().getField(parentKey[i]); if(generatedKey.length != parentKey.length) { if(generatedKeyField.getType() != DataFieldMetadata.STRING_FIELD) { LOG.warn(getId() + ": XML Extract Mapping's generatedKey field has to be String type (keys are concatened to this field)."); m_activeMapping.setGeneratedKey(null); m_activeMapping.setParentKey(null); } else { ((StringDataField) generatedKeyField).append(parentKeyField.toString()); } } else { generatedKeyField.setValue(parentKeyField.getValue()); } } } } } } catch (Exception ex) { throw new SAXException(" for output port number '" + m_activeMapping.getOutPort() + "'. Check also parent mapping. ", ex); } // Fill fields from parent record (if any mapped) if (m_activeMapping.hasFieldsFromAncestor()) { for (AncestorFieldMapping afm : m_activeMapping.getFieldsFromAncestor()) { if (m_activeMapping.getOutRecord().hasField(afm.currentField) && afm.ancestor != null) { m_activeMapping.getOutRecord().getField(afm.currentField).fromString(afm.ancestor.descendantRefernces.get(afm.ancestorField)); } } } } else { throw new SAXException("Stop Signaled"); } } } if(m_activeMapping != null //used only if we right now recognize new mapping element or if we want to use nested unmapped nodes as a source of data && (useNestedNodes || mapping != null)) { // In a matched element (i.e. we are creating a DataRecord) // Store all attributes as columns (this hasn't been // used/tested) for (int i = 0; i < attributes.getLength(); i++) { String attrName = attributes.getQName(i); if (m_activeMapping.descendantRefernces.containsKey(attrName)) { String val = attributes.getValue(i); m_activeMapping.descendantRefernces.put(attrName, trim ? val.trim() : val); } //use fields mapping Map<String, String> xmlCloverMap = m_activeMapping.getXml2CloverFieldsMap(); if (xmlCloverMap != null) { if (xmlCloverMap.containsKey(attrName)) { attrName = xmlCloverMap.get(attrName); } else if (m_activeMapping.explicitCloverFields.contains(attrName)) { continue; // don't do implicit mapping if clover field is used in an explicit mapping } } DataRecord outRecord = m_activeMapping.getOutRecord(); DataField field = null; if (outRecord != null) { if (outRecord.hasLabeledField(attrName)) { field = outRecord.getFieldByLabel(attrName); } } if (field != null) { String val = attributes.getValue(i); field.fromString(trim ? val.trim() : val); } } } } /** * @see org.xml.sax.ContentHandler#characters(char[], int, int) */ public void characters(char[] data, int offset, int length) throws SAXException { // Save the characters into the buffer, endElement will store it into the field if (m_activeMapping != null && m_grabCharacters) { m_characters.append(data, offset, length); m_hasCharacters = true; } } /** * @see org.xml.sax.ContentHandler#endElement(java.lang.String, java.lang.String, java.lang.String) */ public void endElement(String prefix, String namespace, String localName) throws SAXException { if (m_activeMapping != null) { // cache characters value if the xml field is referenced by descendant if (m_level - 1 <= m_activeMapping.getLevel() && m_activeMapping.descendantRefernces.containsKey(localName)) { m_activeMapping.descendantRefernces.put(localName, trim ? m_characters.toString().trim() : m_characters.toString()); } processCharacters(localName, m_level == m_activeMapping.getLevel()); // Regardless of whether this was saved, reset the length of the // buffer and flag m_characters.setLength(0); m_hasCharacters = false; } if (m_activeMapping != null && m_level == m_activeMapping.getLevel()) { // This is the closing element of the matched element that // triggered the processing // That should be the end of this record so send it off to the // next Node if (runIt) { try { OutputPort outPort = getOutputPort(m_activeMapping.getOutPort()); if (outPort != null) { // we just ignore creating output, if port is empty (without metadata) or not specified DataRecord outRecord = m_activeMapping.getOutRecord(); // skip or process row if (skipRows > 0) { if (m_activeMapping.getParent() == null) skipRows } else { //check for index of last returned record if(!(numRecords >= 0 && numRecords == autoFilling.getGlobalCounter())) { // set autofilling autoFilling.setAutoFillingFields(outRecord); // can I do the map? it depends on skip and numRecords. if (m_activeMapping.doMap()) { //send off record outPort.writeRecord(outRecord); } // if (m_activeMapping.getParent() == null) autoFilling.incGlobalCounter(); } } // resets all child's mappings for skip and numRecords m_activeMapping.resetCurrentRecord4ChildMapping(); // reset record outRecord.reset(); } m_activeMapping = m_activeMapping.getParent(); } catch (Exception ex) { throw new SAXException(ex); } } else { throw new SAXException("Stop Signaled"); } } //text value immediately after end tag element should not be stored m_grabCharacters = false; //ended an element so decrease our depth m_level } /** * Store the characters processed by the characters() call back only if we have corresponding * output field and we are on the right level or we want to use data from nested unmapped nodes */ private void processCharacters(String localName, boolean elementValue) { //use fields mapping Map<String, String> xml2clover = m_activeMapping.getXml2CloverFieldsMap(); if (xml2clover != null) { if (elementValue && xml2clover.containsKey(ELEMENT_VALUE_REFERENCE)) { localName = xml2clover.get(ELEMENT_VALUE_REFERENCE); } else if (xml2clover.containsKey(localName)) { localName = xml2clover.get(localName); } else if (m_activeMapping.explicitCloverFields.contains(localName)) { return; // don't do implicit mapping if clover field is used in an explicit mapping } } DataRecord outRecord = m_activeMapping.getOutRecord(); DataField field = null; if ((outRecord != null) && (useNestedNodes || m_level - 1 <= m_activeMapping.getLevel())) { if (outRecord.hasLabeledField(localName)) { field = outRecord.getFieldByLabel(localName); } } if (field != null) { // If field is nullable and there's no character data set it to null if (m_hasCharacters) { try { if (field.getValue() != null && cloverAttributes.contains(localName)) { field.fromString(trim ? field.getValue().toString().trim() : field.getValue().toString()); } else { field.fromString(trim ? m_characters.toString().trim() : m_characters.toString()); } } catch (BadDataFormatException ex) { // This is a bit hacky here SOOO let me explain... if (field.getType() == DataFieldMetadata.DATE_FIELD) { // XML dateTime format is not supported by the // DateFormat oject that clover uses... // so timezones are unparsable // i.e. XML wants -5:00 but DateFormat wants // -500 // Attempt to munge and retry... (there has to // be a better way) try { // Chop off the ":" in the timezone (it HAS // to be at the end) String dateTime = m_characters.substring(0, m_characters.lastIndexOf(":")) + m_characters .substring(m_characters .lastIndexOf(":") + 1); DateFormat format = new SimpleDateFormat(field.getMetadata().getFormatStr()); field.setValue(format.parse(trim ? dateTime.trim() : dateTime)); } catch (Exception ex2) { // Oh well we tried, throw the originating // exception throw ex; } } else { throw ex; } } } else if (field.getType() == DataFieldMetadata.STRING_FIELD // and value wasn't already stored (from characters) && (field.getValue() == null || field.getValue().equals(field.getMetadata().getDefaultValueStr()))) { field.setValue(""); } } } } /** * Mapping holds a single mapping. */ public class Mapping { String m_element; // name of an element for this mapping int m_outPort; // output port number DataRecord m_outRecord; // output record String[] m_parentKey; // parent keys String[] m_generatedKey; // generated keys Map<String, Mapping> m_childMap; // direct children for this mapping WeakReference<Mapping> m_parent; // direct parent mapping int m_level; // original xml tree level (a depth of this element) String m_sequenceField; // sequence field String m_sequenceId; // sequence ID Sequence sequence; // sequence (Simple, Db,..) /** Mapping - xml name -> clover field name */ Map<String, String> xml2CloverFieldsMap = new HashMap<String, String>(); /** List of clover fields (among else) which will be filled from ancestor */ List<AncestorFieldMapping> fieldsFromAncestor; /** Mapping - xml name -> clover field name; these xml fields are referenced by descendant mappings */ Map<String, String> descendantRefernces = new HashMap<String, String>(); /** Set of Clover fields which are mapped explicitly (using xmlFields & cloverFields attributes). * It is union of xml2CloverFieldsMap.values() and Clover fields from fieldsFromAncestor list. Its purpose: quick lookup */ Set<String> explicitCloverFields = new HashSet<String>(); // for skip and number a record attribute for this mapping int skipRecords4Mapping; // skip records int numRecords4Mapping = Integer.MAX_VALUE; // number records // int skipSourceRecords4Mapping; // skip records // int numSourceRecords4Mapping = -1; // number records int currentRecord4Mapping; // record counter for this mapping boolean processSkipOrNumRecords; // what xml element can be skiped boolean bDoMap = true; // should I skip an xml element? depends on processSkipOrNumRecords boolean bReset4CurrentRecord4Mapping; // should I reset submappings? /** * Copy constructor - created a deep copy of all attributes and children elements */ public Mapping(Mapping otherMapping, Mapping parent) { this.m_element = otherMapping.m_element; this.m_outPort = otherMapping.m_outPort; this.m_parentKey = otherMapping.m_parentKey == null ? null : Arrays.copyOf(otherMapping.m_parentKey,otherMapping.m_parentKey.length); this.m_generatedKey = otherMapping.m_generatedKey == null ? null : Arrays.copyOf(otherMapping.m_generatedKey, otherMapping.m_generatedKey.length); this.m_sequenceField = otherMapping.m_sequenceField; this.m_sequenceId = otherMapping.m_sequenceId; this.skipRecords4Mapping = otherMapping.skipRecords4Mapping; this.numRecords4Mapping = otherMapping.numRecords4Mapping; xml2CloverFieldsMap = new HashMap<String, String>(otherMapping.xml2CloverFieldsMap); // Create deep copy of children elements if (otherMapping.m_childMap != null) { this.m_childMap = new HashMap<String,Mapping>(); for (String key : otherMapping.m_childMap.keySet()) { final Mapping child = new Mapping(otherMapping.m_childMap.get(key), this); this.m_childMap.put(key, child); } } if (parent != null) { setParent(parent); parent.addChildMapping(this); } if (otherMapping.hasFieldsFromAncestor()) { for (AncestorFieldMapping m : otherMapping.getFieldsFromAncestor()) { addAcestorFieldMapping(m.originalFieldReference, m.currentField); } } } /** * Minimally required information. */ public Mapping(String element, int outPort, Mapping parent) { m_element = element; m_outPort = outPort; m_parent = new WeakReference<Mapping>(parent); if (parent != null) { parent.addChildMapping(this); } } /** * Gives the optional attributes parentKey and generatedKey. */ public Mapping(String element, int outPort, String parentKey[], String[] generatedKey, Mapping parent) { this(element, outPort, parent); m_parentKey = parentKey; m_generatedKey = generatedKey; } /** * Gets original xml tree level (a deep of this element) * @return */ public int getLevel() { return m_level; } /** * Sets original xml tree level (a deep of this element) * @param level */ public void setLevel(int level) { m_level = level; } /** * Sets direct children for this mapping. * @return */ public Map<String, Mapping> getChildMap() { return m_childMap; } /** * Gets direct children for this mapping. * @param element * @return */ public Mapping getChildMapping(String element) { if (m_childMap == null) { return null; } return m_childMap.get(element); } /** * Adds a direct child for this mapping. * @param mapping */ public void addChildMapping(Mapping mapping) { if (m_childMap == null) { m_childMap = new HashMap<String, Mapping>(); } m_childMap.put(mapping.getElement(), mapping); } /** * Removes a direct child for this mapping. * @param mapping */ public void removeChildMapping(Mapping mapping) { if (m_childMap == null) { return; } m_childMap.remove(mapping.getElement()); } /** * Gets an element name for this mapping. * @return */ public String getElement() { return m_element; } /** * Sets an element name for this mapping. * @param element */ public void setElement(String element) { m_element = element; } /** * Gets generated keys of for this mapping. * @return */ public String[] getGeneratedKey() { return m_generatedKey; } /** * Sets generated keys of for this mapping. * @param generatedKey */ public void setGeneratedKey(String[] generatedKey) { m_generatedKey = generatedKey; } /** * Gets an output port. * @return */ public int getOutPort() { return m_outPort; } /** * Sets an output port. * @param outPort */ public void setOutPort(int outPort) { m_outPort = outPort; } /** * Gets mapping - xml name -> clover field name * WARNING: values of this map must be kept in synch with explicitCloverFields; prefer {@link #putXml2CloverFieldMap()} */ public Map<String, String> getXml2CloverFieldsMap() { return xml2CloverFieldsMap; } public void putXml2CloverFieldMap(String xmlField, String cloverField) { xml2CloverFieldsMap.put(xmlField, cloverField); explicitCloverFields.add(cloverField); } /** * Gets an output record. * @return */ public DataRecord getOutRecord() { if (m_outRecord == null) { OutputPort outPort = getOutputPort(getOutPort()); if (outPort != null) { DataRecordMetadata dataRecordMetadata = outPort.getMetadata(); autoFilling.addAutoFillingFields(dataRecordMetadata); m_outRecord = new DataRecord(dataRecordMetadata); m_outRecord.init(); m_outRecord.reset(); } // Original code is commented, it is valid to have null port now /* else { LOG .warn(getId() + ": Port " + getOutPort() + " does not have an edge connected. Please connect the edge or remove the mapping."); }*/ } return m_outRecord; } /** * Sets an output record. * @param outRecord */ public void setOutRecord(DataRecord outRecord) { m_outRecord = outRecord; } /** * Gets parent key. * @return */ public String[] getParentKey() { return m_parentKey; } /** * Sets parent key. * @param parentKey */ public void setParentKey(String[] parentKey) { m_parentKey = parentKey; } /** * Gets a parent mapping. * @return */ public Mapping getParent() { if (m_parent != null) { return m_parent.get(); } else { return null; } } /** * Sets a parent mapping. * @param parent */ public void setParent(Mapping parent) { m_parent = new WeakReference<Mapping>(parent); } /** * Gets a sequence name. * @return */ public String getSequenceField() { return m_sequenceField; } /** * Sets a sequence name. * @param field */ public void setSequenceField(String field) { m_sequenceField = field; } /** * Gets a sequence ID. * @return */ public String getSequenceId() { return m_sequenceId; } /** * Sets a sequence ID. * @param id */ public void setSequenceId(String id) { m_sequenceId = id; } /** * Gets a Sequence (simple sequence, db sequence, ...). * @return */ public Sequence getSequence() { if(sequence == null) { String element = StringUtils.normalizeString(StringUtils.trimXmlNamespace(getElement())); if(getSequenceId() == null) { sequence = new PrimitiveSequence(element, getGraph(), element); } else { sequence = getGraph().getSequence(getSequenceId()); if(sequence == null) { LOG.warn(getId() + ": Sequence " + getSequenceId() + " does not exist in " + "transformation graph. Primitive sequence is used instead."); sequence = new PrimitiveSequence(element, getGraph(), element); } } } return sequence; } /** * processSkipOrNumRecords is true - mapping can be skipped */ public boolean getProcessSkipOrNumRecords() { if (processSkipOrNumRecords) return true; Mapping parent = getParent(); if (parent == null) { return processSkipOrNumRecords; } return parent.getProcessSkipOrNumRecords(); } /** * Sets inner variables for processSkipOrNumRecords. */ public void prepareProcessSkipOrNumRecords() { Mapping parentMapping = getParent(); processSkipOrNumRecords = parentMapping != null && parentMapping.getProcessSkipOrNumRecords() || (skipRecords4Mapping > 0 || numRecords4Mapping < Integer.MAX_VALUE); } /** * Sets inner variables for bReset4CurrentRecord4Mapping. */ public void prepareReset4CurrentRecord4Mapping() { bReset4CurrentRecord4Mapping = processSkipOrNumRecords; if (m_childMap != null) { Mapping mapping; for (Iterator<Entry<String, Mapping>> it=m_childMap.entrySet().iterator(); it.hasNext();) { mapping = it.next().getValue(); if (mapping.processSkipOrNumRecords) { bReset4CurrentRecord4Mapping = true; break; } } } } /** * skipRecords for this mapping. * @param skipRecords4Mapping */ public void setSkipRecords4Mapping(int skipRecords4Mapping) { this.skipRecords4Mapping = skipRecords4Mapping; } /** * numRecords for this mapping. * @param numRecords4Mapping */ public void setNumRecords4Mapping(int numRecords4Mapping) { this.numRecords4Mapping = numRecords4Mapping; } // /** // * skipRecords for this mapping. // * @param skipRecords4Mapping // */ // public void setSkipSourceRecords4Mapping(int skipSourceRecords4Mapping) { // this.skipSourceRecords4Mapping = skipSourceRecords4Mapping; // /** // * numRecords for this mapping. // * @param numRecords4Mapping // */ // public void setNumSourceRecords4Mapping(int numSourceRecords4Mapping) { // this.numSourceRecords4Mapping = numSourceRecords4Mapping; /** * Counter for this mapping. */ public void incCurrentRecord4Mapping() { currentRecord4Mapping++; } /** * Resets submappings. */ public void resetCurrentRecord4ChildMapping() { if (!bReset4CurrentRecord4Mapping) return; if (m_childMap != null) { Mapping mapping; for (Iterator<Entry<String, Mapping>> it=m_childMap.entrySet().iterator(); it.hasNext();) { mapping = it.next().getValue(); mapping.currentRecord4Mapping = 0; mapping.resetCurrentRecord4ChildMapping(); } } } /** * Sets if this and child mapping should be skipped. */ public void prepareDoMap() { if (!processSkipOrNumRecords) return; Mapping parent = getParent(); bDoMap = (parent == null || parent.doMap()) && currentRecord4Mapping >= skipRecords4Mapping && currentRecord4Mapping-skipRecords4Mapping < numRecords4Mapping; if (m_childMap != null) { Mapping mapping; for (Iterator<Entry<String, Mapping>> it=m_childMap.entrySet().iterator(); it.hasNext();) { mapping = it.next().getValue(); mapping.prepareDoMap(); } } } /** * Can process this mapping? It depends on currentRecord4Mapping, skipRecords4Mapping and numRecords4Mapping * for this and parent mappings. * @return */ public boolean doMap() { return !processSkipOrNumRecords || (processSkipOrNumRecords && bDoMap); } public void addAncestorField(AncestorFieldMapping ancestorFieldReference) { if (fieldsFromAncestor == null) { fieldsFromAncestor = new LinkedList<AncestorFieldMapping>(); } fieldsFromAncestor.add(ancestorFieldReference); if (ancestorFieldReference.ancestor != null) { ancestorFieldReference.ancestor.descendantRefernces.put(ancestorFieldReference.ancestorField, null); } explicitCloverFields.add(ancestorFieldReference.currentField); } public List<AncestorFieldMapping> getFieldsFromAncestor() { return fieldsFromAncestor; } public boolean hasFieldsFromAncestor() { return fieldsFromAncestor != null && !fieldsFromAncestor.isEmpty(); } private void addAcestorFieldMapping(String ancestorFieldRef, String currentField) { String ancestorField = ancestorFieldRef; ancestorField = normalizeAncestorValueRef(ancestorField); Mapping ancestor = this; while (ancestorField.startsWith(PARENT_MAPPING_REFERENCE_PREFIX_WITHSEPARATOR)) { ancestor = ancestor.getParent(); if (ancestor == null) { // User may want this in template declaration LOG.debug("Invalid ancestor XML field reference " + ancestorFieldRef + " in mapping of element <" + this.getElement() + ">"); break; } ancestorField = ancestorField.substring(PARENT_MAPPING_REFERENCE_PREFIX_WITHSEPARATOR.length()); } if (ancestor != null) { addAncestorField(new AncestorFieldMapping(ancestor, ancestorField, currentField, ancestorFieldRef)); } else { // This AncestorFieldMapping makes sense in templates - invalid ancestor reference may become valid in template reference addAncestorField(new AncestorFieldMapping(null, null, currentField, ancestorFieldRef)); } } /** * If <code>ancestorField</code> is reference to ancestor element value, returns its normalized * version, otherwise returns unchanged original parameter. * Normalized ancestor field reference always ends with "../.": suffix. * Valid unnormalized ancestor element value references are i.e.: ".." or "../" */ private String normalizeAncestorValueRef(String ancestorField) { if (PARENT_MAPPING_REFERENCE_PREFIX.equals(ancestorField)) { return PARENT_MAPPING_REFERENCE_PREFIX_WITHSEPARATOR + ELEMENT_VALUE_REFERENCE; } if (ancestorField.startsWith(PARENT_MAPPING_REFERENCE_PREFIX_WITHSEPARATOR)) { if (ancestorField.endsWith(PARENT_MAPPING_REFERENCE_PREFIX)) { ancestorField += PARENT_MAPPING_REFERENCE_SEPARATOR + ELEMENT_VALUE_REFERENCE; } else if (ancestorField.endsWith(PARENT_MAPPING_REFERENCE_PREFIX_WITHSEPARATOR)) { ancestorField += ELEMENT_VALUE_REFERENCE; } } return ancestorField; } } public static class AncestorFieldMapping { final Mapping ancestor; final String ancestorField; final String currentField; final String originalFieldReference; public AncestorFieldMapping(Mapping ancestor, String ancestorField, String currentField, String originalFieldReference) { this.ancestor = ancestor; this.ancestorField = ancestorField; this.currentField = currentField; this.originalFieldReference = originalFieldReference; } } /** * Constructs an XML Extract node with the given id. */ public XMLExtract(String id) { super(id); } /** * Creates an inctence of this class from a xml node. * @param graph * @param xmlElement * @return * @throws XMLConfigurationException */ public static Node fromXML(TransformationGraph graph, Element xmlElement) throws XMLConfigurationException { ComponentXMLAttributes xattribs = new ComponentXMLAttributes(xmlElement, graph); XMLExtract extract; try { // constructor extract = new XMLExtract(xattribs.getString(XML_ID_ATTRIBUTE)); // set input file extract.setInputFile(xattribs.getStringEx(XML_SOURCEURI_ATTRIBUTE,RefResFlag.SPEC_CHARACTERS_OFF)); // set dtd schema // if (xattribs.exists(XML_SCHEMA_ATTRIBUTE)) { // extract.setSchemaFile(xattribs.getString(XML_SCHEMA_ATTRIBUTE)); // if can use nested nodes. if(xattribs.exists(XML_USENESTEDNODES_ATTRIBUTE)) { extract.setUseNestedNodes(xattribs.getBoolean(XML_USENESTEDNODES_ATTRIBUTE)); } // set mapping String mappingURL = xattribs.getStringEx(XML_MAPPING_URL_ATTRIBUTE, null,RefResFlag.SPEC_CHARACTERS_OFF); String mapping = xattribs.getString(XML_MAPPING_ATTRIBUTE, null); NodeList nodes = xmlElement.getChildNodes(); if (mappingURL != null) extract.setMappingURL(mappingURL); else if (mapping != null) extract.setMapping(mapping); else if (nodes != null && nodes.getLength() > 0){ //old-fashioned version of mapping definition //mapping xml elements are child nodes of the component extract.setNodes(nodes); } else { xattribs.getStringEx(XML_MAPPING_URL_ATTRIBUTE,RefResFlag.SPEC_CHARACTERS_OFF); // throw configuration exception } // set a skip row attribute if (xattribs.exists(XML_SKIP_ROWS_ATTRIBUTE)){ extract.setSkipRows(xattribs.getInteger(XML_SKIP_ROWS_ATTRIBUTE)); } // set a numRecord attribute if (xattribs.exists(XML_NUMRECORDS_ATTRIBUTE)){ extract.setNumRecords(xattribs.getInteger(XML_NUMRECORDS_ATTRIBUTE)); } if (xattribs.exists(XML_XML_FEATURES_ATTRIBUTE)){ extract.setXmlFeatures(xattribs.getString(XML_XML_FEATURES_ATTRIBUTE)); } if (xattribs.exists(XML_VALIDATE_ATTRIBUTE)){ extract.setValidate(xattribs.getBoolean(XML_VALIDATE_ATTRIBUTE)); } if (xattribs.exists(XML_CHARSET_ATTRIBUTE)){ extract.setCharset(xattribs.getString(XML_CHARSET_ATTRIBUTE)); } if (xattribs.exists(XML_TRIM_ATTRIBUTE)){ extract.setTrim(xattribs.getBoolean(XML_TRIM_ATTRIBUTE)); } return extract; } catch (Exception ex) { throw new XMLConfigurationException(COMPONENT_TYPE + ":" + xattribs.getString(XML_ID_ATTRIBUTE," unknown ID ") + ":" + ex.getMessage(),ex); } } @Deprecated private void setNodes(NodeList nodes) { this.mappingNodes = nodes; } public void setMappingURL(String mappingURL) { this.mappingURL = mappingURL; } public void setMapping(String mapping) { this.mapping = mapping; } /** * Sets the trim indicator. * @param trim */ public void setTrim(boolean trim) { this.trim = trim; } /** * Creates org.w3c.dom.Document object from the given String. * * @param inString * @return * @throws XMLConfigurationException */ private static Document createDocumentFromString(String inString) throws XMLConfigurationException { InputSource is = new InputSource(new StringReader(inString)); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setCoalescing(true); Document doc; try { doc = dbf.newDocumentBuilder().parse(is); } catch (Exception e) { throw new XMLConfigurationException("Mapping parameter parse error occur.", e); } return doc; } /** * Creates org.w3c.dom.Document object from the given ReadableByteChannel. * * @param readableByteChannel * @return * @throws XMLConfigurationException */ public static Document createDocumentFromChannel(ReadableByteChannel readableByteChannel) throws XMLConfigurationException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setCoalescing(true); Document doc; try { doc = dbf.newDocumentBuilder().parse(Channels.newInputStream(readableByteChannel)); } catch (Exception e) { throw new XMLConfigurationException("Mapping parameter parse error occur.", e); } return doc; } /** * Creates mappings. * * @param graph * @param extract * @param parentMapping * @param nodeXML */ private List<String> processMappings(TransformationGraph graph, Mapping parentMapping, org.w3c.dom.Node nodeXML) { List<String> errors = new LinkedList<String>(); if (XML_MAPPING.equals(nodeXML.getNodeName())) { // for a mapping declaration, process all of the attributes // element, outPort, parentKeyName, generatedKey ComponentXMLAttributes attributes = new ComponentXMLAttributes((Element) nodeXML, graph); Mapping mapping = null; if (attributes.exists(XML_TEMPLATE_REF)) { // template mapping reference String templateId = null; try { templateId = attributes.getString(XML_TEMPLATE_REF); } catch (AttributeNotFoundException e) { // this cannot happen (see if above) errors.add("Attribute 'templateId' is missing"); return errors; } if (!declaredTemplates.containsKey(templateId)) { errors.add("Template '" + templateId + "' has not been declared"); return errors; } mapping = new Mapping(declaredTemplates.get(templateId), parentMapping); } // standard mapping declaration try { int outputPort = -1; if (attributes.exists(XML_OUTPORT)) { outputPort = attributes.getInteger(XML_OUTPORT); } if (mapping == null) { mapping = new Mapping(attributes.getString(XML_ELEMENT), outputPort, parentMapping); } else { if (outputPort != -1) { mapping.setOutPort(outputPort); if (attributes.exists(XML_ELEMENT)) { mapping.setElement(attributes.getString(XML_ELEMENT)); } } } } catch(AttributeNotFoundException ex) { errors.add("Required attribute 'element' missing. Skipping this mapping and all children."); return errors; } // Add new root mapping if (parentMapping == null) { addMapping(mapping); } boolean parentKeyPresent = false; boolean generatedKeyPresent = false; if (attributes.exists(XML_PARENTKEY)) { mapping.setParentKey(attributes.getString(XML_PARENTKEY, null).split(Defaults.Component.KEY_FIELDS_DELIMITER_REGEX)); parentKeyPresent = true; } if (attributes.exists(XML_GENERATEDKEY)) { mapping.setGeneratedKey(attributes.getString(XML_GENERATEDKEY, null).split(Defaults.Component.KEY_FIELDS_DELIMITER_REGEX)); generatedKeyPresent = true; } if (parentKeyPresent != generatedKeyPresent) { errors.add("Mapping for element: " + mapping.getElement() + " must either have both 'parentKey' and 'generatedKey' attributes or neither."); mapping.setParentKey(null); mapping.setGeneratedKey(null); } if (parentKeyPresent && mapping.getParent() == null) { errors.add("Mapping for element: " + mapping.getElement() + " may only have 'parentKey' or 'generatedKey' attributes if it is a nested mapping."); mapping.setParentKey(null); mapping.setGeneratedKey(null); } //mapping between xml fields and clover fields initialization if (attributes.exists(XML_XMLFIELDS) && attributes.exists(XML_CLOVERFIELDS)) { String[] xmlFields = attributes.getString(XML_XMLFIELDS, null).split(Defaults.Component.KEY_FIELDS_DELIMITER); String[] cloverFields = attributes.getString(XML_CLOVERFIELDS, null).split(Defaults.Component.KEY_FIELDS_DELIMITER_REGEX); // TODO add existence check for Clover fields, if possible if(xmlFields.length == cloverFields.length){ for (int i = 0; i < xmlFields.length; i++) { if (xmlFields[i].startsWith(PARENT_MAPPING_REFERENCE_PREFIX_WITHSEPARATOR) || xmlFields[i].equals(PARENT_MAPPING_REFERENCE_PREFIX)) { mapping.addAcestorFieldMapping(xmlFields[i], cloverFields[i]); } else { mapping.putXml2CloverFieldMap(xmlFields[i], cloverFields[i]); } } } else { errors.add("Mapping for element: " + mapping.getElement() + " must have same number of the xml fields and the clover fields attribute."); } } //sequence field if (attributes.exists(XML_SEQUENCEFIELD)) { mapping.setSequenceField(attributes.getString(XML_SEQUENCEFIELD, null)); mapping.setSequenceId(attributes.getString(XML_SEQUENCEID, null)); } //skip rows field if (attributes.exists(XML_SKIP_ROWS_ATTRIBUTE)) { mapping.setSkipRecords4Mapping(attributes.getInteger(XML_SKIP_ROWS_ATTRIBUTE, 0)); } //number records field if (attributes.exists(XML_NUMRECORDS_ATTRIBUTE)) { mapping.setNumRecords4Mapping(attributes.getInteger(XML_NUMRECORDS_ATTRIBUTE, Integer.MAX_VALUE)); } // template declaration if (attributes.exists(XML_TEMPLATE_ID)) { final String templateId = attributes.getString(XML_TEMPLATE_ID, null); if (declaredTemplates.containsKey(templateId)) { errors.add("Template '" + templateId + "' has duplicate declaration"); } declaredTemplates.put(templateId, mapping); } // prepare variables for skip and numRecords for this mapping mapping.prepareProcessSkipOrNumRecords(); // multiple nested references of a template if (attributes.exists(XML_TEMPLATE_REF) && attributes.exists(XML_TEMPLATE_DEPTH)) { int depth = attributes.getInteger(XML_TEMPLATE_DEPTH, 1) - 1; Mapping currentMapping = mapping; while (depth > 0) { currentMapping = new Mapping(currentMapping, currentMapping); currentMapping.prepareProcessSkipOrNumRecords(); depth } while (currentMapping != mapping) { currentMapping.prepareReset4CurrentRecord4Mapping(); currentMapping = currentMapping.getParent(); } } // Process all nested mappings NodeList nodes = nodeXML.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { org.w3c.dom.Node node = nodes.item(i); errors.addAll(processMappings(graph, mapping, node)); } // prepare variable reset of skip and numRecords' attributes mapping.prepareReset4CurrentRecord4Mapping(); } else if (nodeXML.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) { errors.add("Unknown element '" + nodeXML.getNodeName() + "' is ignored with all it's child elements."); } // Ignore every other xml element (text values, comments...) return errors; } @Override public void preExecute() throws ComponentNotReadyException { super.preExecute(); if (firstRun()) { // sets input file to readableChannelIterator and sets its settings (directory, charset, input port,...) if (inputFile != null) { createReadableChannelIterator(); this.readableChannelIterator.init(); } } else { autoFilling.reset(); this.readableChannelIterator.reset(); } if (!readableChannelIterator.isGraphDependentSource()) prepareNextSource(); } @Override public Result execute() throws Exception { Result result; // parse xml from input file(s). if (parseXML()) { // finished successfully result = runIt ? Result.FINISHED_OK : Result.ABORTED; } else { // an error occurred result = runIt ? Result.ERROR : Result.ABORTED; } broadcastEOF(); return result; } @Override public void postExecute() throws ComponentNotReadyException { super.postExecute(); //no input channel is closed here - this could be changed in future } /** * Parses the inputSource. The SAXHandler defined in this class will handle * the rest of the events. Returns false if there was an exception * encountered during processing. */ private boolean parseXML() throws JetelException{ // create new sax factory SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setValidating(validate); initXmlFeatures(factory); SAXParser parser; Set<String> xmlAttributes = getXMLMappingValues(); try { // create new sax parser parser = factory.newSAXParser(); } catch (Exception ex) { throw new JetelException(ex.getMessage(), ex); } try { // prepare next source if (readableChannelIterator.isGraphDependentSource()) { try { if(!nextSource()) return true; } catch (JetelException e) { throw new ComponentNotReadyException(e.getMessage()/*"FileURL attribute (" + inputFile + ") doesn't contain valid file url."*/, e); } } do { // parse the input source parser.parse(m_inputSource, new SAXHandler(xmlAttributes)); // get a next source } while (nextSource()); } catch (SAXException ex) { // process error if (!runIt) { return true; // we were stopped by a stop signal... probably } LOG.error("XML Extract: " + getId() + " Parse Exception" + ex.getMessage(), ex); throw new JetelException("XML Extract: " + getId() + " Parse Exception", ex); } catch (Exception ex) { LOG.error("XML Extract: " + getId() + " Unexpected Exception", ex); throw new JetelException("XML Extract: " + getId() + " Unexpected Exception", ex); } return true; } private Set<String> getXMLMappingValues() { try { SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser(); DefaultHandler handler = new MyHandler(); InputStream is = null; if (this.mappingURL != null) { String filePath = FileUtils.getFile(getGraph().getRuntimeContext().getContextURL(), mappingURL); is = new FileInputStream(new File(filePath)); } else if (this.mapping != null) { is = new ByteArrayInputStream(mapping.getBytes(charset)); } if (is != null) { saxParser.parse(is, handler); return ((MyHandler) handler).getCloverAttributes(); } } catch (Exception e) { return new HashSet<String>(); } return new HashSet<String>(); } /** * Xml features initialization. * @throws JetelException */ private void initXmlFeatures(SAXParserFactory factory) throws JetelException { if (xmlFeatures == null) return; String[] aXmlFeatures = xmlFeatures.split(FEATURES_DELIMETER); String[] aOneFeature; try { for (String oneFeature: aXmlFeatures) { aOneFeature = oneFeature.split(FEATURES_ASSIGN); if (aOneFeature.length != 2) throw new JetelException("The xml feature '" + oneFeature + "' has wrong format"); factory.setFeature(aOneFeature[0], Boolean.parseBoolean(aOneFeature[1])); } } catch (Exception e) { throw new JetelException(e.getMessage(), e); } } /** * Perform sanity checks. */ public void init() throws ComponentNotReadyException { if(isInitialized()) return; super.init(); TransformationGraph graph = getGraph(); URL projectURL = graph != null ? graph.getRuntimeContext().getContextURL() : null; // prepare mapping if (mappingURL != null) { try { ReadableByteChannel ch = FileUtils.getReadableChannel(projectURL, mappingURL); Document doc = createDocumentFromChannel(ch); Element rootElement = doc.getDocumentElement(); mappingNodes = rootElement.getChildNodes(); } catch (Exception e) { throw new ComponentNotReadyException(e); } } else if (mapping != null) { Document doc; try { doc = createDocumentFromString(mapping); } catch (XMLConfigurationException e) { throw new ComponentNotReadyException(e); } Element rootElement = doc.getDocumentElement(); mappingNodes = rootElement.getChildNodes(); } //iterate over 'Mapping' elements declaredTemplates.clear(); String errorPrefix = getId() + ": Mapping error - "; for (int i = 0; i < mappingNodes.getLength(); i++) { org.w3c.dom.Node node = mappingNodes.item(i); List<String> errors = processMappings(graph, null, node); for (String error : errors) { LOG.warn(errorPrefix + error); } } // test that we have at least one input port and one output if (outPorts.size() < 1) { throw new ComponentNotReadyException(getId() + ": At least one output port has to be defined!"); } if (m_elementPortMap.size() < 1) { throw new ComponentNotReadyException( getId() + ": At least one mapping has to be defined. <Mapping element=\"elementToMatch\" outPort=\"123\" [parentKey=\"key in parent\" generatedKey=\"new foreign key in target\"]/>"); } } private void createReadableChannelIterator() throws ComponentNotReadyException { TransformationGraph graph = getGraph(); URL projectURL = graph != null ? graph.getRuntimeContext().getContextURL() : null; this.readableChannelIterator = new ReadableChannelIterator( getInputPort(INPUT_PORT), projectURL, inputFile); this.readableChannelIterator.setCharset(charset); this.readableChannelIterator.setPropertyRefResolver(new PropertyRefResolver(graph.getGraphProperties())); this.readableChannelIterator.setDictionary(graph.getDictionary()); } /** * Prepares a next source. * @throws ComponentNotReadyException */ private void prepareNextSource() throws ComponentNotReadyException { try { if(!nextSource()) { throw new ComponentNotReadyException("FileURL attribute (" + inputFile + ") doesn't contain valid file url."); } } catch (JetelException e) { throw new ComponentNotReadyException(e.getMessage()/*"FileURL attribute (" + inputFile + ") doesn't contain valid file url."*/, e); } } /** * Switch to the next source file. * @return * @throws JetelException */ private boolean nextSource() throws JetelException { ReadableByteChannel stream = null; while (readableChannelIterator.hasNext()) { autoFilling.resetSourceCounter(); autoFilling.resetGlobalSourceCounter(); stream = readableChannelIterator.next(); if (stream == null) continue; // if record no record found autoFilling.setFilename(readableChannelIterator.getCurrentFileName()); File tmpFile = new File(autoFilling.getFilename()); long timestamp = tmpFile.lastModified(); autoFilling.setFileSize(tmpFile.length()); autoFilling.setFileTimestamp(timestamp == 0 ? null : new Date(timestamp)); m_inputSource = new InputSource(Channels.newInputStream(stream)); return true; } readableChannelIterator.blankRead(); return false; } public String getType() { return COMPONENT_TYPE; } private void checkUniqueness(ConfigurationStatus status, Mapping mapping) { if (mapping.getOutRecord() == null) { return; } new UniqueLabelsValidator(status, this).validateMetadata(mapping.getOutRecord().getMetadata()); if (mapping.getChildMap() != null) { for (Mapping child: mapping.getChildMap().values()) { checkUniqueness(status, child); } } } @Override public ConfigurationStatus checkConfig(ConfigurationStatus status) { if (charset != null && !Charset.isSupported(charset)) { status.add(new ConfigurationProblem( "Charset "+charset+" not supported!", ConfigurationStatus.Severity.ERROR, this, ConfigurationStatus.Priority.NORMAL)); } TransformationGraph graph = getGraph(); //Check whether XML mapping schema is valid try { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); DefaultHandler handler = new MyHandler(); InputSource is = null; Document doc = null; if (this.mappingURL != null) { String filePath = FileUtils.getFile(graph.getRuntimeContext().getContextURL(), mappingURL); is = new InputSource(new FileInputStream(new File(filePath))); ReadableByteChannel ch = FileUtils.getReadableChannel( graph != null ? graph.getRuntimeContext().getContextURL() : null, mappingURL); doc = createDocumentFromChannel(ch); } else if (this.mapping != null) { // inlined mapping // don't use the charset of the component's input files, but the charset of the .grf file is = new InputSource(new StringReader(mapping)); doc = createDocumentFromString(mapping); } if (is != null) { saxParser.parse(is, handler); Set<String> attributesNames = ((MyHandler) handler).getAttributeNames(); for (String attributeName : attributesNames) { if (!isXMLAttribute(attributeName)) { status.add(new ConfigurationProblem("Can't resolve XML attribute: " + attributeName, Severity.WARNING, this, Priority.NORMAL)); } } } if (doc != null) { Element rootElement = doc.getDocumentElement(); mappingNodes = rootElement.getChildNodes(); for (int i = 0; i < mappingNodes.getLength(); i++) { org.w3c.dom.Node node = mappingNodes.item(i); List<String> errors = processMappings(graph, null, node); ConfigurationProblem problem; for (String error : errors) { problem = new ConfigurationProblem("Mapping error - " + error, Severity.WARNING, this, Priority.NORMAL); status.add(problem); } } } } catch (Exception e) { status.add(new ConfigurationProblem("Can't parse XML mapping schema. Reason: " + e.getMessage(), Severity.ERROR, this, Priority.NORMAL)); } finally { declaredTemplates.clear(); } for (Mapping mapping: getMappings().values()) { checkUniqueness(status, mapping); } try { // check inputs if (inputFile != null) { createReadableChannelIterator(); this.readableChannelIterator.checkConfig(); URL contextURL = graph != null ? graph.getRuntimeContext().getContextURL() : null; String fName = null; Iterator<String> fit = readableChannelIterator.getFileIterator(); while (fit.hasNext()) { try { fName = fit.next(); if (fName.equals("-")) continue; if (fName.startsWith("dict:")) continue; //this test has to be here, since an involuntary warning is caused String mostInnerFile = FileURLParser.getMostInnerAddress(fName); URL url = FileUtils.getFileURL(contextURL, mostInnerFile); if (FileUtils.isServerURL(url)) { //FileUtils.checkServer(url); //this is very long operation continue; } if (FileURLParser.isArchiveURL(fName)) { // test if the archive file exists // getReadableChannel is too long for archives String path = url.getRef() != null ? url.getFile() + "#" + url.getRef() : url.getFile(); if (new File(path).exists()) continue; throw new ComponentNotReadyException("File is unreachable: " + fName); } FileUtils.getReadableChannel(contextURL, fName).close(); } catch (IOException e) { throw new ComponentNotReadyException("File is unreachable: " + fName, e); } catch (ComponentNotReadyException e) { throw new ComponentNotReadyException("File is unreachable: " + fName, e); } } } } catch (ComponentNotReadyException e) { ConfigurationProblem problem = new ConfigurationProblem(e.getMessage(), ConfigurationStatus.Severity.WARNING, this, ConfigurationStatus.Priority.NORMAL); if(!StringUtils.isEmpty(e.getAttributeName())) { problem.setAttributeName(e.getAttributeName()); } status.add(problem); } finally { free(); } //TODO return status; } private static class MyHandler extends DefaultHandler { //Handler used at checkConfig to parse XML mapping and retrieve attributes names private Set<String> attributeNames = new HashSet<String>(); private Set<String> cloverAttributes = new HashSet<String>(); public void startElement(String namespaceURI, String localName, String qName, Attributes atts) { int length = atts.getLength(); for (int i=0; i<length; i++) { String xmlField = atts.getQName(i); attributeNames.add(xmlField); if (xmlField.equals("cloverFields")) { cloverAttributes.add(atts.getValue(i)); } } } public Set<String> getAttributeNames() { return attributeNames; } public Set<String> getCloverAttributes() { return cloverAttributes; } } private boolean isXMLAttribute(String attribute) { //returns true if given attribute is known XML attribute if (attribute.equals(XML_ELEMENT) || attribute.equals(XML_OUTPORT) || attribute.equals(XML_PARENTKEY) || attribute.equals(XML_GENERATEDKEY) || attribute.equals(XML_XMLFIELDS) || attribute.equals(XML_CLOVERFIELDS) || attribute.equals(XML_SEQUENCEFIELD) || attribute.equals(XML_SEQUENCEID) || attribute.equals(XML_SKIP_ROWS_ATTRIBUTE) || attribute.equals(XML_NUMRECORDS_ATTRIBUTE) || attribute.equals(XML_TRIM_ATTRIBUTE) || attribute.equals(XML_VALIDATE_ATTRIBUTE) || attribute.equals(XML_XML_FEATURES_ATTRIBUTE) || attribute.equals(XML_TEMPLATE_ID) || attribute.equals(XML_TEMPLATE_REF) || attribute.equals(XML_TEMPLATE_DEPTH)) { return true; } return false; } public org.w3c.dom.Node toXML() { return null; } /** * Set the input source containing the XML this will parse. */ public void setInputSource(InputSource inputSource) { m_inputSource = inputSource; } /** * Sets an input file. * @param inputFile */ public void setInputFile(String inputFile) { this.inputFile = inputFile; } /** * * @param useNestedNodes */ public void setUseNestedNodes(boolean useNestedNodes) { this.useNestedNodes = useNestedNodes; } /** * Accessor to add a mapping programatically. */ public void addMapping(Mapping mapping) { m_elementPortMap.put(mapping.getElement(), mapping); } /** * Returns the mapping. Maybe make this read-only? */ public Map<String,Mapping> getMappings() { // return Collections.unmodifiableMap(m_elementPortMap); // return a // read-only map return m_elementPortMap; } /** * Sets skipRows - how many elements to skip. * @param skipRows */ public void setSkipRows(int skipRows) { this.skipRows = skipRows; } /** * Sets numRecords - how many elements to process. * @param numRecords */ public void setNumRecords(int numRecords) { this.numRecords = Math.max(numRecords, 0); } /** * Sets the xml feature. * @param xmlFeatures */ public void setXmlFeatures(String xmlFeatures) { this.xmlFeatures = xmlFeatures; } /** * Sets validation option. * @param validate */ public void setValidate(boolean validate) { this.validate = validate; } /** * Sets charset for dictionary and input port reading. * @param string */ public void setCharset(String charset) { this.charset = charset; } // private void resetRecord(DataRecord record) { // // reset the record setting the nullable fields to null and default // // values. Unfortunately init() does not do this, so if you have a field // // that's nullable and you never set a value to it, it will NOT be null. // // the reason we need to reset data records is the fact that XML data is // // not as rigidly // // structured as csv fields, so column values are regularly "missing" // // and without a reset // // the prior row's value will be present. // for (int i = 0; i < record.getNumFields(); i++) { // DataFieldMetadata fieldMetadata = record.getMetadata().getField(i); // DataField field = record.getField(i); // if (fieldMetadata.isNullable()) { // // Default all nullables to null // field.setNull(true); // } else if(fieldMetadata.isDefaultValue()) { // //Default all default values to their given defaults // field.setToDefaultValue(); // } else { // // Not nullable so set it to the default value (what init does) // switch (fieldMetadata.getType()) { // case DataFieldMetadata.INTEGER_FIELD: // ((IntegerDataField) field).setValue(0); // break; // case DataFieldMetadata.STRING_FIELD: // ((StringDataField) field).setValue(""); // break; // case DataFieldMetadata.DATE_FIELD: // case DataFieldMetadata.DATETIME_FIELD: // ((DateDataField) field).setValue(0); // break; // case DataFieldMetadata.NUMERIC_FIELD: // ((NumericDataField) field).setValue(0); // break; // case DataFieldMetadata.LONG_FIELD: // ((LongDataField) field).setValue(0); // break; // case DataFieldMetadata.DECIMAL_FIELD: // ((NumericDataField) field).setValue(0); // break; // case DataFieldMetadata.BYTE_FIELD: // ((ByteDataField) field).setValue((byte) 0); // break; // case DataFieldMetadata.UNKNOWN_FIELD: // default: // break; }
package org.zanata.action; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Set; import javax.faces.event.ValueChangeEvent; import javax.persistence.EntityManager; import javax.persistence.EntityNotFoundException; import org.apache.commons.lang.StringUtils; import org.hibernate.Session; import org.hibernate.criterion.NaturalIdentifier; import org.hibernate.criterion.Restrictions; import org.jboss.seam.annotations.In; import org.jboss.seam.annotations.Name; import org.jboss.seam.annotations.Transactional; import org.jboss.seam.core.Events; import org.jboss.seam.faces.FacesMessages; import org.jboss.seam.security.management.JpaIdentityStore; import org.zanata.common.EntityStatus; import org.zanata.dao.ProjectIterationDAO; import org.zanata.model.HAccount; import org.zanata.model.HAccountRole; import org.zanata.model.HLocale; import org.zanata.model.HProject; import org.zanata.model.HProjectIteration; import org.zanata.security.ZanataIdentity; import org.zanata.service.LocaleService; import org.zanata.service.SlugEntityService; import org.zanata.webtrans.shared.model.ValidationAction; import lombok.Getter; import lombok.Setter; @Name("projectHome") public class ProjectHome extends SlugHome<HProject> { private static final long serialVersionUID = 1L; public static final String PROJECT_UPDATE = "project.update"; @Getter @Setter private String slug; @In ZanataIdentity identity; @In(required = false, value = JpaIdentityStore.AUTHENTICATED_USER) HAccount authenticatedAccount; /* Outjected from LocaleListAction */ @In(required = false) Map<String, String> customizedItems; /* Outjected from LocaleListAction */ @In(required = false) private Boolean overrideLocales; /* Outjected from ProjectRoleRestrictionAction */ @In(required = false) private Set<HAccountRole> customizedProjectRoleRestrictions; /* Outjected from ProjectRoleRestrictionAction */ @In(required = false) private Boolean restrictByRoles; /* Outjected from ValidationOptionsAction */ @In(required = false) private Collection<ValidationAction> customizedValidations; @In private LocaleService localeServiceImpl; @In private SlugEntityService slugEntityServiceImpl; @In private ProjectIterationDAO projectIterationDAO; @In private EntityManager entityManager; @Override protected HProject loadInstance() { Session session = (Session) getEntityManager().getDelegate(); return (HProject) session.byNaturalId(HProject.class) .using("slug", getSlug()).load(); } public void validateSuppliedId() { HProject ip = getInstance(); // this will raise an EntityNotFound // exception // when id is invalid and conversation will not // start if (ip.getStatus().equals(EntityStatus.OBSOLETE) && !checkViewObsolete()) { throw new EntityNotFoundException(); } } public void verifySlugAvailable(ValueChangeEvent e) { String slug = (String) e.getNewValue(); validateSlug(slug, e.getComponent().getId()); } public boolean validateSlug(String slug, String componentId) { if (!isSlugAvailable(slug)) { FacesMessages.instance().addToControl(componentId, "This Project ID is not available"); return false; } return true; } public boolean isSlugAvailable(String slug) { return slugEntityServiceImpl.isSlugAvailable(slug, HProject.class); } @Override @Transactional public String persist() { String retValue = ""; if (!validateSlug(getInstance().getSlug(), "slug")) return null; if (authenticatedAccount != null) { updateOverrideLocales(); updateRoleRestrictions(); updateOverrideValidations(); getInstance().addMaintainer(authenticatedAccount.getPerson()); retValue = super.persist(); Events.instance().raiseEvent("projectAdded"); } return retValue; } public List<HProjectIteration> getVersions() { List<HProjectIteration> results = new ArrayList<HProjectIteration>(); for (HProjectIteration iteration : getInstance().getProjectIterations()) { if (iteration.getStatus() == EntityStatus.OBSOLETE && checkViewObsolete()) { results.add(iteration); } else if (iteration.getStatus() != EntityStatus.OBSOLETE) { results.add(iteration); } } Collections.sort(results, new Comparator<HProjectIteration>() { @Override public int compare(HProjectIteration o1, HProjectIteration o2) { EntityStatus fromStatus = o1.getStatus(); EntityStatus toStatus = o2.getStatus(); if (fromStatus.equals(toStatus)) { return 0; } if (fromStatus.equals(EntityStatus.ACTIVE)) { return -1; } if (fromStatus.equals(EntityStatus.READONLY)) { if (toStatus.equals(EntityStatus.ACTIVE)) { return 1; } return -1; } if (fromStatus.equals(EntityStatus.OBSOLETE)) { return 1; } return 0; } }); return results; } public EntityStatus getEffectiveVersionStatus(HProjectIteration version) { /** * Null pointer exception checking caused by unknown issues where * getEffectiveIterationStatus gets invoke before getIterations */ if (version == null) { return null; } if (getInstance().getStatus() == EntityStatus.READONLY) { if (version.getStatus() == EntityStatus.ACTIVE) { return EntityStatus.READONLY; } } else if (getInstance().getStatus() == EntityStatus.OBSOLETE) { if (version.getStatus() == EntityStatus.ACTIVE || version.getStatus() == EntityStatus.READONLY) { return EntityStatus.OBSOLETE; } } return version.getStatus(); } public String cancel() { return "cancel"; } @Override public boolean isIdDefined() { return slug != null; } @Override public NaturalIdentifier getNaturalId() { return Restrictions.naturalId().set("slug", slug); } @Override public Object getId() { return slug; } @Override public String update() { updateOverrideLocales(); updateRoleRestrictions(); updateOverrideValidations(); String state = super.update(); Events.instance().raiseEvent(PROJECT_UPDATE, getInstance()); if (getInstance().getStatus() == EntityStatus.READONLY) { for (HProjectIteration version : getInstance() .getProjectIterations()) { if (version.getStatus() == EntityStatus.ACTIVE) { version.setStatus(EntityStatus.READONLY); entityManager.merge(version); Events.instance().raiseEvent( ProjectIterationHome.PROJECT_ITERATION_UPDATE, version); } } } else if (getInstance().getStatus() == EntityStatus.OBSOLETE) { for (HProjectIteration version : getInstance() .getProjectIterations()) { if (version.getStatus() != EntityStatus.OBSOLETE) { version.setStatus(EntityStatus.OBSOLETE); entityManager.merge(version); Events.instance().raiseEvent( ProjectIterationHome.PROJECT_ITERATION_UPDATE, version); } } } return state; } private void updateOverrideLocales() { if (overrideLocales != null) { getInstance().setOverrideLocales(overrideLocales); if (!overrideLocales) { getInstance().getCustomizedLocales().clear(); } else if (customizedItems != null) { Set<HLocale> locale = localeServiceImpl .convertCustomizedLocale(customizedItems); getInstance().getCustomizedLocales().clear(); getInstance().getCustomizedLocales().addAll(locale); } } } private void updateOverrideValidations() { // edit project page code won't have customized validations outjected if (customizedValidations != null) { getInstance().getCustomizedValidations().clear(); for (ValidationAction action : customizedValidations) { getInstance().getCustomizedValidations().put( action.getId().name(), action.getState().name()); } } } private void updateRoleRestrictions() { if (restrictByRoles != null) { getInstance().setRestrictedByRoles(restrictByRoles); getInstance().getAllowedRoles().clear(); if (restrictByRoles) { getInstance().getAllowedRoles().addAll( customizedProjectRoleRestrictions); } } } public boolean isProjectActive() { return getInstance().getStatus() == EntityStatus.ACTIVE; } public boolean checkViewObsolete() { return identity != null && identity.hasPermission("HProject", "view-obsolete"); } public boolean isUserAllowedToTranslateOrReview(String versionSlug, HLocale localeId) { return !StringUtils.isEmpty(versionSlug) && localeId != null && isIterationActive(versionSlug) && identity != null && (identity.hasPermission("add-translation", getInstance(), localeId) || identity.hasPermission( "translation-review", getInstance(), localeId)); } private boolean isIterationActive(String versionSlug) { HProjectIteration version = projectIterationDAO.getBySlug(getSlug(), versionSlug); return getInstance().getStatus() == EntityStatus.ACTIVE || version.getStatus() == EntityStatus.ACTIVE; } }
package com.yahoo.vespa.curator; import com.google.inject.Inject; import com.yahoo.cloud.config.ConfigserverConfig; import com.yahoo.io.IOUtils; import com.yahoo.net.HostName; import com.yahoo.path.Path; import com.yahoo.text.Utf8; import com.yahoo.vespa.curator.recipes.CuratorCounter; import com.yahoo.vespa.defaults.Defaults; import com.yahoo.vespa.zookeeper.VespaZooKeeperServer; import org.apache.curator.RetryPolicy; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.api.transaction.CuratorTransaction; import org.apache.curator.framework.api.transaction.CuratorTransactionFinal; import org.apache.curator.framework.recipes.atomic.DistributedAtomicLong; import org.apache.curator.framework.recipes.cache.ChildData; import org.apache.curator.framework.recipes.cache.NodeCacheListener; import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener; import org.apache.curator.framework.recipes.locks.InterProcessLock; import org.apache.curator.framework.recipes.locks.InterProcessMutex; import org.apache.curator.retry.ExponentialBackoffRetry; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.client.ZKClientConfig; import org.apache.zookeeper.data.Stat; import org.apache.zookeeper.server.quorum.QuorumPeerConfig; import java.io.File; import java.time.Duration; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.concurrent.ExecutorService; import java.util.function.Function; import java.util.logging.Logger; /** * Curator interface for Vespa. * This contains method for constructing common recipes and utilities as well as * a small wrapper API for common operations which uses typed paths and avoids throwing checked exceptions. * <p> * There is a mock implementation in MockCurator. * * @author vegardh * @author bratseth */ public class Curator implements AutoCloseable { private static final Logger logger = Logger.getLogger(Curator.class.getName()); private static final int ZK_SESSION_TIMEOUT = 30000; private static final int ZK_CONNECTION_TIMEOUT = 30000; private static final int BASE_SLEEP_TIME = 1000; private static final int MAX_RETRIES = 10; private static final File zkClientConfigFile = new File(Defaults.getDefaults().underVespaHome("conf/zookeeper/zookeeper-client.cfg")); protected final RetryPolicy retryPolicy; private final CuratorFramework curatorFramework; private final String connectionSpec; // May be a subset of the servers in the ensemble private final String zooKeeperEnsembleConnectionSpec; private final int zooKeeperEnsembleCount; /** Creates a curator instance from a comma-separated string of ZooKeeper host:port strings */ public static Curator create(String connectionSpec) { return new Curator(connectionSpec, connectionSpec, Optional.of(zkClientConfigFile)); } // For testing only, use Optional.empty for clientConfigFile parameter to create default zookeeper client config public static Curator create(String connectionSpec, Optional<File> clientConfigFile) { return new Curator(connectionSpec, connectionSpec, clientConfigFile); } // Depend on ZooKeeperServer to make sure it is started first // TODO: Move zookeeperserver config out of configserverconfig (requires update of controller services.xml as well) @Inject public Curator(ConfigserverConfig configserverConfig, VespaZooKeeperServer server) { this(configserverConfig, Optional.of(zkClientConfigFile)); } Curator(ConfigserverConfig configserverConfig, Optional<File> clientConfigFile) { this(createConnectionSpec(configserverConfig), createEnsembleConnectionSpec(configserverConfig), clientConfigFile); } private Curator(String connectionSpec, String zooKeeperEnsembleConnectionSpec, Optional<File> clientConfigFile) { this(connectionSpec, zooKeeperEnsembleConnectionSpec, (retryPolicy) -> CuratorFrameworkFactory .builder() .retryPolicy(retryPolicy) .sessionTimeoutMs(ZK_SESSION_TIMEOUT) .connectionTimeoutMs(ZK_CONNECTION_TIMEOUT) .connectString(connectionSpec) .zookeeperFactory(new VespaZooKeeperFactory(createClientConfig(clientConfigFile))) .dontUseContainerParents() // TODO: Remove when we know ZooKeeper 3.5 works fine, consider waiting until Vespa 8 .build()); } protected Curator(String connectionSpec, String zooKeeperEnsembleConnectionSpec, Function<RetryPolicy, CuratorFramework> curatorFactory) { this(connectionSpec, zooKeeperEnsembleConnectionSpec, curatorFactory, new ExponentialBackoffRetry(BASE_SLEEP_TIME, MAX_RETRIES)); } private Curator(String connectionSpec, String zooKeeperEnsembleConnectionSpec, Function<RetryPolicy, CuratorFramework> curatorFactory, RetryPolicy retryPolicy) { this.connectionSpec = connectionSpec; this.retryPolicy = retryPolicy; this.curatorFramework = curatorFactory.apply(retryPolicy); if (this.curatorFramework != null) { validateConnectionSpec(connectionSpec); validateConnectionSpec(zooKeeperEnsembleConnectionSpec); addLoggingListener(); curatorFramework.start(); } this.zooKeeperEnsembleConnectionSpec = zooKeeperEnsembleConnectionSpec; this.zooKeeperEnsembleCount = zooKeeperEnsembleConnectionSpec.split(",").length; } private static String createConnectionSpec(ConfigserverConfig configserverConfig) { return configserverConfig.zookeeperLocalhostAffinity() ? createConnectionSpecForLocalhost(configserverConfig) : createEnsembleConnectionSpec(configserverConfig); } private static ZKClientConfig createClientConfig(Optional<File> clientConfigFile) { if (clientConfigFile.isPresent()) { boolean useSecureClient = Boolean.parseBoolean(getEnvironmentVariable("VESPA_USE_TLS_FOR_ZOOKEEPER_CLIENT").orElse("false")); String config = "zookeeper.client.secure=" + useSecureClient + "\n"; clientConfigFile.get().getParentFile().mkdirs(); IOUtils.writeFile(clientConfigFile.get(), Utf8.toBytes(config)); try { return new ZKClientConfig(clientConfigFile.get()); } catch (QuorumPeerConfig.ConfigException e) { throw new RuntimeException("Unable to create ZooKeeper client config file " + clientConfigFile.get()); } } else { return new ZKClientConfig(); } } private static String createEnsembleConnectionSpec(ConfigserverConfig config) { StringBuilder connectionSpec = new StringBuilder(); for (int i = 0; i < config.zookeeperserver().size(); i++) { if (connectionSpec.length() > 0) { connectionSpec.append(','); } ConfigserverConfig.Zookeeperserver server = config.zookeeperserver(i); connectionSpec.append(server.hostname()); connectionSpec.append(':'); connectionSpec.append(server.port()); } return connectionSpec.toString(); } static String createConnectionSpecForLocalhost(ConfigserverConfig config) { String thisServer = HostName.getLocalhost(); for (int i = 0; i < config.zookeeperserver().size(); i++) { ConfigserverConfig.Zookeeperserver server = config.zookeeperserver(i); if (thisServer.equals(server.hostname())) { return String.format("%s:%d", server.hostname(), server.port()); } } throw new IllegalArgumentException("Unable to create connect string to localhost: " + "There is no localhost server specified in config: " + config); } private static void validateConnectionSpec(String connectionSpec) { if (connectionSpec == null || connectionSpec.isEmpty()) throw new IllegalArgumentException(String.format("Connections spec '%s' is not valid", connectionSpec)); } /** * Returns the ZooKeeper "connect string" used by curator: a comma-separated list of * host:port of ZooKeeper endpoints to connect to. This may be a subset of * zooKeeperEnsembleConnectionSpec() if there's some affinity, e.g. for * performance reasons. * * This may be empty but never null */ public String connectionSpec() { return connectionSpec; } /** For internal use; prefer creating a {@link CuratorCounter} */ public DistributedAtomicLong createAtomicCounter(String path) { return new DistributedAtomicLong(curatorFramework, path, new ExponentialBackoffRetry(BASE_SLEEP_TIME, MAX_RETRIES)); } /** For internal use; prefer creating a {@link com.yahoo.vespa.curator.Lock} */ public InterProcessLock createMutex(String lockPath) { return new InterProcessMutex(curatorFramework, lockPath); } private void addLoggingListener() { curatorFramework.getConnectionStateListenable().addListener((curatorFramework, connectionState) -> { switch (connectionState) { case SUSPENDED: logger.info("ZK connection state change: SUSPENDED"); break; case RECONNECTED: logger.info("ZK connection state change: RECONNECTED"); break; case LOST: logger.warning("ZK connection state change: LOST"); break; } }); } public CompletionWaiter getCompletionWaiter(Path waiterPath, int numMembers, String id) { return CuratorCompletionWaiter.create(curatorFramework, waiterPath, numMembers, id); } public CompletionWaiter createCompletionWaiter(Path parentPath, String waiterNode, int numMembers, String id) { return CuratorCompletionWaiter.createAndInitialize(this, parentPath, waiterNode, numMembers, id); } /** Creates a listenable cache which keeps in sync with changes to all the immediate children of a path */ public DirectoryCache createDirectoryCache(String path, boolean cacheData, boolean dataIsCompressed, ExecutorService executorService) { return new PathChildrenCacheWrapper(framework(), path, cacheData, dataIsCompressed, executorService); } /** Creates a listenable cache which keeps in sync with changes to a given node */ public FileCache createFileCache(String path, boolean dataIsCompressed) { return new NodeCacheWrapper(framework(), path, dataIsCompressed); } /** A convenience method which returns whether the given path exists */ public boolean exists(Path path) { try { return framework().checkExists().forPath(path.getAbsolute()) != null; } catch (Exception e) { throw new RuntimeException("Could not check existence of " + path.getAbsolute(), e); } } /** * A convenience method which sets some content at a path. * If the path and any of its parents does not exists they are created. */ public void set(Path path, byte[] data) { String absolutePath = path.getAbsolute(); try { if ( ! exists(path)) framework().create().creatingParentsIfNeeded().forPath(absolutePath, data); else framework().setData().forPath(absolutePath, data); } catch (Exception e) { throw new RuntimeException("Could not set data at " + absolutePath, e); } } /** * Creates an empty node at a path, creating any parents as necessary. * If the node already exists nothing is done. * Returns whether a change was attempted. */ public boolean create(Path path) { if (exists(path)) return false; String absolutePath = path.getAbsolute(); try { framework().create().creatingParentsIfNeeded().forPath(absolutePath, new byte[0]); } catch (org.apache.zookeeper.KeeperException.NodeExistsException e) { // Path created between exists() and create() call, do nothing } catch (Exception e) { throw new RuntimeException("Could not create " + absolutePath, e); } return true; } /** * Creates all the given paths in a single transaction. Any paths which already exists are ignored. */ public void createAtomically(Path... paths) { try { CuratorTransaction transaction = framework().inTransaction(); for (Path path : paths) { if ( ! exists(path)) { transaction = transaction.create().forPath(path.getAbsolute(), new byte[0]).and(); } } ((CuratorTransactionFinal)transaction).commit(); } catch (Exception e) { throw new RuntimeException("Could not create " + Arrays.toString(paths), e); } } /** * Deletes the given path and any children it may have. * If the path does not exists nothing is done. */ public void delete(Path path) { try { framework().delete().guaranteed().deletingChildrenIfNeeded().forPath(path.getAbsolute()); } catch (KeeperException.NoNodeException e) { // Do nothing } catch (Exception e) { throw new RuntimeException("Could not delete " + path.getAbsolute(), e); } } /** * Returns the names of the children at the given path. * If the path does not exist or have no children an empty list (never null) is returned. */ public List<String> getChildren(Path path) { try { return framework().getChildren().forPath(path.getAbsolute()); } catch (KeeperException.NoNodeException e) { return List.of(); } catch (Exception e) { throw new RuntimeException("Could not get children of " + path.getAbsolute(), e); } } /** * Returns the data at the given path, which may be a zero-length buffer if the node exists but have no data. * Empty is returned if the path does not exist. */ public Optional<byte[]> getData(Path path) { try { return Optional.of(framework().getData().forPath(path.getAbsolute())); } catch (KeeperException.NoNodeException e) { return Optional.empty(); } catch (Exception e) { throw new RuntimeException("Could not get data at " + path.getAbsolute(), e); } } /** * Returns the stat data at the given path. * Empty is returned if the path does not exist. */ public Optional<Stat> getStat(Path path) { try { return Optional.ofNullable(framework().checkExists().forPath(path.getAbsolute())); } catch (KeeperException.NoNodeException e) { return Optional.empty(); } catch (Exception e) { throw new RuntimeException("Could not get data at " + path.getAbsolute(), e); } } /** Returns the curator framework API */ public CuratorFramework framework() { return curatorFramework; } @Override public void close() { curatorFramework.close(); } /** * Interface for waiting for completion of an operation */ public interface CompletionWaiter { /** * Awaits completion of something. Blocks until an implementation defined * condition has been met. * * @param timeout timeout for blocking await call. * @throws CompletionTimeoutException if timeout is reached without completion. */ void awaitCompletion(Duration timeout); /** * Notify completion of something. This method does not block and is called by clients * that want to notify the completion waiter that something has completed. */ void notifyCompletion(); } /** * A listenable cache of all the immediate children of a curator path. * This wraps the Curator PathChildrenCache recipe to allow us to mock it. */ public interface DirectoryCache { void start(); void addListener(PathChildrenCacheListener listener); List<ChildData> getCurrentData(); /** Returns the ChildData, or null if it does not exist. */ ChildData getCurrentData(Path absolutePath); void close(); } /** * A listenable cache of the content of a single curator path. * This wraps the Curator NodeCache recipe to allow us to mock it. */ public interface FileCache { void start(); void addListener(NodeCacheListener listener); ChildData getCurrentData(); void close(); } /** * @return The non-null connect string containing all ZooKeeper servers in the ensemble. * WARNING: This may be different from the servers this Curator may connect to. * TODO: Move method out of this class. */ public String zooKeeperEnsembleConnectionSpec() { return zooKeeperEnsembleConnectionSpec; } /** * Returns the number of zooKeeper servers in this ensemble. * WARNING: This may be different from the number of servers this Curator may connect to. * TODO: Move method out of this class. */ public int zooKeeperEnsembleCount() { return zooKeeperEnsembleCount; } private static Optional<String> getEnvironmentVariable(String variableName) { return Optional.ofNullable(System.getenv().get(variableName)) .filter(var -> !var.isEmpty()); } }
package org.vosao.service.vo; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.vosao.entity.CommentEntity; import org.vosao.utils.DateUtil; /** * Value object to be returned from services. * @author Alexander Oleynik */ public class CommentVO { private CommentEntity comment; public CommentVO(final CommentEntity entity) { comment = entity; } public static List<CommentVO> create(List<CommentEntity> list) { List<CommentVO> result = new ArrayList<CommentVO>(); for (CommentEntity comment : list) { result.add(new CommentVO(comment)); } return result; } public Long getId() { return comment.getId(); } public String getPageUrl() { return comment.getPageUrl(); } public String getName() { return comment.getName(); } public String getContent() { return comment.getContent(); } public String getPublishDate() { return DateUtil.toString(comment.getPublishDate()); } public String getPublishDateTime() { return DateUtil.dateTimeToString(comment.getPublishDate()); } public Date getDate() { return comment.getPublishDate(); } public boolean isDisabled() { return comment.isDisabled(); } }
package backupbuddies.gui; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.event.ChangeListener; import javax.swing.event.ChangeEvent; import java.io.File; import java.util.List; import java.util.ArrayList; import java.util.Arrays; import java.util.Map; import java.util.Set; import java.util.HashMap; import java.lang.*; import backupbuddies.gui.ListModel; import backupbuddies.shared.IInterface; import static backupbuddies.Debug.*; @SuppressWarnings("serial") public class GuiMain extends JFrame { //colors //static final Color colorBlue = new Color(53, 129, 184); static final Color colorBlue = new Color(80, 80, 80); static final Color textColor = new Color(220, 220, 220); static final Color buttonTextColor = new Color(40, 40, 40); static final Color listColor = new Color(255, 255, 255); static final Color backgroundColor = new Color(92, 146, 194); static final Color colorGray = new Color(20, 20, 20); static final Font font = new Font("Papyrus", Font.BOLD, 18); //load assets, lists etc before creating the gui static JFrame frame = new JFrame("BackupBuddies"); static JTextField saveDir = new JTextField(); static final DefaultListModel<String> userModel = new DefaultListModel<String>(); static final DefaultListModel<String> fileModel = new DefaultListModel<String>(); static final DefaultListModel<ListModel> files = new DefaultListModel<ListModel>(); static DefaultListModel<ListModel> filetest = new DefaultListModel<ListModel>(); static DefaultListModel<ListModel> usertest = new DefaultListModel<ListModel>(); static JList<ListModel> allFiles = new JList<ListModel>(); static JList<ListModel> allUsers = new JList<ListModel>(); //holds the all indices selected by the user static DefaultListModel<String> lastFileState = new DefaultListModel<String>(); static DefaultListModel<String> lastUserState = new DefaultListModel<String>(); static DefaultListModel<ListModel> debug = new DefaultListModel<ListModel>(); static final JTextArea log = new JTextArea(6, 20); static List<String> prevEvents = new ArrayList<>(); static ImageIcon statusRed = new ImageIcon("bin/backupbuddies/gui/assets/RedderCircle.png"); static ImageIcon statusYellow = new ImageIcon("bin/backupbuddies/backupbuddies/gui/assets/YellowerCircle.png"); static ImageIcon statusGreen = new ImageIcon("bin/backupbuddies/backupbuddies/gui/assets/GreenerCircle.png"); static JList<ListModel> userMap = fetchAndProcess("users"); static JList<ListModel> fileMap = fetchAndProcess("files"); static boolean firstSearch = false; static String globalSearch = ""; //populate the window static Container contentPane = frame.getContentPane(); static JPanel loginPanel = loginPanel(); static JPanel controlPanel = controlPanel(); static JScrollPane userListPanel = userListPanel(); static JScrollPane fileListPanel = fileListPanel(""); static JPanel selectUsersPanel = selectUsersPanel(); static JPanel selectFilesPanel = selectFilesPanel(); static JPanel searchPanel = searchPanel(); static JPanel varsPanel = varsPanel(); static JPanel storagePanel = storagePanel(); static JPanel logPanel = logPanel(); static JPanel namePanel = namePanel(); static Map<Component, List<Integer>> panelLocs = new HashMap<Component, List<Integer>>(); //process lists returned from networking //NOTE: to speed this up we can just do it in the interface methods //iteration already occurs there public static JList<ListModel> fetchAndProcess(String type) { //get data JList<ListModel> map = new JList<ListModel>(); //debug = new DefaultListModel<>(); if (type.equals("users")) debug = IInterface.INSTANCE.fetchUserList(); else if (type.equals("files")) debug = IInterface.INSTANCE.fetchFileList(); return map; } //updates ui on interval public static void startIntervals(int interval) { ActionListener updateUI = new ActionListener() { public void actionPerformed(ActionEvent e) { IInterface.INSTANCE.saveNetwork(); userMap = fetchAndProcess("users"); fileMap = fetchAndProcess("files"); updateFileSelection(); updateUserSelection(); fileSearch(globalSearch); if(firstSearch == false){ fileSearch(""); firstSearch = true; } int[] selected = new int[lastFileState.getSize()]; for(int i=0; i<lastFileState.getSize(); i++){ selected[i] = Integer.parseInt(lastFileState.getElementAt(i)); } allFiles.setSelectedIndices(selected); // fileSearch(globalSearch); //FIXME: this gets slower as more events are added //prevArray --> int (length of last returned array) //change to check length of returned array //append the last (len(events) - prevLength) elements to log //if this is negative they cleared the event log //only reset prevArraysize variable List<String> events = IInterface.INSTANCE.getEventLog(); log.setText(""); for (String event : events) { log.append(event + "\n"); log.setCaretPosition(log.getDocument().getLength()); } prevEvents = events; } }; Timer timer = new Timer(interval, updateUI); timer.setRepeats(true); timer.start(); } //user chooses directory to save to public static void setSaveDir() { JFileChooser browser = new JFileChooser(); browser.setDialogTitle("choose save location"); browser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); browser.setAcceptAllFileFilterUsed(false); if (browser.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) { saveDir.setText(browser.getSelectedFile().toString()); IInterface.INSTANCE.setStoragePath(saveDir.getText()); } } //user selects a file and it uploads to network public static void chooseAndUpload() { JFileChooser browser = new JFileChooser(); browser.setMultiSelectionEnabled(true); browser.setDialogTitle("choose files to upload"); if (browser.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) { //File[] files = browser.getSelectedFiles(); //for (File f : files) { // System.out.printf("%s\n", f.toPath()); int[] selected = allUsers.getSelectedIndices(); for( int i=0; i<selected.length; i++){ IInterface.INSTANCE.uploadFile(browser.getSelectedFiles(), allUsers.getModel().getElementAt(selected[i]).getName()); } } //fileSearch(""); } //user downloads a file to save directory (and chooses if not set) public static void setDirAndDownload() { //FIXME: need to have a list of uploaded files to choose from //String fileToGet = "test.txt"; if (saveDir.getText().equals("")) { setSaveDir(); } int[] selected = allFiles.getSelectedIndices(); for(int i=0; i<selected.length; i++){ //System.out.printf("Index: %d %s\n", i, hi.getModel().getElementAt(selected[i]).getName()); IInterface.INSTANCE.downloadFile(allFiles.getModel().getElementAt(selected[i]).getName(), saveDir.getText()); } } //upload, download, save control buttons public static JPanel controlPanel() { //create panel JFrame failedUpload = new JFrame(); JPanel controlPanel = new JPanel(); GridLayout layout = new GridLayout(2, 1, 0, 10); controlPanel.setLayout(layout); //create components JLabel fileLabel = new JLabel("backup your files"); JButton uploadButton = new JButton("upload"); JButton downloadButton = new JButton("download"); JButton pathButton = new JButton("save to..."); downloadButton.setForeground(buttonTextColor); uploadButton.setForeground(buttonTextColor); //set button colors //uploadButton.setForeground(colorGreen); //text color //uploadButton.setBackground(backgroundColor); //uploadButton.setContentAreaFilled(false); //uploadButton.setOpaque(true); //bind methods to buttons uploadButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (allUsers.getSelectedIndex() == -1){ String upError = "Please select at least one user\n"; System.out.printf(upError); JOptionPane.showMessageDialog(failedUpload, upError); }else{ chooseAndUpload(); } } }); pathButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { setSaveDir(); } }); downloadButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { setDirAndDownload(); } }); //add components to panel and specify orientation controlPanel.setPreferredSize(new Dimension(250, 150)); //controlPanel.add(fileLabel); controlPanel.add(uploadButton); controlPanel.add(downloadButton); //controlPanel.add(pathButton); //controlPanel.setComponentOrientation( // ComponentOrientation.LEFT_TO_RIGHT); return controlPanel; } //allows user to input ip and pass and connect to network public static JPanel loginPanel() { //create panel final JPanel loginPanel = new JPanel(); BoxLayout layout = new BoxLayout(loginPanel, BoxLayout.Y_AXIS); loginPanel.setLayout(layout); //create components final JLabel loginLabel = new JLabel("Join a Network:"); final JButton loginButton = new JButton("Join"); final JTextField ipField = new JTextField("network ip...", 21); final JTextField passField = new JTextField("network password..."); ipField.setEnabled(false); passField.setEnabled(false); ipField.setBackground(listColor); passField.setBackground(listColor); loginButton.setForeground(buttonTextColor); //bind methods to buttons loginButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { IInterface.INSTANCE.login(ipField.getText(), passField.getText()); } }); ipField.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { ipField.setText(""); ipField.setEnabled(true); ipField.requestFocus(); } }); passField.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { passField.setText(""); passField.setEnabled(true); passField.requestFocus(); } }); // loginButton.setBorder(new RoundedBorder(10)); //add components to panel and specify orientation // loginButton.setOpaque(false); // loginButton.setBorderPainted(false); // loginButton.setFocusPainted(false); //loginButton.setForeground(Color.BLUE); //loginButton.setBorder(BorderFactory.createEmptyBorder(1,1,1,1)); loginLabel.setForeground(textColor); loginLabel.setFont(font); loginPanel.add(loginLabel); loginPanel.add(ipField); loginPanel.add(passField); loginPanel.add(loginButton); return loginPanel; } //list of peers in the network //TODO: multiple selection //TODO: renders images public static JScrollPane userListPanel() { usertest = (IInterface.INSTANCE.fetchUserList()); allUsers.setModel(usertest); allUsers.addMouseListener(new MouseAdapter(){ @Override public void mouseClicked(MouseEvent e){ int selectedItem = allUsers.getSelectedIndex(); lastUserState.addElement(Integer.toString(selectedItem)); } }); allUsers.setCellRenderer(new ListRenderer()); JScrollPane pane = new JScrollPane(allUsers); pane.setPreferredSize(new Dimension(250, 440)); //allUsers.setSelectionBackground(Color.green); allUsers.setBackground(listColor); return pane; } //list of files you can recover //TODO: multiple selection //TODO: renders images public static JScrollPane fileListPanel(String search) { filetest = (IInterface.INSTANCE.fetchFileList()); //allFiles.setModel(filetest); allFiles.setModel(files); for(int i=0; i< files.size(); i++){ System.out.printf("%s\n", files.getElementAt(i)); } /*for(int i=0; i< filetest.size(); i++){ System.out.printf("%s\n", filetest.getElementAt(i)); }*/ allFiles.addMouseListener(new MouseAdapter(){ @Override public void mouseClicked(MouseEvent e){ int selectedItem = allFiles.getSelectedIndex(); lastFileState.addElement(Integer.toString(selectedItem)); } }); allFiles.setCellRenderer(new ListRenderer()); JScrollPane pane = new JScrollPane(allFiles); pane.setPreferredSize(new Dimension(250, 440)); //allFiles.setSelectionBackground(Color.green); allFiles.setBackground(listColor); return pane; } public static void fileSearch(String search){ //int cap = debug.getSize(); int cap = filetest.getSize(); files.clear(); for(int i=0; i<cap; i++){ //ListModel model = debug.elementAt(i); ListModel model = filetest.elementAt(i); String name = model.getName(); if(name.indexOf(search) != -1){ ListModel add = new ListModel(model.getName(), model.getStatus()); //filetest.addElement(add); files.addElement(add);; } } } public static JPanel searchPanel() { JPanel panel = new JPanel(); JLabel label = new JLabel("Search:"); JTextField search = new JTextField("search...", 12); search.setEnabled(false); // fileSearch(search.getText()); search.setBackground(listColor); search.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { search.setText(""); search.setEnabled(true); search.requestFocus(); } }); search.getDocument().addDocumentListener(new DocumentListener(){ @Override public void changedUpdate(DocumentEvent arg0) { System.out.printf("changed\n"); } @Override public void insertUpdate(DocumentEvent arg0) { fileSearch(search.getText()); globalSearch = search.getText(); } @Override public void removeUpdate(DocumentEvent arg0) { fileSearch(search.getText()); globalSearch = search.getText(); } }); label.setForeground(textColor); label.setFont(font); panel.add(label); panel.add(search); return panel; } public static JPanel varsPanel() { //create panel final JPanel panel = new JPanel(); BoxLayout layout = new BoxLayout(panel, BoxLayout.Y_AXIS); panel.setLayout(layout); //create components final JLabel varsPanelLabel = new JLabel("Enter Encryption Key:"); final JButton lockPassButton = new JButton("confirm key"); final JTextField keyField = new JTextField("key...",10); keyField.setEnabled(false); keyField.setBackground(listColor); lockPassButton.setForeground(buttonTextColor); //bind methods to buttons lockPassButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { IInterface.INSTANCE.setEncryptKey(keyField.getText()); } }); keyField.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { keyField.setText(""); keyField.setEnabled(true); keyField.requestFocus(); } }); //add components to panel and specify orientation varsPanelLabel.setForeground(textColor); varsPanelLabel.setFont(font); panel.add(varsPanelLabel); panel.add(keyField); panel.add(lockPassButton); panel.setComponentOrientation( ComponentOrientation.LEFT_TO_RIGHT); return panel; } public static JPanel storagePanel(){ JPanel panel = new JPanel(); GridLayout layout = new GridLayout(2, 2, 0, 0); panel.setLayout(layout); panel.setPreferredSize(new Dimension(280, 50)); int min = 0; int max = 100; int init = 1; final JLabel sliderLabel = new JLabel("Storage:"); final JLabel positionLabel = new JLabel(""); sliderLabel.setForeground(textColor); sliderLabel.setFont(font); final JSlider slider = new JSlider(JSlider.HORIZONTAL, min, max, init); slider.setBackground(colorBlue); slider.setPreferredSize(new Dimension(200, 30)); slider.setMajorTickSpacing(max / 10); slider.setPaintTicks(true); final JLabel currStorageLabel = new JLabel(String.valueOf(slider.getValue()) + " GB"); currStorageLabel.setForeground(textColor); currStorageLabel.setFont(font); slider.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { if (!slider.getValueIsAdjusting()) { currStorageLabel.setText(String.valueOf(slider.getValue()) + " GB"); IInterface.INSTANCE.setStorageSpace(slider.getValue()); } } }); panel.add(sliderLabel); panel.add(positionLabel); panel.add(slider); panel.add(currStorageLabel); panel.setComponentOrientation( ComponentOrientation.LEFT_TO_RIGHT); return panel; } public static JPanel selectUsersPanel() { //create panel final JPanel panel = new JPanel(); final JLabel selectUser = new JLabel("Select Peer: "); final JButton selectAllButton = new JButton("all"); final JButton selectNoneButton = new JButton("none"); selectAllButton.setForeground(buttonTextColor); selectNoneButton.setForeground(buttonTextColor); //bind methods to buttons selectAllButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.out.printf("[*] selecting all\n"); for(int i=0; i < (allUsers.getModel().getSize()); i++){ lastUserState.addElement(Integer.toString(i)); } } }); selectNoneButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.out.printf("[*] selecting none\n"); lastUserState.clear(); } }); selectUser.setForeground(textColor); selectUser.setFont(font); panel.add(selectUser); panel.add(selectAllButton); panel.add(selectNoneButton); return panel; } public static JPanel selectFilesPanel() { //create panel final JPanel panel = new JPanel(); final JLabel selectFiles = new JLabel("Select File: "); final JButton selectAllButton = new JButton("all"); final JButton selectNoneButton = new JButton("none"); selectAllButton.setForeground(buttonTextColor); selectNoneButton.setForeground(buttonTextColor); //bind methods to buttons selectAllButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.out.printf("[*] selecting all\n"); for(int i=0; i < (allFiles.getModel().getSize()); i++){ lastFileState.addElement(Integer.toString(i)); } } }); selectNoneButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.out.printf("[*] selecting none\n"); lastFileState.clear(); } }); selectFiles.setForeground(textColor); selectFiles.setFont(font); panel.add(selectFiles); panel.add(selectAllButton); panel.add(selectNoneButton); return panel; } public static void updateFileSelection(){ for(int i=0; i<lastFileState.getSize(); i++){ allFiles.addSelectionInterval(Integer.parseInt(lastFileState.elementAt(i)), Integer.parseInt(lastFileState.elementAt(i))); } } public static void updateUserSelection(){ for(int i=0; i<lastUserState.getSize(); i++){ allUsers.addSelectionInterval(Integer.parseInt(lastUserState.elementAt(i)), Integer.parseInt(lastUserState.elementAt(i))); } } public static JPanel logPanel() { //create panel final JPanel panel = new JPanel(); BoxLayout layout = new BoxLayout(panel, BoxLayout.Y_AXIS); panel.setLayout(layout); //create components final JLabel logLabel = new JLabel("Event Log:"); logLabel.setForeground(textColor); logLabel.setFont(font); log.setEditable(false); //log.append(text + newline) log.setBackground(listColor); panel.add(logLabel); panel.add(new JScrollPane(log)); return panel; } public static SpringLayout frameLayout() { SpringLayout layout = new SpringLayout(); //set locations for each panel for (Component panel : panelLocs.keySet()) { layout.putConstraint(SpringLayout.NORTH, panel, panelLocs.get(panel).get(1), SpringLayout.NORTH, contentPane); layout.putConstraint(SpringLayout.WEST, panel, panelLocs.get(panel).get(0), SpringLayout.WEST, contentPane); } return layout; } public static JPanel namePanel() { //create panel final JPanel panel = new JPanel(); //BoxLayout layout = new BoxLayout(panel, BoxLayout.Y_AXIS); //panel.setLayout(layout); //create components final JLabel nameLabel = new JLabel("Enter Device Name: "); final JButton lockNameButton = new JButton("set"); final JTextField nameField = new JTextField("name...",10); nameField.setEnabled(false); nameField.setBackground(listColor); lockNameButton.setForeground(buttonTextColor); //bind methods to buttons lockNameButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { IInterface.INSTANCE.setDisplayName(nameField.getText()); } }); nameField.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { nameField.setText(""); nameField.setEnabled(true); nameField.requestFocus(); } }); //add components to panel and specify orientation nameLabel.setForeground(textColor); nameLabel.setFont(font); panel.add(nameLabel); panel.add(nameField); panel.add(lockNameButton); panel.setComponentOrientation( ComponentOrientation.LEFT_TO_RIGHT); return panel; } public static JPanel leftColorPanel() { JPanel panel = new JPanel(); panel.setBackground(colorBlue); panel.setPreferredSize(new Dimension(310, 600)); return panel; } public static JPanel linePanel() { JPanel panel = new JPanel(); panel.setBackground(colorGray); panel.setPreferredSize(new Dimension(318, 600)); return panel; } public static JPanel topColorPanel() { JPanel panel = new JPanel(); panel.setBackground(colorGray); panel.setPreferredSize(new Dimension(1000, 100)); return panel; } //bind panels to frame and display the gui public static void startGui() { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { //load network IInterface.INSTANCE.loadNetwork(); //start those intervals startIntervals(500); //create the window and center it on screen frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setResizable(false); //left column locations panelLocs.put(loginPanel, Arrays.asList(30, 10)); panelLocs.put(varsPanel, Arrays.asList(30, 120)); panelLocs.put(controlPanel, Arrays.asList(30, 210)); panelLocs.put(logPanel, Arrays.asList(30, 425)); panelLocs.put(storagePanel, Arrays.asList(30, 365)); //middle column locatinos panelLocs.put(userListPanel, Arrays.asList(370, 80)); panelLocs.put(selectUsersPanel, Arrays.asList(350, 40)); //right column locations panelLocs.put(searchPanel, Arrays.asList(650, 10)); panelLocs.put(selectFilesPanel, Arrays.asList(650, 40)); panelLocs.put(fileListPanel, Arrays.asList(670, 80)); panelLocs.put(namePanel, Arrays.asList(610, 540)); //confirm layout contentPane.setLayout(frameLayout()); frame.setSize(1000, 620); frame.setLocationRelativeTo(null); for (Component panel : panelLocs.keySet()) { contentPane.add(panel); } contentPane.add(leftColorPanel()); contentPane.add(linePanel()); //contentPane.add(topColorPanel()); //set background color Color globalColor = colorBlue; //background stuff frame.getContentPane().setBackground(backgroundColor); searchPanel.setBackground(backgroundColor); selectFilesPanel.setBackground(backgroundColor); selectUsersPanel.setBackground(backgroundColor); namePanel.setBackground(backgroundColor); //left panel stuff loginPanel.setBackground(globalColor); varsPanel.setBackground(globalColor); storagePanel.setBackground(globalColor); logPanel.setBackground(globalColor); controlPanel.setBackground(globalColor); //display the window frame.validate(); frame.repaint(); frame.setVisible(true); } }); } }
package io.cloudchaser.murmur; import io.cloudchaser.murmur.parser.MurmurParser; import io.cloudchaser.murmur.parser.MurmurParserBaseVisitor; import io.cloudchaser.murmur.symbol.Symbol; import io.cloudchaser.murmur.symbol.SymbolContext; import io.cloudchaser.murmur.types.MurmurInteger; import io.cloudchaser.murmur.types.MurmurObject; import java.util.HashMap; import java.util.Map; /** * * @author Mihail K * @since 0.1 */ public class MurmurASTVisitor extends MurmurParserBaseVisitor<MurmurObject> { private static class MurmurBaseContext implements SymbolContext { private final Map<String, Symbol> symbols; public MurmurBaseContext() { symbols = new HashMap<>(); } @Override public SymbolContext getParent() { return null; } @Override public void addSymbol(Symbol symbol) { symbols.put(symbol.getName(), symbol); } @Override public Symbol getSymbol(String name) { return symbols.get(name); } } private final SymbolContext context; public MurmurASTVisitor() { context = new MurmurBaseContext(); } @Override public MurmurObject visitCompilationUnit(MurmurParser.CompilationUnitContext ctx) { // Visit children. ctx.statement().stream().forEach(this::visitStatement); return null; } @Override public MurmurObject visitStatement(MurmurParser.StatementContext ctx) { // Print results for debug. System.out.println(visitExpression(ctx.expression())); return null; } /* - Statements - */ public MurmurObject visitLeftArrowStatement(MurmurParser.KeywordStatementContext ctx) { // TODO return null; } public MurmurObject visitRightArrowStatement(MurmurParser.KeywordStatementContext ctx) { // TODO return null; } public MurmurObject visitBreakStatement(MurmurParser.KeywordStatementContext ctx) { // TODO return null; } public MurmurObject visitContinueStatement(MurmurParser.KeywordStatementContext ctx) { // TODO return null; } public MurmurObject visitLetStatement(MurmurParser.KeywordStatementContext ctx) { // TODO return null; } public MurmurObject visitReturnStatement(MurmurParser.KeywordStatementContext ctx) { // TODO return null; } public MurmurObject visitThrowStatement(MurmurParser.KeywordStatementContext ctx) { // TODO return null; } @Override public MurmurObject visitKeywordStatement(MurmurParser.KeywordStatementContext ctx) { if(ctx.operator != null) { // Keyword/operator. switch(ctx.operator.getText()) { case "<-": return visitLeftArrowStatement(ctx); case "->": return visitRightArrowStatement(ctx); case "break": return visitBreakStatement(ctx); case "continue": return visitContinueStatement(ctx); case "let": return visitLetStatement(ctx); case "return": return visitReturnStatement(ctx); case "throw": return visitThrowStatement(ctx); default: // Unknown operation. throw new RuntimeException(); } } // Something went wrong. throw new RuntimeException(); } /* - Interfaces - */ public MurmurObject visitITypeFunction(MurmurParser.ITypeElementContext ctx) { // TODO return null; } @Override public MurmurObject visitITypeElement(MurmurParser.ITypeElementContext ctx) { // TODO return null; } /* - Classes - */ public MurmurObject visitTypeField(MurmurParser.TypeElementContext ctx) { // TODO return null; } public MurmurObject visitTypeFunction(MurmurParser.TypeElementContext ctx) { // TODO return null; } @Override public MurmurObject visitTypeElement(MurmurParser.TypeElementContext ctx) { // TODO return null; } /* - Expressions - */ public MurmurObject visitPositiveExpression(MurmurParser.ExpressionContext ctx) { // TODO return null; } public MurmurObject visitPreIncrementExpression(MurmurParser.ExpressionContext ctx) { // TODO return null; } public MurmurObject visitPostIncrementExpression(MurmurParser.ExpressionContext ctx) { // TODO return null; } public MurmurObject visitAdditionExpression(MurmurParser.ExpressionContext ctx) { MurmurObject left = visitExpression(ctx.left); MurmurObject right = visitExpression(ctx.right); return left.opPlus(right); } public MurmurObject visitNegativeExpression(MurmurParser.ExpressionContext ctx) { // TODO return null; } public MurmurObject visitPreDecrementExpression(MurmurParser.ExpressionContext ctx) { // TODO return null; } public MurmurObject visitPostDecrementExpression(MurmurParser.ExpressionContext ctx) { // TODO return null; } public MurmurObject visitSubtractionExpression(MurmurParser.ExpressionContext ctx) { // TODO return null; } public MurmurObject visitMultiplicationExpression(MurmurParser.ExpressionContext ctx) { // TODO return null; } public MurmurObject visitDivisionExpression(MurmurParser.ExpressionContext ctx) { // TODO return null; } public MurmurObject visitModuloExpression(MurmurParser.ExpressionContext ctx) { // TODO return null; } public MurmurObject visitEqualExpression(MurmurParser.ExpressionContext ctx) { // TODO return null; } public MurmurObject visitNotEqualExpression(MurmurParser.ExpressionContext ctx) { // TODO return null; } public MurmurObject visitLogicalNotExpression(MurmurParser.ExpressionContext ctx) { // TODO return null; } public MurmurObject visitLogicalAndExpression(MurmurParser.ExpressionContext ctx) { // TODO return null; } public MurmurObject visitLogicalOrExpression(MurmurParser.ExpressionContext ctx) { // TODO return null; } public MurmurObject visitBinaryNotExpression(MurmurParser.ExpressionContext ctx) { // TODO return null; } public MurmurObject visitBinaryAndExpression(MurmurParser.ExpressionContext ctx) { // TODO return null; } public MurmurObject visitBinaryXorExpression(MurmurParser.ExpressionContext ctx) { // TODO return null; } public MurmurObject visitBinaryOrExpression(MurmurParser.ExpressionContext ctx) { // TODO return null; } public MurmurObject visitLessThanExpression(MurmurParser.ExpressionContext ctx) { // TODO return null; } public MurmurObject visitGreaterThanExpression(MurmurParser.ExpressionContext ctx) { // TODO return null; } public MurmurObject visitLessOrEqualExpression(MurmurParser.ExpressionContext ctx) { // TODO return null; } public MurmurObject visitGreaterOrEqualExpression(MurmurParser.ExpressionContext ctx) { // TODO return null; } public MurmurObject visitShiftLeftExpression(MurmurParser.ExpressionContext ctx) { // TODO return null; } public MurmurObject visitShiftRightExpression(MurmurParser.ExpressionContext ctx) { // TODO return null; } public MurmurObject visitTernaryExpression(MurmurParser.ExpressionContext ctx) { // TODO return null; } public MurmurObject visitArrayIndexExpression(MurmurParser.ExpressionContext ctx) { // TODO return null; } public MurmurObject visitFunctionArguments(MurmurParser.ExpressionListContext ctx) { // Visit the argument list. ctx.expression().stream().forEach(this::visitExpression); // TODO return null; } public MurmurObject visitFunctionCallExpression(MurmurParser.ExpressionContext ctx) { if(ctx.expressionList() != null) { visitFunctionArguments(ctx.expressionList()); } // TODO return null; } public MurmurObject visitAssignmentExpression(MurmurParser.ExpressionContext ctx) { // TODO return null; } public MurmurObject visitMemberExpression(MurmurParser.ExpressionContext ctx) { // TODO return null; } public MurmurObject visitSetNotationExpression(MurmurParser.ExpressionContext ctx) { // TODO return null; } public MurmurObject visitIdentifierExpression(MurmurParser.ExpressionContext ctx) { return context.getSymbol(ctx.getText()); } @Override public MurmurObject visitExpression(MurmurParser.ExpressionContext ctx) { // Literals. if(ctx.literal() != null) { return visitLiteral(ctx.literal()); } if(ctx.operator != null) { // Operator types. switch(ctx.operator.getText()) { case ".": // Expression: a.b return visitMemberExpression(ctx); case ",": // Expression: [a, b] return visitSetNotationExpression(ctx); case "+": if(ctx.left != null) // Expression: a + b return visitAdditionExpression(ctx); // Expression: +a return visitPositiveExpression(ctx); case "-": if(ctx.left != null) // Expression: a - b return visitSubtractionExpression(ctx); // Expression: -a return visitNegativeExpression(ctx); case "*": // Expression: a * b return visitMultiplicationExpression(ctx); case "/": // Expression: a / b return visitDivisionExpression(ctx); case "%": // Expression: a % b return visitModuloExpression(ctx); case "!": // Expression: !a return visitLogicalNotExpression(ctx); case "~": // Expression: ~a return visitBinaryNotExpression(ctx); case "&": // Expression: a & b return visitBinaryAndExpression(ctx); case "^": // Expression: a ^ b return visitBinaryXorExpression(ctx); case "|": // Expression: a | b return visitBinaryOrExpression(ctx); case "<": // Expression: a < b return visitLessThanExpression(ctx); case ">": // Expression: a > b return visitGreaterThanExpression(ctx); case "=": // Expression: a = b return visitAssignmentExpression(ctx); case "?": // Expression: a ? b : c return visitTernaryExpression(ctx); case "(": // Expression: a(b, c, ...) return visitFunctionCallExpression(ctx); case "[": // Expression: a[b] return visitArrayIndexExpression(ctx); case "++": if(ctx.left != null) // Expression: a++ return visitPostIncrementExpression(ctx); // Expression: ++a return visitPreIncrementExpression(ctx); case " if(ctx.left != null) // Expression: a-- return visitPostDecrementExpression(ctx); // Expression: --a return visitPreDecrementExpression(ctx); case "&&": // Expression: a && b return visitLogicalAndExpression(ctx); case "||": // Expression: a || b return visitLogicalOrExpression(ctx); case "==": // Expression: a == b return visitEqualExpression(ctx); case "!=": // Expression: a != b return visitNotEqualExpression(ctx); case "<=": // Expression: a <= b return visitLessOrEqualExpression(ctx); case ">=": // Expression: a >= b return visitGreaterOrEqualExpression(ctx); case "<<": // Expression: a << b return visitShiftLeftExpression(ctx); case ">>": // Expression: a >> b return visitShiftRightExpression(ctx); default: // Unknown operator. throw new RuntimeException(); } } // Identifier. if(ctx.Identifier() != null) { return visitIdentifierExpression(ctx); } // Lambda. if(ctx.lambda() != null) { return visitLambda(ctx.lambda()); } // Parenthesized. if(ctx.inner != null) { return visitExpression(ctx.inner); } throw new RuntimeException(); } /* - Literal Types - */ public MurmurInteger visitIntegerLiteral(MurmurParser.LiteralContext ctx) { long value = Long.parseLong(ctx.getText()); if(value == 0) return MurmurInteger.ZERO; return new MurmurInteger(value); } public MurmurObject visitDecimalLiteral(MurmurParser.LiteralContext ctx) { // TODO return null; } public MurmurObject visitBooleanLiteral(MurmurParser.LiteralContext ctx) { // TODO return null; } public MurmurObject visitCharacterLiteral(MurmurParser.LiteralContext ctx) { // TODO return null; } public MurmurObject visitStringLiteral(MurmurParser.LiteralContext ctx) { // TODO return null; } public MurmurObject visitNullLiteral(MurmurParser.LiteralContext ctx) { // TODO return null; } @Override public MurmurObject visitLiteral(MurmurParser.LiteralContext ctx) { // Integer literals. if(ctx.IntegerLiteral() != null) { return visitIntegerLiteral(ctx); } // Decimal literals. if(ctx.DecimalLiteral() != null) { return visitDecimalLiteral(ctx); } // Boolean literals. if(ctx.BooleanLiteral() != null) { return visitDecimalLiteral(ctx); } // Character literals. if(ctx.CharacterLiteral() != null) { return visitCharacterLiteral(ctx); } // String literals. if(ctx.StringLiteral() != null) { return visitStringLiteral(ctx); } // Null literals. if(ctx.NullLiteral() != null) { return visitNullLiteral(ctx); } // Unknown literal type. throw new RuntimeException(); } }
package io.flutter.module; import com.intellij.icons.AllIcons; import com.intellij.ide.util.projectWizard.WizardContext; import com.intellij.ide.wizard.AbstractWizard; import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory; import com.intellij.openapi.ui.ComboBox; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.ui.TextComponentAccessor; import com.intellij.openapi.ui.ValidationInfo; import com.intellij.openapi.util.IconLoader; import com.intellij.openapi.util.io.FileUtilRt; import com.intellij.ui.ComboboxWithBrowseButton; import com.intellij.ui.DocumentAdapter; import com.intellij.ui.JBProgressBar; import com.intellij.ui.components.JBLabel; import com.intellij.ui.components.labels.LinkLabel; import com.intellij.util.ReflectionUtil; import com.intellij.util.ui.UIUtil; import com.intellij.xml.util.XmlStringUtil; import io.flutter.FlutterBundle; import io.flutter.sdk.FlutterSdkUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.event.DocumentEvent; import javax.swing.text.JTextComponent; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class FlutterGeneratorPeer { private final WizardContext myContext; private JPanel myMainPanel; private ComboboxWithBrowseButton mySdkPathComboWithBrowse; private JBLabel myVersionContent; private JLabel errorIcon; private JTextPane errorText; private JScrollPane errorPane; private LinkLabel myInstallActionLink; private JBProgressBar myProgressBar; private JTextPane myProgressText; private JScrollPane myProgressScrollPane; private JLabel myCancelProgressButton; private final InstallSdkAction myInstallSdkAction; private InstallSdkAction.CancelActionListener myListener; public FlutterGeneratorPeer(WizardContext context) { myContext = context; myInstallSdkAction = new InstallSdkAction(this); errorIcon.setText(""); errorIcon.setIcon(AllIcons.Actions.Lightning); Messages.installHyperlinkSupport(errorText); // Hide pending real content. myVersionContent.setVisible(false); myProgressBar.setVisible(false); myProgressText.setVisible(false); myCancelProgressButton.setVisible(false); init(); validate(); } private void init() { mySdkPathComboWithBrowse.getComboBox().setEditable(true); FlutterSdkUtil.addKnownSDKPathsToCombo(mySdkPathComboWithBrowse.getComboBox()); mySdkPathComboWithBrowse.addBrowseFolderListener(FlutterBundle.message("flutter.sdk.browse.path.label"), null, null, FileChooserDescriptorFactory.createSingleFolderDescriptor(), TextComponentAccessor.STRING_COMBOBOX_WHOLE_TEXT); final JTextComponent editorComponent = (JTextComponent)getSdkEditor().getEditorComponent(); editorComponent.getDocument().addDocumentListener(new DocumentAdapter() { @Override protected void textChanged(DocumentEvent e) { validate(); } }); myInstallActionLink.setIcon(myInstallSdkAction.getLinkIcon()); myInstallActionLink.setDisabledIcon(IconLoader.getDisabledIcon(myInstallSdkAction.getLinkIcon())); myInstallActionLink.setText(myInstallSdkAction.getLinkText()); //noinspection unchecked myInstallActionLink.setListener((label, linkUrl) -> myInstallSdkAction.actionPerformed(null), null); myProgressText.setFont(UIUtil.getLabelFont(UIUtil.FontSize.NORMAL).deriveFont(Font.ITALIC)); // Some feedback on hover. myCancelProgressButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); myCancelProgressButton.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { myListener.actionCanceled(); } }); } @SuppressWarnings("EmptyMethod") void apply() { } @NotNull public JComponent getComponent() { return myMainPanel; } private void createUIComponents() { mySdkPathComboWithBrowse = new ComboboxWithBrowseButton(new ComboBox<>()); } public boolean validate() { final ValidationInfo info = validateSdk(); if (info != null) { errorText.setText(XmlStringUtil.wrapInHtml(info.message)); } errorIcon.setVisible(info != null); errorPane.setVisible(info != null); myInstallActionLink.setEnabled(info != null || getSdkComboPath().trim().isEmpty()); return info == null; } @Nullable private ValidationInfo validateSdk() { final String sdkPath = getSdkComboPath(); final String message = FlutterSdkUtil.getErrorMessageIfWrongSdkRootPath(sdkPath); if (message != null) { return new ValidationInfo(message, mySdkPathComboWithBrowse); } return null; } @NotNull public String getSdkComboPath() { return FileUtilRt.toSystemIndependentName(getSdkEditor().getItem().toString().trim()); } @NotNull public ComboBoxEditor getSdkEditor() { return mySdkPathComboWithBrowse.getComboBox().getEditor(); } @NotNull public ComboboxWithBrowseButton getSdkComboBox() { return mySdkPathComboWithBrowse; } public void setSdkPath(@NotNull String sdkPath) { getSdkEditor().setItem(sdkPath); } public JBProgressBar getProgressBar() { return myProgressBar; } public LinkLabel getInstallActionLink() { return myInstallActionLink; } public JTextPane getProgressText() { return myProgressText; } public JLabel getCancelProgressButton() { return myCancelProgressButton; } /** * Set error details (pass null to hide). */ public void setErrorDetails(@Nullable String details) { final boolean makeVisible = details != null; if (makeVisible) { errorText.setText(details); } errorIcon.setVisible(makeVisible); errorPane.setVisible(makeVisible); } public void addCancelActionListener(InstallSdkAction.CancelActionListener listener) { myListener = listener; } public void requestNextStep() { final AbstractWizard wizard = myContext.getWizard(); if (wizard != null) { // AbstractProjectWizard makes `doNextAction` public but we can't reference it directly since it does not exist in WebStorm. final Method nextAction = ReflectionUtil.getMethod(wizard.getClass(), "doNextAction"); if (nextAction != null) { try { nextAction.invoke(wizard); } catch (IllegalAccessException | InvocationTargetException e) { // Ignore. } } } } }
package io.flutter.module; import com.intellij.execution.OutputListener; import com.intellij.execution.process.ProcessListener; import com.intellij.ide.util.projectWizard.ModuleBuilder; import com.intellij.ide.util.projectWizard.ModuleWizardStep; import com.intellij.ide.util.projectWizard.SettingsStep; import com.intellij.ide.util.projectWizard.WizardContext; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.WriteAction; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.module.*; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ModifiableRootModel; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import icons.FlutterIcons; import io.flutter.FlutterBundle; import io.flutter.FlutterConstants; import io.flutter.FlutterMessages; import io.flutter.FlutterUtils; import io.flutter.actions.FlutterDoctorAction; import io.flutter.module.settings.FlutterCreateAdditionalSettingsFields; import io.flutter.pub.PubRoot; import io.flutter.sdk.FlutterCreateAdditionalSettings; import io.flutter.sdk.FlutterSdk; import io.flutter.sdk.FlutterSdkUtil; import io.flutter.utils.FlutterModuleUtils; import org.apache.commons.lang.StringUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.io.IOException; import java.util.concurrent.atomic.AtomicReference; import static java.util.Arrays.asList; public class FlutterModuleBuilder extends ModuleBuilder { private static final Logger LOG = Logger.getInstance(FlutterModuleBuilder.class); private FlutterModuleWizardStep myStep; @NotNull private final FlutterCreateAdditionalSettingsFields mySettingsFields = new FlutterCreateAdditionalSettingsFields(new FlutterCreateAdditionalSettings()); @Override public String getName() { return getPresentableName(); } @Override public String getPresentableName() { return FlutterBundle.message("flutter.module.name"); } @Override public String getDescription() { return FlutterBundle.message("flutter.project.description"); } @Override public Icon getNodeIcon() { return FlutterIcons.Flutter; } @Override public void setupRootModel(ModifiableRootModel model) { doAddContentEntry(model); // Add a reference to Dart SDK project library, without committing. model.addInvalidLibrary("Dart SDK", "project"); } protected FlutterSdk getFlutterSdk() { return myStep.getFlutterSdk(); } @Nullable @Override public Module commitModule(@NotNull Project project, @Nullable ModifiableModuleModel model) { final String basePath = getModuleFileDirectory(); if (basePath == null) { Messages.showErrorDialog("Module path not set", "Internal Error"); return null; } final VirtualFile baseDir = LocalFileSystem.getInstance().refreshAndFindFileByPath(basePath); if (baseDir == null) { Messages.showErrorDialog("Unable to determine Flutter project directory", "Internal Error"); return null; } final FlutterSdk sdk = getFlutterSdk(); if (sdk == null) { Messages.showErrorDialog("Flutter SDK not found", "Error"); return null; } final OutputListener listener = new OutputListener(); final PubRoot root = runFlutterCreateWithProgress(baseDir, sdk, project, listener, getAdditionalSettings()); if (root == null) { final String stderr = listener.getOutput().getStderr(); final String msg = stderr.isEmpty() ? "Flutter create command was unsuccessful" : stderr; final int code = FlutterMessages.showDialog(project, msg, "Project Creation Error", new String[]{"Run Flutter Doctor", "Cancel"}, 0); if (code == 0) { new FlutterDoctorAction().startCommand(project, sdk, null); } return null; } FlutterSdkUtil.updateKnownSdkPaths(sdk.getHomePath()); // Create the Flutter module. This indirectly calls setupRootModule, etc. final Module flutter = super.commitModule(project, model); if (flutter == null) { return null; } FlutterModuleUtils.autoShowMain(project, root); addAndroidModule(project, model, basePath, flutter.getName()); return flutter; } private static String validateSettings(FlutterCreateAdditionalSettings settings) { final String description = settings.getDescription(); if (description != null && description.contains(": ")) { return "Invalid package description: '" + description + "' - cannot contain the sequence ': '."; } final String org = settings.getOrg(); if (StringUtils.endsWith(org, ".")) { return "Invalid organization name: '" + org + "' - cannot end in '.'."; } return null; } private static void addAndroidModule(@NotNull Project project, @Nullable ModifiableModuleModel model, @NotNull String baseDirPath, @NotNull String flutterModuleName) { final VirtualFile baseDir = LocalFileSystem.getInstance().refreshAndFindFileByPath(baseDirPath); if (baseDir == null) { return; } final VirtualFile androidFile = findAndroidModuleFile(baseDir, flutterModuleName); if (androidFile == null) return; try { final ModifiableModuleModel toCommit; if (model == null) { toCommit = ModuleManager.getInstance(project).getModifiableModel(); //noinspection AssignmentToMethodParameter model = toCommit; } else { toCommit = null; } model.loadModule(androidFile.getPath()); if (toCommit != null) { WriteAction.run(toCommit::commit); } } catch (ModuleWithNameAlreadyExists | IOException e) { LOG.warn(e); } } @Nullable private static VirtualFile findAndroidModuleFile(@NotNull VirtualFile baseDir, String flutterModuleName) { baseDir.refresh(false, false); for (String name : asList(flutterModuleName + "_android.iml", "android.iml")) { final VirtualFile candidate = baseDir.findChild(name); if (candidate != null && candidate.exists()) { return candidate; } } return null; } @Override public boolean validate(Project current, Project dest) { final String settingsValidation = validateSettings(getAdditionalSettings()); if (settingsValidation != null) { Messages.showErrorDialog(settingsValidation, "Error"); return false; } return myStep.getFlutterSdk() != null; } @Override public boolean validateModuleName(@NotNull String moduleName) throws ConfigurationException { if (!FlutterUtils.isValidPackageName(moduleName)) { throw new ConfigurationException( "Invalid module name: '" + moduleName + "' - must be a valid Dart package name (lower_case_with_underscores)."); } if (FlutterUtils.isDartKeyword(moduleName)) { throw new ConfigurationException("Invalid module name: '" + moduleName + "' - must not be a Dart keyword."); } if (!FlutterUtils.isValidDartIdentifier(moduleName)) { throw new ConfigurationException("Invalid module name: '" + moduleName + "' - must be a valid Dart identifier."); } if (FlutterConstants.FLUTTER_PACKAGE_DEPENDENCIES.contains(moduleName)) { throw new ConfigurationException("Invalid module name: '" + moduleName + "' - this will conflict with Flutter package dependencies."); } if (moduleName.length() > FlutterConstants.MAX_MODULE_NAME_LENGTH) { throw new ConfigurationException("Invalid module name - must be less than " + FlutterConstants.MAX_MODULE_NAME_LENGTH + " characters."); } return super.validateModuleName(moduleName); } @NotNull public FlutterCreateAdditionalSettings getAdditionalSettings() { return mySettingsFields.getAdditionalSettings(); } @Nullable @Override public ModuleWizardStep modifySettingsStep(@NotNull SettingsStep settingsStep) { final ModuleWizardStep wizard = super.modifySettingsStep(settingsStep); mySettingsFields.addSettingsFields(settingsStep); return wizard; } @Override public ModuleWizardStep modifyProjectTypeStep(@NotNull SettingsStep settingsStep) { // Don't allow super to add an SDK selection field (#2052). return null; } @Nullable @Override public ModuleWizardStep getCustomOptionsStep(final WizardContext context, final Disposable parentDisposable) { myStep = new FlutterModuleWizardStep(context); Disposer.register(parentDisposable, myStep); return myStep; } @Override @NotNull public String getBuilderId() { // The builder id is used to distinguish between different builders with the same module type, see // com.intellij.ide.projectWizard.ProjectTypeStep for an example. return StringUtil.notNullize(super.getBuilderId()) + "_" + FlutterModuleBuilder.class.getCanonicalName(); } @Override @NotNull public ModuleType getModuleType() { return FlutterModuleUtils.getFlutterModuleType(); } /** * Runs flutter create without showing a console, but with an indeterminate progress dialog. * <p> * Returns the PubRoot if successful. */ @Nullable private static PubRoot runFlutterCreateWithProgress(@NotNull VirtualFile baseDir, @NotNull FlutterSdk sdk, @NotNull Project project, @Nullable ProcessListener processListener, @Nullable FlutterCreateAdditionalSettings additionalSettings) { final ProgressManager progress = ProgressManager.getInstance(); final AtomicReference<PubRoot> result = new AtomicReference<>(null); FlutterUtils.disableGradleProjectMigrationNotification(project); progress.runProcessWithProgressSynchronously(() -> { progress.getProgressIndicator().setIndeterminate(true); result.set(sdk.createFiles(baseDir, null, processListener, additionalSettings)); }, "Creating Flutter Project", false, project); return result.get(); } public void setFlutterSdkPath(String s) { final ComboBoxEditor combo = myStep.myPeer.getSdkEditor(); combo.setItem(s); } public static class FlutterModuleWizardStep extends ModuleWizardStep implements Disposable { private final FlutterGeneratorPeer myPeer; public FlutterModuleWizardStep(@NotNull WizardContext context) { //TODO(pq): find a way to listen to wizard cancelation and propagate to peer. myPeer = new FlutterGeneratorPeer(context); } @Override public JComponent getComponent() { return myPeer.getComponent(); } @Override public void updateDataModel() { } @Override public boolean validate() { final boolean valid = myPeer.validate(); if (valid) { myPeer.apply(); } return valid; } @Override public void dispose() { } @Nullable private FlutterSdk getFlutterSdk() { final String sdkPath = myPeer.getSdkComboPath(); // Ensure the local filesystem has caught up to external processes (e.g., git clone). if (!sdkPath.isEmpty()) { try { LocalFileSystem .getInstance().refreshAndFindFileByPath(sdkPath); } catch (Throwable e) { // It's possible that the refresh will fail in which case we just want to trap and ignore. } } return FlutterSdk.forPath(sdkPath); } } }
package net.sf.picard.metrics; import net.sf.picard.PicardException; import net.sf.picard.util.FormatUtil; import net.sf.picard.util.Histogram; import net.sf.samtools.util.StringUtil; import java.io.*; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.TreeSet; /** * Contains a set of metrics that can be written to a file and parsed back * again. The set of metrics is composed of zero or more instances of a class, * BEAN, that extends {@link MetricBase} (all instances must be of the same type) * and may optionally include one or more histograms that share the same key set. * * @author Tim Fennell */ public class MetricsFile<BEAN extends MetricBase, HKEY extends Comparable> { public static final String MAJOR_HEADER_PREFIX = " public static final String MINOR_HEADER_PREFIX = " public static final String SEPARATOR = "\t"; public static final String HISTO_HEADER = "## HISTOGRAM\t"; public static final String METRIC_HEADER = "## METRICS CLASS\t"; private final List<Header> headers = new ArrayList<Header>(); private final List<BEAN> metrics = new ArrayList<BEAN>(); private final List<Histogram<HKEY>> histograms = new ArrayList<Histogram<HKEY>>(); /** Adds a header to the collection of metrics. */ public void addHeader(Header h) { this.headers.add(h); } /** Returns the list of headers. */ public List<Header> getHeaders() { return Collections.unmodifiableList(this.headers); } /** Adds a bean to the collection of metrics. */ public void addMetric(BEAN bean) { this.metrics.add(bean); } /** Returns the list of headers. */ public List<BEAN> getMetrics() { return Collections.unmodifiableList(this.metrics); } /** Returns the histogram contained in the metrics file if any. */ public Histogram<HKEY> getHistogram() { if (histograms.size() > 0) return this.histograms.get(0); else return null; } /** Sets the histogram contained in the metrics file. */ public void setHistogram(Histogram<HKEY> histogram) { if (this.histograms.isEmpty()) { if (histogram != null) this.histograms.add(histogram); } else { this.histograms.set(0, histogram); } } /** Adds a histogram to the list of histograms in the metrics file. */ public void addHistogram(Histogram<HKEY> histogram) { this.histograms.add(histogram); } /** Returns the number of histograms added to the metrics file. */ public int getNumHistograms() { return this.histograms.size(); } /** Returns the list of headers with the specified type. */ public List<Header> getHeaders(Class<? extends Header> type) { List<Header> tmp = new ArrayList<Header>(); for (Header h : this.headers) { if (h.getClass().equals(type)) { tmp.add(h); } } return tmp; } /** * Writes out the metrics file to the supplied file. The file is written out * headers first, metrics second and histogram third. * * @param f a File into which to write the metrics */ public void write(File f) { FileWriter w = null; try { w = new FileWriter(f); write(w); } catch (IOException ioe) { throw new PicardException("Could not write metrics to file: " + f.getAbsolutePath(), ioe); } finally { if (w != null) { try { w.close(); } catch (IOException e) { } } } } /** * Writes out the metrics file to the supplied writer. The file is written out * headers first, metrics second and histogram third. * * @param w a Writer into which to write the metrics */ public void write(Writer w) { try { FormatUtil formatter = new FormatUtil(); BufferedWriter out = new BufferedWriter(w); printHeaders(out); out.newLine(); printBeanMetrics(out, formatter); out.newLine(); printHistogram(out, formatter); out.newLine(); out.flush(); } catch (IOException ioe) { throw new PicardException("Could not write metrics file.", ioe); } } /** Prints the headers into the provided PrintWriter. */ private void printHeaders(BufferedWriter out) throws IOException { for (Header h : this.headers) { out.append(MAJOR_HEADER_PREFIX); out.append(h.getClass().getName()); out.newLine(); out.append(MINOR_HEADER_PREFIX); out.append(h.toString()); out.newLine(); } } /** Prints each of the metrics entries into the provided PrintWriter. */ private void printBeanMetrics(BufferedWriter out, FormatUtil formatter) throws IOException { if (this.metrics.isEmpty()) { return; } // Write out a header row with the type of the metric class out.append(METRIC_HEADER + getBeanType().getName()); out.newLine(); // Write out the column headers Field[] fields = getBeanType().getFields(); final int fieldCount = fields.length; for (int i=0; i<fieldCount; ++i) { out.append(fields[i].getName()); if (i < fieldCount - 1) { out.append(MetricsFile.SEPARATOR); } else { out.newLine(); } } // Write out each of the data rows for (BEAN bean : this.metrics) { for (int i=0; i<fieldCount; ++i) { try { Object value = fields[i].get(bean); out.append(StringUtil.assertCharactersNotInString(formatter.format(value), '\t', '\n')); if (i < fieldCount - 1) { out.append(MetricsFile.SEPARATOR); } else { out.newLine(); } } catch (IllegalAccessException iae) { throw new PicardException("Could not read property " + fields[i].getName() + " from class of type " + bean.getClass()); } } } out.flush(); } /** Prints the histogram if one is present. */ private void printHistogram(BufferedWriter out, FormatUtil formatter) throws IOException { if (this.histograms.isEmpty()) { return; } // Build a combined key set java.util.Set<HKEY> keys = new TreeSet<HKEY>(); for (Histogram<HKEY> histo : histograms) { if (histo != null) keys.addAll(histo.keySet()); } // Add a header for the histogram key type out.append(HISTO_HEADER + this.histograms.get(0).keySet().iterator().next().getClass().getName()); out.newLine(); // Output a header row out.append(StringUtil.assertCharactersNotInString(this.histograms.get(0).getBinLabel(), '\t', '\n')); for (Histogram<HKEY> histo : this.histograms) { out.append(SEPARATOR); out.append(StringUtil.assertCharactersNotInString(histo.getValueLabel(), '\t', '\n')); } out.newLine(); for (HKEY key : keys) { out.append(key.toString()); for (Histogram<HKEY> histo : this.histograms) { Histogram<HKEY>.Bin bin = histo.get(key); final double value = (bin == null ? 0 : bin.getValue()); out.append(SEPARATOR); out.append(formatter.format(value)); } out.newLine(); } } /** Gets the type of the metrics bean being used. */ private Class<?> getBeanType() { if (this.metrics == null || this.metrics.isEmpty()) { return null; } else { return this.metrics.get(0).getClass(); } } /** Reads the Metrics in from the given reader. */ public void read(Reader r) { BufferedReader in = new BufferedReader(r); FormatUtil formatter = new FormatUtil(); String line = null; try { // First read the headers Header header = null; boolean inHeader = true; while ((line = in.readLine()) != null && inHeader) { line = line.trim(); // A blank line signals the end of the headers, otherwise parse out // the header types and values and build the headers. if ("".equals(line)) { inHeader = false; } else if (line.startsWith(MAJOR_HEADER_PREFIX)) { if (header != null) { throw new IllegalStateException("Consecutive header class lines encountered."); } String className = line.substring(MAJOR_HEADER_PREFIX.length()).trim(); try { header = (Header) loadClass(className).newInstance(); } catch (Exception e) { throw new PicardException("Error load and/or instantiating an instance of " + className, e); } } else if (line.startsWith(MINOR_HEADER_PREFIX)) { if (header == null) { throw new IllegalStateException("Header class must precede header value:" + line); } header.parse(line.substring(MINOR_HEADER_PREFIX.length())); this.headers.add(header); header = null; } else { throw new PicardException("Illegal state. Found following string in metrics file header: " + line); } } if (line == null) { throw new PicardException("No lines in metrics file after header."); } // Then read the metrics if there are any while (!line.startsWith(MAJOR_HEADER_PREFIX)) { line = in.readLine().trim(); } if (line.startsWith(METRIC_HEADER)) { // Get the metric class from the header String className = line.split(SEPARATOR)[1]; Class<?> type = null; try { type = loadClass(className); } catch (ClassNotFoundException cnfe) { throw new PicardException("Could not locate class with name " + className, cnfe); } // Read the next line with the column headers String[] fieldNames = in.readLine().split(SEPARATOR); Field[] fields = new Field[fieldNames.length]; for (int i=0; i<fieldNames.length; ++i) { try { fields[i] = type.getField(fieldNames[i]); } catch (Exception e) { throw new PicardException("Could not get field with name " + fieldNames[i] + " from class " + type.getName()); } } // Now read the values while ((line = in.readLine()) != null) { line = line.trim(); if ("".equals(line)) { break; } else { String[] values = line.split(SEPARATOR); BEAN bean = null; try { bean = (BEAN) type.newInstance(); } catch (Exception e) { throw new PicardException("Error instantiating a " + type.getName(), e); } for (int i=0; i<fields.length; ++i) { Object value = null; if (values[i] != null && values[i].length() > 0) { value = formatter.parseObject(values[i], fields[i].getType()); } try { fields[i].set(bean, value); } catch (Exception e) { throw new PicardException("Error setting field " + fields[i].getName() + " on class of type " + type.getName(), e); } } this.metrics.add(bean); } } } // Then read the histograms if any are present while (line != null && !line.startsWith(MAJOR_HEADER_PREFIX)) { line = in.readLine(); } if (line != null && line.startsWith(HISTO_HEADER)) { // Get the key type of the histogram String keyClassName = line.split(SEPARATOR)[1].trim(); Class<?> keyClass = null; try { keyClass = loadClass(keyClassName); } catch (ClassNotFoundException cnfe) { throw new PicardException("Could not load class with name " + keyClassName); } // Read the next line with the bin and value labels String[] labels = in.readLine().split(SEPARATOR); for (int i=1; i<labels.length; ++i) { this.histograms.add(new Histogram<HKEY>(labels[0], labels[i])); } // Read the entries in the histograms while ((line = in.readLine()) != null && !"".equals(line)) { String[] fields = line.trim().split(SEPARATOR); HKEY key = (HKEY) formatter.parseObject(fields[0], keyClass); for (int i=1; i<fields.length; ++i) { double value = formatter.parseDouble(fields[i]); this.histograms.get(i-1).increment(key, value); } } } } catch (IOException ioe) { throw new PicardException("Could not read metrics from reader.", ioe); } } /** Attempts to load a class, taking into account that some classes have "migrated" from the broad to sf. */ private Class<?> loadClass(String className) throws ClassNotFoundException { try { return Class.forName(className); } catch (ClassNotFoundException cnfe) { if (className.startsWith("edu.mit.broad.picard")) { return loadClass(className.replace("edu.mit.broad.picard", "net.sf.picard")); } else { throw cnfe; } } } /** Checks that the headers, metrics and histogram are all equal. */ @Override public boolean equals(Object o) { if (o == null) { return false; } if (getClass() != o.getClass()) { return false; } MetricsFile that = (MetricsFile) o; if (!this.headers.equals(that.headers)) { return false; } if (!this.metrics.equals(that.metrics)) { return false; } if (!this.histograms.equals(that.histograms)) { return false; } return true; } @Override public int hashCode() { int result = headers.hashCode(); result = 31 * result + metrics.hashCode(); return result; } }
package com.sun.jimi.core; import java.awt.*; import java.awt.image.*; import java.io.*; import java.net.*; import java.util.Enumeration; import com.sun.jimi.core.util.*; import com.sun.jimi.core.raster.JimiRasterImage; public class JimiReader { public static final int UNKNOWN = -1; protected static final int STREAM_BUFFER_SIZE = 10 * 1024; // decoder-related state. protected JimiDecoderFactory decoderFactory; protected JimiDecoder decoder; protected JimiImageFactory imageFactory; protected InputStream input; // cache protected JimiRasterImage cacheJimiImage; protected ImageProducer cacheImageProducer; protected Image cacheImage; protected int cacheIndex = -1; /** image series state */ protected int seriesIndex = 0; protected ImageSeriesDecodingController series; /** true if images should be fully decoded before being returned */ protected boolean synchronous; /** set to true if built-in JPEG decoding is in use */ protected boolean builtinJPEG; protected ImageProducer jpegProducer; protected URL location; protected String filename; protected ProgressListener listener; // Command for the decoder to run when it finishes. protected Runnable cleanupCommand; /** * Create and partially initialize a JimiReader. * * @param imageFactory factory for creating images * @param decoderFactory factory for creating the decoder * @param input stream to read image data from */ protected JimiReader(JimiImageFactory imageFactory, JimiDecoderFactory decoderFactory, InputStream input) throws JimiException { initReader(imageFactory, decoderFactory, input); } /** * Create and partially initialize a JimiReader. * * @param imageFactory factory for creating images * @param input stream to read image data from * @param typeID the mimetype of the image format */ protected JimiReader(JimiImageFactory imageFactory, InputStream input, String typeID) throws JimiException { JimiDecoderFactory decoderFactory = JimiControl.getDecoderByType(typeID); if (decoderFactory == null) { throw new JimiException("No decoder available for " + typeID); } initReader(imageFactory, decoderFactory, input); } /** * Create and partially initialize a JimiReader. * * @param imageFactory factory for creating images * @param filename the name of the image file * @param typeID the mimetype of the image format */ protected JimiReader(JimiImageFactory factory, String filename, String typeID) throws JimiException { cleanupCommand = new StreamCloseCommand(); JimiDecoderFactory decoderFactory = JimiControl.getDecoderByType(typeID); if (decoderFactory == null) { throw new JimiException("No decoder available for " + typeID); } try { InputStream input = new FileInputStream(filename); input = new BufferedInputStream(input, STREAM_BUFFER_SIZE); initReader(imageFactory, decoderFactory, input); } catch (IOException e) { throw new JimiException(e.getMessage()); } } /** * Create and partially initialize a JimiReader. * * @param imageFactory factory for creating images * @param location the URL of the image file */ protected JimiReader(JimiImageFactory imageFactory, URL location) throws JimiException { cleanupCommand = new StreamCloseCommand(); this.location = location; try { JimiDecoderFactory decoderFactory = JimiControl.getDecoderByFileExtension(location.toString()); URLConnection conn = location.openConnection(); InputStream input = location.openStream(); if (decoderFactory == null) { decoderFactory = JimiControl.getDecoderByType(conn.getContentType()); } if (decoderFactory == null) { PushbackInputStream stream = new PushbackInputStream(input, 128); decoderFactory = JimiControl.getDecoderForInputStream(stream); input = stream; } if (decoderFactory == null) { throw new JimiException("No decoder available for location: " + location); } input = new BufferedInputStream(input, STREAM_BUFFER_SIZE); initReader(imageFactory, decoderFactory, input); } catch (IOException e) { throw new JimiException(e.toString()); } } /** * Create and partially initialize a JimiReader. * * @param imageFactory factory for creating images * @param location the URL of the image file * @param typeID the mimetype of the image format */ protected JimiReader(JimiImageFactory imageFactory, URL location, String typeID) throws JimiException { cleanupCommand = new StreamCloseCommand(); this.location = location; try { JimiDecoderFactory decoderFactory = JimiControl.getDecoderByType(typeID); if (decoderFactory == null) { throw new JimiException("No decoder available for file: " + location); } InputStream input = location.openStream(); input = new BufferedInputStream(input, STREAM_BUFFER_SIZE); initReader(imageFactory, decoderFactory, input); } catch (IOException e) { throw new JimiException(e.toString()); } } /** * Create and partially initialize a JimiReader. * * @param imageFactory factory for creating images * @param filename the name of the image file */ protected JimiReader(JimiImageFactory imageFactory, String filename) throws JimiException { cleanupCommand = new StreamCloseCommand(); this.filename = filename; try { JimiDecoderFactory decoderFactory = JimiControl.getDecoderByFileExtension(filename); if (decoderFactory == null) { throw new JimiException("No decoder available for file: " + filename); } InputStream input = new FileInputStream(filename); input = new BufferedInputStream(input, STREAM_BUFFER_SIZE); initReader(imageFactory, decoderFactory, input); } catch (IOException e) { throw new JimiException(e.toString()); } } /** * Create and partially initialize a JimiReader. * * @param imageFactory factory for creating images * @param input stream to read image data from */ protected JimiReader(JimiImageFactory imageFactory, InputStream input) throws JimiException { PushbackInputStream stream = new PushbackInputStream(input, 128); JimiDecoderFactory decoderFactory = JimiControl.getDecoderForInputStream(stream); if (decoderFactory == null) { throw new JimiException("Cannot find decoder for stream"); } initReader(imageFactory, decoderFactory, stream); } /** * Create and partially initialize a JimiReader. * * @param imageFactory factory for creating images */ protected JimiReader(JimiImageFactory imageFactory) throws JimiException { initReader(imageFactory); } /** * Find out how many images are available. */ public int getNumberOfImages() { return UNKNOWN; } /** * Register a ProgressListener to be informed of decoding progress. */ public void setProgressListener(ProgressListener listener) { this.listener = listener; if (decoder != null) { decoder.setProgressListener(listener); } } /** * Set the mime-type of the format. */ public void setMimeType(String typeID) throws JimiException { JimiDecoderFactory decoderFactory = JimiControl.getDecoderByType(typeID); if (decoderFactory == null) { throw new JimiException("Cannot find decoder for type: " + typeID); } if (input != null) { initReader(imageFactory, decoderFactory, input); } else { initReader(imageFactory, decoderFactory); } } /** * Initialize or re-initialize the reader. */ protected void initReader(JimiImageFactory imageFactory, JimiDecoderFactory decoderFactory, InputStream input) { if (decoderFactory instanceof FreeFormat) { imageFactory = JimiUtil.stripStamping(imageFactory); } this.imageFactory = imageFactory; this.decoderFactory = decoderFactory; decoder = decoderFactory.createDecoder(); if (listener != null && decoder != null) { decoder.setProgressListener(listener); } this.input = input; if (decoderFactory.getClass().getName() .equals("com.sun.jimi.core.decoder.builtin.BuiltinDecoderFactory")) { builtinJPEG = true; } else { if (cleanupCommand != null) { decoder.addCleanupCommand(cleanupCommand); } series = decoder.initDecoding(imageFactory, input); } } /** * Initialize or re-initialize the reader. */ protected void initReader(JimiImageFactory imageFactory, JimiDecoderFactory decoderFactory) { if (decoderFactory instanceof FreeFormat) { imageFactory = JimiUtil.stripStamping(imageFactory); } initReader(imageFactory); this.decoderFactory = decoderFactory; decoder = decoderFactory.createDecoder(); if (listener != null) { decoder.setProgressListener(listener); } if (decoderFactory.getClass().getName() .equals("com.sun.jimi.core.decoder.builtin.BuiltinDecoderFactory")) { builtinJPEG = true; } else if (cleanupCommand != null) { decoder.addCleanupCommand(cleanupCommand); } } /** * Initialize or re-initialize the reader. */ protected void initReader(JimiImageFactory factory) { this.imageFactory = factory; } /** * Replace or set the source for the image data. * The JimiReader object already exists and the type of image file * format that can be decoded is set. Setting the image source * to an image file of a type different from what this JimiReader * object is set for will generate exceptions and or errors from * any methods which retrieve Image data in any form. * * @param in InputStream from which to read image data * @exception JimiException is not currently thrown **/ public void setSource(InputStream input) throws JimiException { // initialize reader initReader(imageFactory, decoderFactory, input); } /** * Set a file as the image data source. * * @param filename the name of the file to read from */ public void setSource(String filename) throws JimiException { InputStream input; try { input = new FileInputStream(filename); this.filename = filename; input = new BufferedInputStream(input, STREAM_BUFFER_SIZE); } catch (Exception e) { throw new JimiException("Unable to open source file."); } initReader(imageFactory, decoderFactory, input); } /** * Set a URL as the image data source. * * @param location the location to read from */ public void setSource(URL location) throws JimiException { InputStream input; try { input = location.openStream(); this.location = location; input = new BufferedInputStream(input, STREAM_BUFFER_SIZE); } catch (IOException e) { throw new JimiException("Unable to open source URL."); } } /** * Choose whether to block on image loading, i.e. operate synchronously. * * @param synchronous true if getImage-methods should block until the image * is fully loaded */ public void setBlocking(boolean synchronous) { this.synchronous = synchronous; } /** * Get the size of the first image. */ public Dimension getSize() throws JimiException { JimiRasterImage image = getRasterImage(); image.waitInfoAvailable(); return new Dimension(image.getWidth(), image.getHeight()); } /** * Read a single JimiRasterImage from the source. * @return the JimiRasterImage * @exception JimiException if an error prevents the image from being loaded */ public JimiRasterImage getRasterImage() throws JimiException { if (cacheIndex == 0) { if (cacheJimiImage != null) { return cacheJimiImage; } else { return Jimi.createRasterImage(cacheImageProducer); } } else if (seriesIndex == 0) { JimiRasterImage img = getNextJimiImage(); if (decoder != null) { decoder.setFinished(); } return img; } else { throw new JimiException(); } } /** * Read a single image from the source and return an ImageProducer for it. * @return the ImageProducer * @exception JimiException if an error prevents the image from being loaded */ public ImageProducer getImageProducer() { try { if (cacheIndex == 0) { return cacheImageProducer; } else if (seriesIndex == 0) { ImageProducer img = getNextImageProducer(); if (decoder != null) { decoder.setFinished(); } return img; } } catch (JimiException e) { } return JimiUtil.getErrorImageProducer(); } /** * Reada single image from the source and return an Image representation. * @return the Image */ public Image getImage() { if (cacheIndex == 0) { if (cacheImage != null) { return cacheImage; } else { Image img = Toolkit.getDefaultToolkit().createImage(cacheImageProducer); GraphicsUtils.waitForImage(img); cacheImage = img; return img; } } else { try { Image img = getNextImage(); if (decoder != null) { decoder.setFinished(); } return img; } catch (Exception e) { return JimiUtil.getErrorImage(); } } } /** * Enumerate all images stored in the file. * @return the Enumeration of JimiRasterImages. */ public Enumeration getRasterImageEnumeration() { return new ImageSeriesEnumerator(this, ImageSeriesEnumerator.JIMIIMAGE); } /** * Enumerate all images stored in the file. * @return the Enumeration of Images. */ public Enumeration getImageEnumeration() { return new ImageSeriesEnumerator(this, ImageSeriesEnumerator.IMAGE); } /** * Enumerate all images stored in the file. * @return the Enumeration of ImageProducers. */ public Enumeration getImageProducerEnumeration() { return new ImageSeriesEnumerator(this, ImageSeriesEnumerator.IMAGEPRODUCER); } public void skipNextImage() throws JimiException { if (!series.hasMoreImages()) { series.skipNextImage(); seriesIndex++; } else { throw new JimiException("Attemping to move beyond last image."); } } /* * Random access methods. */ /** * Get an ImageProducer for an image at a specified index in the image series. * This method is not guaranteed to return corrently when referencing * an image behind the reader's current index. * @param n the index of the image to decode * @return the ImageProducer for image number n * @exception JimiException if an error prevents decoding */ public ImageProducer getImageProducer(int n) throws JimiException { if (n < seriesIndex) { throw new JimiException("Unable to access image number " + n); } while (seriesIndex < n) { skipNextImage(); } return getNextImageProducer(); } /** * Get an Image at a specified index in the image series. * This method is not guaranteed to return corrently when referencing * an image behind the reader's current index. * @param n the index of the image to decode * @return the ImageProducer for image number n * @exception JimiException if an error prevents decoding */ public Image getImage(int n) throws JimiException { if (n == cacheIndex && cacheImage != null) { return cacheImage; } else { ImageProducer prod = getImageProducer(n); Image i = Toolkit.getDefaultToolkit().createImage(prod); if (synchronous) { GraphicsUtils.waitForImage(i); } return i; } } /** * Close the reader. This can be called to indicate that no more images * will be requested. When all requested images are fully loaded, * the input is closed. This is implied by single-image getting methods. */ public void close() { if (decoder != null) { decoder.setFinished(); } } protected JimiRasterImage getNextJimiImage() throws JimiException { return getNextJimiImage(true); } /** * Get the next available image. * * @param allowSynchronous false if blocking should not be performed in this method * @return the image * @exception JimiException if an error prevents the image from being loaded */ protected JimiRasterImage getNextJimiImage(boolean allowSynchronous) throws JimiException { if (builtinJPEG) { if (cacheIndex == 0) { return cacheJimiImage; } else if (seriesIndex == 0) { Image image = getBuiltinJPEG(); cacheImage = image; cacheImageProducer = null; cacheJimiImage = null; cacheIndex = 0; seriesIndex++; return Jimi.createRasterImage(image.getSource()); } else { throw new JimiException(); } } else { JimiDecodingController controller = series.getNextController(); JimiImage ji = controller.getJimiImage(); if (allowSynchronous && synchronous) { controller.requestDecoding(); ji.waitFinished(); } JimiRasterImage rasterImage = JimiUtil.asJimiRasterImage(ji); if (rasterImage == null) { throw new JimiException(); } cacheJimiImage = rasterImage; cacheImageProducer = rasterImage.getImageProducer(); cacheImage = null; cacheIndex = seriesIndex; seriesIndex++; return rasterImage; } } /** * Get the next available ImageProducer. * * @exception JimiException if no more ImageProducers can be loaded */ protected ImageProducer getNextImageProducer() throws JimiException { if (builtinJPEG) { if (cacheIndex == 0) { return cacheImageProducer; } else if (seriesIndex == 0) { Image image = getBuiltinJPEG(); cacheIndex = 0; cacheImage = image; cacheImageProducer = image.getSource(); seriesIndex++; return image.getSource(); } else { throw new JimiException(); } } else { JimiRasterImage image = getNextJimiImage(false); cacheJimiImage = image; cacheImageProducer = image.getImageProducer(); cacheIndex = seriesIndex; return image.getImageProducer(); } } /** * Get the next available JimiImage. * * @exception JimiException if no more JimiImages can be loaded */ protected Image getNextImage() throws JimiException { if (builtinJPEG) { if (cacheIndex == 0) { if (cacheImage != null) { return cacheImage; } else { Image image = Toolkit.getDefaultToolkit().createImage(cacheImageProducer); GraphicsUtils.waitForImage(image); return image; } } else if (seriesIndex == 0) { Image image = getBuiltinJPEG(); cacheIndex = 0; cacheImage = image; cacheImageProducer = image.getSource(); seriesIndex++; GraphicsUtils.waitForImage(image); return image; } else { throw new JimiException(); } } ImageProducer producer = getNextImageProducer(); Image image = Toolkit.getDefaultToolkit().createImage(producer); cacheImage = image; GraphicsUtils.waitForImage(image); return image; } /** * Check if more images are available. */ protected boolean hasMoreElements() { if (builtinJPEG) { return seriesIndex == 0; } else { return series.hasMoreImages(); } } /** * Get the decoding controller for the next image in the series. */ protected JimiDecodingController getNextController() { JimiDecodingController controller = series.getNextController(); return controller; } /** * Use the JDKs inbuilt JPEG decoder to read an image. * Ensure that the image is back-ended by a JimiRasterImage. */ protected Image getBuiltinImage() { JimiRasterImage rasterImage = null; try { rasterImage = getBuiltinJimiImage(); } catch (JimiException e) { return JimiUtil.getErrorImage(); } cacheJimiImage = rasterImage; cacheImageProducer = rasterImage.getImageProducer(); Image image = Toolkit.getDefaultToolkit().createImage(rasterImage.getImageProducer()); return image; } /** * Use the JDKs inbuilt JPEG decoder to read an image, and convert it to a * JimiRasterImage. */ protected JimiRasterImage getBuiltinJimiImage() throws JimiException { Image image = getBuiltinJPEG(); JimiRasterImage rasterImage = Jimi.createRasterImage(image.getSource(), imageFactory); return rasterImage; } /** * Low-level interface to builtin JPEG decoder. */ protected Image getBuiltinJPEG() { Image awtimage = null; Toolkit toolkit = Toolkit.getDefaultToolkit(); if (location != null) { awtimage = toolkit.getImage(location); } else if (filename != null) { awtimage = toolkit.getImage(filename); } else { try { byte[] data = new byte[input.available()]; int offset = 0; while (offset < data.length - 1) { offset += input.read(data, offset, data.length - offset); } input.close(); awtimage = toolkit.createImage(data); } catch (IOException e) { awtimage = JimiUtil.getErrorImage(); } } if (Jimi.crippled) { ImageFilter filter = new StampImageFilter(); ImageProducer prod = new FilteredImageSource(awtimage.getSource(), filter); awtimage = Toolkit.getDefaultToolkit().createImage(prod); } return awtimage; } class StreamCloseCommand implements Runnable { public void run() { try { JimiReader.this.input.close(); } catch (IOException e) { } } } } /** * Class for enumerating decoder results in the desired form, * Image, ImageProducer, or JimiImage. */ class ImageSeriesEnumerator implements Enumeration { protected JimiReader reader; protected int type; protected static final int IMAGE = 0; protected static final int JIMIIMAGE = 1; protected static final int IMAGEPRODUCER = 2; protected boolean loadedFirstImage = false; protected boolean error = false; protected Object prev; /** * Enumerate an image series using a specified type. * @param contoller the controller for the series * @param type the type, either ImageProducer, Image, or JimiImage */ public ImageSeriesEnumerator(JimiReader reader, int type) { this.reader = reader; this.type = type; } public boolean hasMoreElements() { return (!error) && ((!loadedFirstImage) || reader.hasMoreElements()); } public Object nextElement() { return createNextElement(); } public Object createNextElement() { loadedFirstImage = true; if (type == JIMIIMAGE) { try { return reader.getNextJimiImage(); } catch (JimiException e) { error = true; return null; } } else if (type == IMAGE) { try { return reader.getNextImage(); } catch (JimiException e) { error = true; return JimiUtil.getErrorImage(); } } else if (type == IMAGEPRODUCER) { try { return reader.getNextImageProducer(); } catch (JimiException e) { error = true; return JimiUtil.getErrorImageProducer(); } } return null; } }
// ImporterDialog.java package loci.plugins.in; import ij.gui.GenericDialog; import java.awt.Checkbox; import java.awt.Choice; import java.awt.Color; import java.awt.Component; import java.awt.KeyboardFocusManager; import java.awt.Label; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.HashMap; import java.util.Map; import java.util.Vector; import javax.swing.JEditorPane; import javax.swing.JScrollPane; import loci.plugins.util.WindowTools; import com.jgoodies.forms.builder.PanelBuilder; import com.jgoodies.forms.layout.CellConstraints; import com.jgoodies.forms.layout.FormLayout; public class MainDialog extends ImporterDialog implements FocusListener, ItemListener, MouseListener { // -- Constants -- /** Initial message to display in help text box. */ public static final String INFO_DEFAULT = "<i>Select an option for a detailed explanation. " + "Documentation written by Glen MacDonald and Curtis Rueden.</i>"; // -- Fields -- protected Checkbox autoscaleBox; protected Checkbox colorizeBox; protected Checkbox concatenateBox; protected Checkbox cropBox; protected Checkbox customColorizeBox; protected Checkbox groupFilesBox; protected Checkbox ungroupFilesBox; protected Checkbox mergeChannelsBox; protected Checkbox openAllSeriesBox; protected Checkbox recordBox; protected Checkbox showMetadataBox; protected Checkbox showOMEXMLBox; protected Checkbox showROIsBox; protected Checkbox specifyRangesBox; protected Checkbox splitZBox; protected Checkbox splitTBox; protected Checkbox splitCBox; protected Choice stackFormatChoice; protected Choice stackOrderChoice; protected Checkbox swapDimsBox; protected Checkbox virtualBox; protected Map<Component, String> infoTable; protected JEditorPane infoPane; // -- Constructor -- /** Creates a general options dialog for the Bio-Formats Importer. */ public MainDialog(ImportProcess process) { super(process); } // -- ImporterDialog methods -- @Override protected boolean needPrompt() { return !process.isWindowless(); } @Override protected GenericDialog constructDialog() { GenericDialog gd = new GenericDialog("Bio-Formats Import Options"); addCheckbox(gd, ImporterOptions.KEY_AUTOSCALE); addCheckbox(gd, ImporterOptions.KEY_COLORIZE); addCheckbox(gd, ImporterOptions.KEY_CONCATENATE); addCheckbox(gd, ImporterOptions.KEY_CROP); addCheckbox(gd, ImporterOptions.KEY_CUSTOM_COLORIZE); addCheckbox(gd, ImporterOptions.KEY_GROUP_FILES); addCheckbox(gd, ImporterOptions.KEY_UNGROUP_FILES); addCheckbox(gd, ImporterOptions.KEY_MERGE_CHANNELS); addCheckbox(gd, ImporterOptions.KEY_OPEN_ALL_SERIES); addCheckbox(gd, ImporterOptions.KEY_QUIET); // NB: invisible addCheckbox(gd, ImporterOptions.KEY_RECORD); addCheckbox(gd, ImporterOptions.KEY_SHOW_METADATA); addCheckbox(gd, ImporterOptions.KEY_SHOW_OME_XML); addCheckbox(gd, ImporterOptions.KEY_SHOW_ROIS); addCheckbox(gd, ImporterOptions.KEY_SPECIFY_RANGES); addCheckbox(gd, ImporterOptions.KEY_SPLIT_Z); addCheckbox(gd, ImporterOptions.KEY_SPLIT_T); addCheckbox(gd, ImporterOptions.KEY_SPLIT_C); addChoice(gd, ImporterOptions.KEY_STACK_FORMAT); addChoice(gd, ImporterOptions.KEY_STACK_ORDER); addCheckbox(gd, ImporterOptions.KEY_SWAP_DIMS); addCheckbox(gd, ImporterOptions.KEY_VIRTUAL); rebuildDialog(gd); return gd; } @Override protected boolean harvestResults(GenericDialog gd) { options.setAutoscale(gd.getNextBoolean()); options.setColorize(gd.getNextBoolean()); options.setConcatenate(gd.getNextBoolean()); options.setCrop(gd.getNextBoolean()); options.setCustomColorize(gd.getNextBoolean()); options.setGroupFiles(gd.getNextBoolean()); options.setUngroupFiles(gd.getNextBoolean()); options.setMergeChannels(gd.getNextBoolean()); options.setOpenAllSeries(gd.getNextBoolean()); options.setQuiet(gd.getNextBoolean()); // NB: invisible options.setRecord(gd.getNextBoolean()); options.setShowMetadata(gd.getNextBoolean()); options.setShowOMEXML(gd.getNextBoolean()); options.setShowROIs(gd.getNextBoolean()); options.setSpecifyRanges(gd.getNextBoolean()); options.setSplitFocalPlanes(gd.getNextBoolean()); options.setSplitTimepoints(gd.getNextBoolean()); options.setSplitChannels(gd.getNextBoolean()); options.setStackFormat(options.getStackFormats()[gd.getNextChoiceIndex()]); options.setStackOrder(options.getStackOrders()[gd.getNextChoiceIndex()]); options.setSwapDimensions(gd.getNextBoolean()); options.setVirtual(gd.getNextBoolean()); return true; } // -- FocusListener methods -- /** Handles information pane updates when component focus changes. */ public void focusGained(FocusEvent e) { Object src = e.getSource(); String text = infoTable.get(src); infoPane.setText("<html>" + text); infoPane.setCaretPosition(0); } public void focusLost(FocusEvent e) { } // -- ItemListener methods -- /** Handles toggling of mutually exclusive options. */ public void itemStateChanged(ItemEvent e) { verifyOptions(e.getSource()); } // -- MouseListener methods -- /** Focuses the component upon mouseover. */ public void mouseEntered(MouseEvent e) { Object src = e.getSource(); if (src instanceof Component) { ((Component) src).requestFocusInWindow(); } } public void mouseClicked(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mousePressed(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } // -- Helper methods -- /** Fancies up the importer dialog to look much nicer. */ private void rebuildDialog(GenericDialog gd) { // extract GUI components from dialog and add listeners Vector<Checkbox> boxes = null; Vector<Choice> choices = null; Vector<Label> labels = null; Label stackFormatLabel = null, stackOrderLabel = null; Component[] c = gd.getComponents(); if (c != null) { boxes = new Vector<Checkbox>(); choices = new Vector<Choice>(); labels = new Vector<Label>(); for (int i=0; i<c.length; i++) { if (c[i] instanceof Checkbox) { Checkbox item = (Checkbox) c[i]; item.addFocusListener(this); item.addItemListener(this); item.addMouseListener(this); boxes.add(item); } else if (c[i] instanceof Choice) { Choice item = (Choice) c[i]; item.addFocusListener(this); item.addItemListener(this); item.addMouseListener(this); choices.add(item); } else if (c[i] instanceof Label) labels.add((Label) c[i]); } autoscaleBox = boxes.get(0); colorizeBox = boxes.get(1); concatenateBox = boxes.get(2); cropBox = boxes.get(3); customColorizeBox = boxes.get(4); groupFilesBox = boxes.get(5); ungroupFilesBox = boxes.get(6); mergeChannelsBox = boxes.get(7); openAllSeriesBox = boxes.get(8); //quietBox = boxes.get(9); recordBox = boxes.get(10); showMetadataBox = boxes.get(11); showOMEXMLBox = boxes.get(12); showROIsBox = boxes.get(13); specifyRangesBox = boxes.get(14); splitZBox = boxes.get(15); splitTBox = boxes.get(16); splitCBox = boxes.get(17); stackFormatChoice = choices.get(0); stackFormatLabel = labels.get(0); stackOrderChoice = choices.get(1); stackOrderLabel = labels.get(1); swapDimsBox = boxes.get(18); virtualBox = boxes.get(19); } verifyOptions(null); // associate information for each option infoTable = new HashMap<Component, String>(); infoTable.put(autoscaleBox, options.getAutoscaleInfo()); infoTable.put(colorizeBox, options.getColorizeInfo()); infoTable.put(concatenateBox, options.getConcatenateInfo()); infoTable.put(cropBox, options.getCropInfo()); infoTable.put(customColorizeBox, options.getCustomColorizeInfo()); infoTable.put(groupFilesBox, options.getGroupFilesInfo()); infoTable.put(ungroupFilesBox, options.getUngroupFilesInfo()); infoTable.put(mergeChannelsBox, options.getMergeChannelsInfo()); infoTable.put(openAllSeriesBox, options.getOpenAllSeriesInfo()); infoTable.put(recordBox, options.getRecordInfo()); infoTable.put(showMetadataBox, options.getShowMetadataInfo()); infoTable.put(showOMEXMLBox, options.getShowOMEXMLInfo()); infoTable.put(showROIsBox, options.getShowROIsInfo()); infoTable.put(specifyRangesBox, options.getSpecifyRangesInfo()); infoTable.put(splitZBox, options.getSplitFocalPlanesInfo()); infoTable.put(splitTBox, options.getSplitTimepointsInfo()); infoTable.put(splitCBox, options.getSplitChannelsInfo()); infoTable.put(stackFormatChoice, options.getStackFormatInfo()); infoTable.put(stackFormatLabel, options.getStackFormatInfo()); infoTable.put(stackOrderChoice, options.getStackOrderInfo()); infoTable.put(stackOrderLabel, options.getStackOrderInfo()); infoTable.put(swapDimsBox, options.getSwapDimensionsInfo()); infoTable.put(virtualBox, options.getVirtualInfo()); // rebuild dialog using FormLayout to organize things more nicely String cols = // first column "pref, 3dlu, pref:grow, " + // second column "10dlu, pref, " + // third column "10dlu, fill:150dlu"; String rows = // Stack viewing | Metadata viewing "pref, 3dlu, pref, 3dlu, pref, 3dlu, pref, " + // Dataset organization | Memory management "9dlu, pref, 3dlu, pref, 3dlu, pref, 3dlu, pref, 3dlu, pref, " + "3dlu, pref, " + // Color options | Split into separate windows "9dlu, pref, 3dlu, pref, 3dlu, pref, 3dlu, pref, 3dlu, pref"; // TODO: change "Merge channels into RGB" checkbox to // "Channel merging" choice with options: // "Default", "Merge channels" or "Separate channels" // TODO: change "Use virtual stack" and "Record modifications to virtual // stack" checkboxes to "Stack type" choice with options: // "Normal", "Virtual" or "Smart virtual" PanelBuilder builder = new PanelBuilder(new FormLayout(cols, rows)); CellConstraints cc = new CellConstraints(); // populate 1st column int row = 1; builder.addSeparator("Stack viewing", cc.xyw(1, row, 3)); row += 2; builder.add(stackFormatLabel, cc.xy(1, row)); builder.add(stackFormatChoice, cc.xy(3, row)); row += 2; builder.add(stackOrderLabel, cc.xy(1, row)); builder.add(stackOrderChoice, cc.xy(3, row)); row += 4; builder.addSeparator("Dataset organization", cc.xyw(1, row, 3)); row += 2; builder.add(groupFilesBox, xyw(cc, 1, row, 3)); row += 2; builder.add(ungroupFilesBox, xyw(cc, 1, row, 3)); row += 2; builder.add(swapDimsBox, xyw(cc, 1, row, 3)); row += 2; builder.add(openAllSeriesBox, xyw(cc, 1, row, 3)); row += 2; builder.add(concatenateBox, xyw(cc, 1, row, 3)); row += 2; builder.addSeparator("Color options", cc.xyw(1, row, 3)); row += 2; builder.add(mergeChannelsBox, xyw(cc, 1, row, 3)); row += 2; builder.add(colorizeBox, xyw(cc, 1, row, 3)); row += 2; builder.add(customColorizeBox, xyw(cc, 1, row, 3)); row += 2; builder.add(autoscaleBox, xyw(cc, 1, row, 3)); row += 2; // populate 2nd column row = 1; builder.addSeparator("Metadata viewing", cc.xy(5, row)); row += 2; builder.add(showMetadataBox, xyw(cc, 5, row, 1)); row += 2; builder.add(showOMEXMLBox, xyw(cc, 5, row, 1)); row += 2; builder.add(showROIsBox, xyw(cc, 5, row, 1)); row += 2; builder.addSeparator("Memory management", cc.xy(5, row)); row += 2; builder.add(virtualBox, xyw(cc, 5, row, 1)); row += 2; builder.add(recordBox, xyw(cc, 5, row, 1)); row += 2; builder.add(specifyRangesBox, xyw(cc, 5, row, 1)); row += 2; builder.add(cropBox, xyw(cc, 5, row, 1)); row += 4; builder.addSeparator("Split into separate windows", cc.xy(5, row)); row += 2; builder.add(splitCBox, xyw(cc, 5, row, 1)); row += 2; builder.add(splitZBox, xyw(cc, 5, row, 1)); row += 2; builder.add(splitTBox, xyw(cc, 5, row, 1)); //row += 4; // information section builder.addSeparator("Information", cc.xy(7, 1)); //row += 2; infoPane = new JEditorPane(); infoPane.setContentType("text/html"); infoPane.setEditable(false); infoPane.setText("<html>" + INFO_DEFAULT); builder.add(new JScrollPane(infoPane), cc.xywh(7, 3, 1, row)); //row += 2; gd.removeAll(); gd.add(builder.getPanel()); WindowTools.addScrollBars(gd); gd.setBackground(Color.white); // HACK: workaround for JPanel in a Dialog } /** * Convenience method for creating a left-aligned, * vertically centered cell constraints object. */ private CellConstraints xyw(CellConstraints cc, int x, int y, int w) { return cc.xyw(x, y, w, CellConstraints.LEFT, CellConstraints.CENTER); } /** Ensures that the options dialog has no mutually exclusive options. */ private void verifyOptions(Object src) { // record GUI state boolean autoscaleEnabled = autoscaleBox.isEnabled(); boolean colorizeEnabled = colorizeBox.isEnabled(); boolean concatenateEnabled = concatenateBox.isEnabled(); boolean cropEnabled = cropBox.isEnabled(); boolean customColorizeEnabled = customColorizeBox.isEnabled(); boolean groupFilesEnabled = groupFilesBox.isEnabled(); boolean ungroupFilesEnabled = ungroupFilesBox.isEnabled(); boolean mergeChannelsEnabled = mergeChannelsBox.isEnabled(); boolean openAllSeriesEnabled = openAllSeriesBox.isEnabled(); boolean recordEnabled = recordBox.isEnabled(); boolean showMetadataEnabled = showMetadataBox.isEnabled(); boolean showOMEXMLEnabled = showOMEXMLBox.isEnabled(); boolean specifyRangesEnabled = specifyRangesBox.isEnabled(); boolean splitZEnabled = splitZBox.isEnabled(); boolean splitTEnabled = splitTBox.isEnabled(); boolean splitCEnabled = splitCBox.isEnabled(); //boolean stackFormatEnabled = stackFormatChoice.isEnabled(); boolean stackOrderEnabled = stackOrderChoice.isEnabled(); boolean swapDimsEnabled = swapDimsBox.isEnabled(); boolean virtualEnabled = virtualBox.isEnabled(); boolean isAutoscale = autoscaleBox.getState(); boolean isColorize = colorizeBox.getState(); boolean isConcatenate = concatenateBox.getState(); boolean isCrop = cropBox.getState(); boolean isCustomColorize = customColorizeBox.getState(); boolean isGroupFiles = groupFilesBox.getState(); boolean isUngroupFiles = ungroupFilesBox.getState(); boolean isMergeChannels = mergeChannelsBox.getState(); boolean isOpenAllSeries = openAllSeriesBox.getState(); boolean isRecord = recordBox.getState(); boolean isShowMetadata = showMetadataBox.getState(); boolean isShowOMEXML = showOMEXMLBox.getState(); boolean isSpecifyRanges = specifyRangesBox.getState(); boolean isSplitZ = splitZBox.getState(); boolean isSplitT = splitTBox.getState(); boolean isSplitC = splitCBox.getState(); String stackFormatValue = stackFormatChoice.getSelectedItem(); boolean isStackNone = stackFormatValue.equals(ImporterOptions.VIEW_NONE); boolean isStackStandard = stackFormatValue.equals(ImporterOptions.VIEW_STANDARD); boolean isStackHyperstack = stackFormatValue.equals(ImporterOptions.VIEW_HYPERSTACK); boolean isStackBrowser = stackFormatValue.equals(ImporterOptions.VIEW_BROWSER); boolean isStackVisBio = stackFormatValue.equals(ImporterOptions.VIEW_VISBIO); boolean isStackImage5D = stackFormatValue.equals(ImporterOptions.VIEW_IMAGE_5D); boolean isStackView5D = stackFormatValue.equals(ImporterOptions.VIEW_VIEW_5D); String stackOrderValue = stackOrderChoice.getSelectedItem(); boolean isSwap = swapDimsBox.getState(); boolean isVirtual = virtualBox.getState(); // toggle availability of each option based on state of earlier options // NB: The order the options are examined here defines their order of // precedence. This ordering is necessary because it affects which // component states are capable of graying out other components. // For example, we want to disable autoscaleBox when virtualBox is checked, // so the virtualBox logic must appear before the autoscaleBox logic. // To make it more intuitive for the user, the order of precedence should // match the component layout from left to right, top to bottom, according // to subsection. // == Stack viewing == // stackOrderChoice stackOrderEnabled = isStackStandard || isStackVisBio; if (src == stackFormatChoice) { if (isStackHyperstack || isStackBrowser || isStackImage5D) { stackOrderValue = ImporterOptions.ORDER_XYCZT; } else if (isStackView5D) stackOrderValue = ImporterOptions.ORDER_XYZCT; else stackOrderValue = ImporterOptions.ORDER_DEFAULT; } // == Metadata viewing == // showMetadataBox showMetadataEnabled = !isStackNone; if (!showMetadataEnabled) isShowMetadata = true; // showOMEXMLBox // NB: no other options affect showOMEXMLBox // == Dataset organization == // groupFilesBox if (src == stackFormatChoice && isStackBrowser) isGroupFiles = true; // ungroupFilesBox // NB: no other options affect ungroupFilesBox // swapDimsBox // NB: no other options affect swapDimsBox // openAllSeriesBox // NB: no other options affect openAllSeriesBox // concatenateBox // NB: no other options affect concatenateBox // == Memory management == // virtualBox virtualEnabled = !isStackNone && !isStackImage5D && !isStackView5D; if (!virtualEnabled) isVirtual = false; else if (src == stackFormatChoice && isStackBrowser) isVirtual = true; // recordBox recordEnabled = isVirtual; if (!recordEnabled) isRecord = false; // specifyRangesBox specifyRangesEnabled = !isStackNone && !isVirtual; if (!specifyRangesEnabled) isSpecifyRanges = false; // cropBox cropEnabled = !isStackNone && !isVirtual; if (!cropEnabled) isCrop = false; // == Color options == // mergeChannelsBox mergeChannelsEnabled = !isStackImage5D; if (!mergeChannelsEnabled) isMergeChannels = false; // colorizeBox colorizeEnabled = !isMergeChannels && !isStackBrowser && !isStackImage5D && !isStackView5D && !isCustomColorize; if (!colorizeEnabled) isColorize = false; // customColorizeBox customColorizeEnabled = !isMergeChannels && !isStackBrowser && !isStackImage5D && !isStackView5D && !isColorize; if (!customColorizeEnabled) isCustomColorize = false; // autoscaleBox autoscaleEnabled = !isVirtual; if (!autoscaleEnabled) isAutoscale = false; // == Split into separate windows == boolean splitEnabled = !isStackNone && !isStackBrowser && !isStackVisBio && !isStackImage5D && !isStackView5D && !isVirtual; // TODO: make splitting work with Data Browser & virtual stacks // splitCBox splitCEnabled = splitEnabled && !isMergeChannels; if (!splitCEnabled) isSplitC = false; // splitZBox splitZEnabled = splitEnabled; if (!splitZEnabled) isSplitZ = false; // splitTBox splitTEnabled = splitEnabled; if (!splitTEnabled) isSplitT = false; // update state of each option, in case anything changed autoscaleBox.setEnabled(autoscaleEnabled); colorizeBox.setEnabled(colorizeEnabled); concatenateBox.setEnabled(concatenateEnabled); cropBox.setEnabled(cropEnabled); customColorizeBox.setEnabled(customColorizeEnabled); groupFilesBox.setEnabled(groupFilesEnabled); ungroupFilesBox.setEnabled(ungroupFilesEnabled); mergeChannelsBox.setEnabled(mergeChannelsEnabled); openAllSeriesBox.setEnabled(openAllSeriesEnabled); recordBox.setEnabled(recordEnabled); showMetadataBox.setEnabled(showMetadataEnabled); showOMEXMLBox.setEnabled(showOMEXMLEnabled); specifyRangesBox.setEnabled(specifyRangesEnabled); splitZBox.setEnabled(splitZEnabled); splitTBox.setEnabled(splitTEnabled); splitCBox.setEnabled(splitCEnabled); //stackFormatChoice.setEnabled(stackFormatEnabled); stackOrderChoice.setEnabled(stackOrderEnabled); swapDimsBox.setEnabled(swapDimsEnabled); virtualBox.setEnabled(virtualEnabled); autoscaleBox.setState(isAutoscale); colorizeBox.setState(isColorize); concatenateBox.setState(isConcatenate); cropBox.setState(isCrop); customColorizeBox.setState(isCustomColorize); groupFilesBox.setState(isGroupFiles); ungroupFilesBox.setState(isUngroupFiles); mergeChannelsBox.setState(isMergeChannels); openAllSeriesBox.setState(isOpenAllSeries); recordBox.setState(isRecord); showMetadataBox.setState(isShowMetadata); showOMEXMLBox.setState(isShowOMEXML); specifyRangesBox.setState(isSpecifyRanges); splitZBox.setState(isSplitZ); splitTBox.setState(isSplitT); splitCBox.setState(isSplitC); //stackFormatChoice.select(stackFormatValue); stackOrderChoice.select(stackOrderValue); swapDimsBox.setState(isSwap); virtualBox.setState(isVirtual); if (IS_GLITCHED) { // HACK - work around a Mac OS X bug where GUI components do not update // list of affected components Component[] c = { autoscaleBox, colorizeBox, concatenateBox, cropBox, customColorizeBox, groupFilesBox, ungroupFilesBox, mergeChannelsBox, openAllSeriesBox, recordBox, showMetadataBox, showOMEXMLBox, specifyRangesBox, splitZBox, splitTBox, splitCBox, stackFormatChoice, stackOrderChoice, swapDimsBox, virtualBox }; // identify currently focused component Component focused = null; for (int i=0; i<c.length; i++) { if (c[i].isFocusOwner()) focused = c[i]; } // temporarily disable focus events for (int i=0; i<c.length; i++) c[i].removeFocusListener(this); // cycle through focus on all components for (int i=0; i<c.length; i++) c[i].requestFocusInWindow(); // clear the focus globally KeyboardFocusManager kfm = KeyboardFocusManager.getCurrentKeyboardFocusManager(); kfm.clearGlobalFocusOwner(); sleep(100); // doesn't work if this value is too small // refocus the originally focused component if (focused != null) focused.requestFocusInWindow(); // reenable focus events for (int i=0; i<c.length; i++) c[i].addFocusListener(this); } } }
package org.apache.commons.lang.enum; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Abstract superclass for type-safe enums. * <p> * One feature of the C programming language lacking in Java is enumerations. The * C implementation based on ints was poor and open to abuse. The original Java * recommendation and most of the JDK also uses int constants. It has been recognised * however that a more robust type-safe class-based solution can be designed. This * class follows the basic Java type-safe enumeration pattern. * <p> * <em>NOTE:</em>Due to the way in which Java ClassLoaders work, comparing Enum objects * should always be done using the equals() method, not ==. The equals() method will * try == first so in most cases the effect is the same. * <p> * To use this class, it must be subclassed. For example: * * <pre> * public final class ColorEnum extends Enum { * public static final ColorEnum RED = new ColorEnum("Red"); * public static final ColorEnum GREEN = new ColorEnum("Green"); * public static final ColorEnum BLUE = new ColorEnum("Blue"); * * private ColorEnum(String color) { * super(color); * } * * public static ColorEnum getEnum(String color) { * return (ColorEnum) getEnum(ColorEnum.class, color); * } * * public static Map getEnumMap() { * return getEnumMap(ColorEnum.class); * } * * public static List getEnumList() { * return getEnumList(ColorEnum.class); * } * * public static Iterator iterator() { * return iterator(ColorEnum.class); * } * } * </pre> * <p> * As shown, each enum has a name. This can be accessed using <code>getName</code>. * <p> * The <code>getEnum</code> and <code>iterator</code> methods are recommended. * Unfortunately, Java restrictions require these to be coded as shown in each subclass. * An alternative choice is to use the {@link EnumUtils} class. * <p> * <em>NOTE:</em> This class originated in the Jakarta Avalon project. * </p> * * @author <a href="mailto:scolebourne@joda.org">Stephen Colebourne</a> * @version $Id: Enum.java,v 1.4 2002/11/02 13:16:30 scolebourne Exp $ */ public abstract class Enum implements Comparable, Serializable { /** * An empty map, as JDK1.2 didn't have an empty map */ private static final Map EMPTY_MAP = Collections.unmodifiableMap(new HashMap()); /** * Map, key of class name, value of Entry. */ private static final Map cEnumClasses = new HashMap(); /** * The string representation of the Enum. */ private final String iName; /** * Enable the iterator to retain the source code order */ private static class Entry { /** Map of Enum name to Enum */ final Map map = new HashMap(50); /** List of Enums in source code order */ final List list = new ArrayList(25); /** * Restrictive constructor */ private Entry() { } } protected Enum(String name) { super(); if (name == null || name.length() == 0) { throw new IllegalArgumentException("The Enum name must not be empty"); } iName = name; Entry entry = (Entry) cEnumClasses.get(getClass().getName()); if (entry == null) { entry = new Entry(); cEnumClasses.put(getClass().getName(), entry); } if (entry.map.containsKey(name)) { throw new IllegalArgumentException("The Enum name must be unique, '" + name + "' has already been added"); } entry.map.put(name, this); entry.list.add(this); } protected Object readResolve() { return Enum.getEnum(getClass(), getName()); } protected static Enum getEnum(Class enumClass, String name) { if (enumClass == null) { throw new IllegalArgumentException("The Enum Class must not be null"); } Entry entry = (Entry) cEnumClasses.get(enumClass.getName()); if (entry == null) { return null; } return (Enum) entry.map.get(name); } protected static Map getEnumMap(Class enumClass) { if (enumClass == null) { throw new IllegalArgumentException("The Enum Class must not be null"); } if (Enum.class.isAssignableFrom(enumClass) == false) { throw new IllegalArgumentException("The Class must be a subclass of Enum"); } Entry entry = (Entry) cEnumClasses.get(enumClass.getName()); if (entry == null) { return EMPTY_MAP; } return Collections.unmodifiableMap(entry.map); } protected static List getEnumList(Class enumClass) { if (enumClass == null) { throw new IllegalArgumentException("The Enum Class must not be null"); } if (Enum.class.isAssignableFrom(enumClass) == false) { throw new IllegalArgumentException("The Class must be a subclass of Enum"); } Entry entry = (Entry) cEnumClasses.get(enumClass.getName()); if (entry == null) { return Collections.EMPTY_LIST; } return Collections.unmodifiableList(entry.list); } protected static Iterator iterator(Class enumClass) { return Enum.getEnumList(enumClass).iterator(); } /** * Retrieve the name of this Enum item, set in the constructor. * * @return the <code>String</code> name of this Enum item */ public final String getName() { return iName; } /** * Tests for equality. Two Enum objects are considered equal * if they have the same class names and the same names. * Identity is tested for first, so this method usually runs fast. * * @param other the other object to compare for equality * @return true if the Enums are equal */ public final boolean equals(Object other) { if (other == this) { return true; } else if (other == null) { return false; } else if (other.getClass() == this.getClass()) { // shouldn't happen, but... return iName.equals(((Enum) other).iName); } else if (other.getClass().getName().equals(this.getClass().getName())) { // different classloaders try { // try to avoid reflection return iName.equals(((Enum) other).iName); } catch (ClassCastException ex) { // use reflection try { Method mth = other.getClass().getMethod("getName", null); String name = (String) mth.invoke(other, null); return iName.equals(name); } catch (NoSuchMethodException ex2) { // ignore - should never happen } catch (IllegalAccessException ex2) { // ignore - should never happen } catch (InvocationTargetException ex2) { // ignore - should never happen } return false; } } else { return false; } } /** * Returns a suitable hashCode for the enumeration. * * @return a hashcode based on the name */ public final int hashCode() { return 7 + iName.hashCode(); } /** * Tests for order. The default ordering is alphabetic by name, but this * can be overridden by subclasses. * * @see java.lang.Comparable#compareTo(Object) * @param other the other object to compare to * @return -ve if this is less than the other object, +ve if greater than, 0 of equal * @throws ClassCastException if other is not an Enum * @throws NullPointerException if other is null */ public int compareTo(Object other) { return iName.compareTo(((Enum) other).iName); } /** * Human readable description of this Enum item. For use when debugging. * * @return String in the form <code>type[name]</code>, for example: * <code>Color[Red]</code>. Note that the package name is stripped from * the type name. */ public String toString() { String shortName = getClass().getName(); int pos = shortName.lastIndexOf('.'); if (pos != -1) { shortName = shortName.substring(pos + 1); } return shortName + "[" + getName() + "]"; } }
package org.jdesktop.swingx; import java.awt.Component; import java.awt.HeadlessException; import java.util.prefs.Preferences; import javax.swing.JDialog; import org.jdesktop.swingx.plaf.JXTipOfTheDayAddon; import org.jdesktop.swingx.plaf.LookAndFeelAddons; import org.jdesktop.swingx.plaf.TipOfTheDayUI; import org.jdesktop.swingx.tips.DefaultTipOfTheDayModel; import org.jdesktop.swingx.tips.TipOfTheDayModel; import org.jdesktop.swingx.tips.TipOfTheDayModel.Tip; /** * Provides the "Tip of The Day" pane and dialog.<br> * * <p> * Tips are retrieved from the {@link org.jdesktop.swingx.tips.TipOfTheDayModel}. * In the most common usage, a tip (as returned by * {@link org.jdesktop.swingx.tips.TipOfTheDayModel.Tip#getTip()}) is just a * <code>String</code>. However, the return type of this method is actually * <code>Object</code>. Its interpretation depends on its type: * <dl compact> * <dt>Component * <dd>The <code>Component</code> is displayed in the dialog. * <dt>Icon * <dd>The <code>Icon</code> is wrapped in a <code>JLabel</code> and * displayed in the dialog. * <dt>others * <dd>The object is converted to a <code>String</code> by calling its * <code>toString</code> method. The result is wrapped in a * <code>JEditorPane</code> or <code>JTextArea</code> and displayed. * </dl> * * <p> * <code>JXTipOfTheDay<code> finds its tips in its {@link org.jdesktop.swingx.tips.TipOfTheDayModel}. * Such model can be programmatically built using {@link org.jdesktop.swingx.tips.DefaultTipOfTheDayModel} * and {@link org.jdesktop.swingx.tips.DefaultTip} but * the {@link org.jdesktop.swingx.tips.TipLoader} provides a convenient method to * build a model and its tips from a {@link java.util.Properties} object. * * <p> * Example: * <p> * Let's consider a file <i>tips.properties</i> with the following content: * <pre> * <code> * tip.1.description=This is the first time! Plain text. * tip.2.description=&lt;html&gt;This is &lt;b&gt;another tip&lt;/b&gt;, it uses HTML! * tip.3.description=A third one * </code> * </pre> * * To load and display the tips: * * <pre> * <code> * Properties tips = new Properties(); * tips.load(new FileInputStream("tips.properties")); * * TipOfTheDayModel model = TipLoader.load(tips); * JXTipOfTheDay totd = new JXTipOfTheDay(model); * * totd.showDialog(someParentComponent); * </code> * </pre> * * <p> * Additionally, <code>JXTipOfTheDay</code> features an option enabling the end-user * to choose to not display the "Tip Of The Day" dialog. This user choice can be stored * in the user {@link java.util.prefs.Preferences} but <code>JXTipOfTheDay</code> also * supports custom storage through the {@link org.jdesktop.swingx.JXTipOfTheDay.ShowOnStartupChoice} interface. * * <pre> * <code> * Preferences userPreferences = Preferences.userRoot().node("myApp"); * totd.showDialog(someParentComponent, userPreferences); * </code> * </pre> * In this code, the first time showDialog is called, the dialog will be made * visible and the user will have the choice to not display it again in the future * (usually this is controlled by a checkbox "Show tips on startup"). If the user * unchecks the option, subsequent calls to showDialog will not display the dialog. * As the choice is saved in the user Preferences, it will persist when the application is relaunched. * * @see org.jdesktop.swingx.tips.TipLoader * @see org.jdesktop.swingx.tips.TipOfTheDayModel * @see org.jdesktop.swingx.tips.TipOfTheDayModel.Tip * @see #showDialog(Component, Preferences) * @see #showDialog(Component, ShowOnStartupChoice) * * @author <a href="mailto:fred@L2FProd.com">Frederic Lavigne</a> */ public class JXTipOfTheDay extends JXPanel { /** * JXTipOfTheDay pluggable UI key <i>swingx/TipOfTheDayUI</i> */ public final static String uiClassID = "swingx/TipOfTheDayUI"; // ensure at least the default ui is registered static { LookAndFeelAddons.contribute(new JXTipOfTheDayAddon()); } /** * Key used to store the status of the "Show tip on startup" checkbox" */ public static final String PREFERENCE_KEY = "ShowTipOnStartup"; /** * Used when generating PropertyChangeEvents for the "currentTip" property */ public static final String CURRENT_TIP_CHANGED_KEY = "currentTip"; private TipOfTheDayModel model; private int currentTip = 0; /** * Constructs a new <code>JXTipOfTheDay</code> with an empty * TipOfTheDayModel */ public JXTipOfTheDay() { this(new DefaultTipOfTheDayModel(new Tip[0])); } /** * Constructs a new <code>JXTipOfTheDay</code> showing tips from the given * TipOfTheDayModel. * * @param model */ public JXTipOfTheDay(TipOfTheDayModel model) { this.model = model; updateUI(); } /** * Notification from the <code>UIManager</code> that the L&F has changed. * Replaces the current UI object with the latest version from the * <code>UIManager</code>. * * @see javax.swing.JComponent#updateUI */ public void updateUI() { setUI((TipOfTheDayUI)LookAndFeelAddons.getUI(this, TipOfTheDayUI.class)); } /** * Sets the L&F object that renders this component. * * @param ui * the <code>TipOfTheDayUI</code> L&F object * @see javax.swing.UIDefaults#getUI * * @beaninfo bound: true hidden: true description: The UI object that * implements the taskpane group's LookAndFeel. */ public void setUI(TipOfTheDayUI ui) { super.setUI(ui); } /** * Gets the UI object which implements the L&F for this component. * * @return the TipOfTheDayUI object that implements the TipOfTheDayUI L&F */ public TipOfTheDayUI getUI() { return (TipOfTheDayUI)ui; } /** * Returns the name of the L&F class that renders this component. * * @return the string {@link #uiClassID} * @see javax.swing.JComponent#getUIClassID * @see javax.swing.UIDefaults#getUI */ public String getUIClassID() { return uiClassID; } public TipOfTheDayModel getModel() { return model; } public void setModel(TipOfTheDayModel model) { if (model == null) { throw new IllegalArgumentException("model can not be null"); } TipOfTheDayModel old = this.model; this.model = model; firePropertyChange("model", old, model); } public int getCurrentTip() { return currentTip; } public void setCurrentTip(int currentTip) { if (currentTip < 0 || currentTip >= getModel().getTipCount()) { throw new IllegalArgumentException( "Current tip must be within the bounds [0, " + getModel().getTipCount() + "["); } int oldTip = this.currentTip; this.currentTip = currentTip; firePropertyChange(CURRENT_TIP_CHANGED_KEY, oldTip, currentTip); } /** * Shows the next tip in the list. It cycles the tip list. */ public void nextTip() { int count = getModel().getTipCount(); if (count == 0) { return; } int nextTip = currentTip + 1; if (nextTip >= count) { nextTip = 0; } setCurrentTip(nextTip); } /** * Shows the previous tip in the list. It cycles the tip list. */ public void previousTip() { int count = getModel().getTipCount(); if (count == 0) { return; } int previousTip = currentTip - 1; if (previousTip < 0) { previousTip = count - 1; } setCurrentTip(previousTip); } /** * Pops up a "Tip of the day" dialog. * * @param parentComponent * @exception HeadlessException * if GraphicsEnvironment.isHeadless() returns true. * @see java.awt.GraphicsEnvironment#isHeadless */ public void showDialog(Component parentComponent) throws HeadlessException { showDialog(parentComponent, (ShowOnStartupChoice)null); } public boolean showDialog(Component parentComponent, Preferences showOnStartupPref) throws HeadlessException { return showDialog(parentComponent, showOnStartupPref, false); } public boolean showDialog(Component parentComponent, final Preferences showOnStartupPref, boolean force) throws HeadlessException { if (showOnStartupPref == null) { throw new IllegalArgumentException( "Preferences can not be null"); } ShowOnStartupChoice store = new ShowOnStartupChoice() { public boolean isShowingOnStartup() { return showOnStartupPref.getBoolean(PREFERENCE_KEY, true); } public void setShowingOnStartup(boolean showOnStartup) { // only save the choice if it is negative if (!showOnStartup) { showOnStartupPref.putBoolean(PREFERENCE_KEY, showOnStartup); } } }; return showDialog(parentComponent, store, force); } /** * Pops up a "Tip of the day" dialog. * * If <code>choice</code> is not null, the method first checks if * {@link ShowOnStartupChoice#isShowingOnStartup()} is true before showing the * dialog. * * Additionally, it saves the state of the "Show tips on startup" checkbox * using the given {@link ShowOnStartupChoice} object. * * @param parentComponent * @param choice * @exception HeadlessException * if GraphicsEnvironment.isHeadless() returns true. * @see java.awt.GraphicsEnvironment#isHeadless * @return true if the user chooses to see the tips again, false otherwise. */ public boolean showDialog(Component parentComponent, ShowOnStartupChoice choice) { return showDialog(parentComponent, choice, false); } /** * Pops up a "Tip of the day" dialog. * * If <code>choice</code> is not null, the method first checks if * <code>force</code> is true or if * {@link ShowOnStartupChoice#isShowingOnStartup()} is true before showing the * dialog. * * Additionally, it saves the state of the "Show tips on startup" checkbox * using the given {@link ShowOnStartupChoice} object. * * @param parentComponent * @param choice * @param force * if true, the dialog is displayed even if * {@link ShowOnStartupChoice#isShowingOnStartup()} is false * @exception HeadlessException * if GraphicsEnvironment.isHeadless() returns true. * @see java.awt.GraphicsEnvironment#isHeadless * @return true if the user chooses to see the tips again, false otherwise. */ public boolean showDialog(Component parentComponent, ShowOnStartupChoice choice, boolean force) { if (choice == null) { JDialog dialog = createDialog(parentComponent, choice); dialog.setVisible(true); dialog.dispose(); return true; } else if (force || choice.isShowingOnStartup()) { JDialog dialog = createDialog(parentComponent, choice); dialog.setVisible(true); dialog.dispose(); return choice.isShowingOnStartup(); } else { return false; } } /** * @param showOnStartupPref * @return true if the key named "ShowTipOnStartup" is not set to false */ public static boolean isShowingOnStartup(Preferences showOnStartupPref) { return showOnStartupPref.getBoolean(PREFERENCE_KEY, true); } /** * Removes the value set for "ShowTipOnStartup" in the given Preferences to * ensure the dialog shown by a later call to * {@link #showDialog(Component, Preferences)} will be visible to the user. * * @param showOnStartupPref */ public static void forceShowOnStartup(Preferences showOnStartupPref) { showOnStartupPref.remove(PREFERENCE_KEY); } /** * Calls * {@link TipOfTheDayUI#createDialog(Component, JXTipOfTheDay.ShowOnStartupChoice)}. * * This method can be overriden in order to control things such as the * placement of the dialog or its title. * * @param parentComponent * @param choice * @return a JDialog to show this TipOfTheDay pane */ protected JDialog createDialog(Component parentComponent, ShowOnStartupChoice choice) { return getUI().createDialog(parentComponent, choice); } /** * Used in conjunction with the * {@link JXTipOfTheDay#showDialog(Component, ShowOnStartupChoice)} to save the * "Show tips on startup" choice. */ public static interface ShowOnStartupChoice { /** * Persists the user choice * @param showOnStartup the user choice */ void setShowingOnStartup(boolean showOnStartup); /** * @return the previously stored user choice */ boolean isShowingOnStartup(); } }
package org.orbeon.oxf.util; import org.apache.log4j.*; import org.apache.log4j.xml.DOMConfigurator; import org.orbeon.oxf.pipeline.api.PipelineContext; import org.orbeon.oxf.processor.DOMSerializer; import org.orbeon.oxf.processor.Processor; import org.orbeon.oxf.processor.ProcessorImpl; import org.orbeon.oxf.resources.OXFProperties; public class LoggerFactory { public static final String LOG4J_DOM_CONFIG_PROPERTY = "oxf.log4j-config"; public static final String LOG4J_DOM_CONFIG_PROPERTY_OLD = "oxf.servlet.log4j"; static { // 11-22-2004 d : Current log4j tries to load a default config. This is // why we are seeing a message about a log4j.properties being // loaded from the Axis jar. // Since this is't a behaviour we want we hack around it by // specifying a file that doesn't exist. System.setProperty( "log4j.configuration", "-there-aint-no-such-file-" ); } private static final Logger logger = LoggerFactory.createLogger(LoggerFactory.class); public static Logger createLogger(Class clazz) { return Logger.getLogger(clazz.getName()); } /* * Init basic config until resource manager is setup. */ public static void initBasicLogger() { LogManager.resetConfiguration(); Logger root = Logger.getRootLogger(); root.setLevel(Level.INFO); root.addAppender(new ConsoleAppender(new PatternLayout(PatternLayout.DEFAULT_CONVERSION_PATTERN), ConsoleAppender.SYSTEM_ERR)); } /** * Init log4j. Needs Presentation Server Properties system up and running. */ public static void initLogger() { try { // Accept both xs:string and xs:anyURI types String log4jConfigURL = OXFProperties.instance().getPropertySet().getStringOrURIAsString(LOG4J_DOM_CONFIG_PROPERTY); if (log4jConfigURL == null) log4jConfigURL = OXFProperties.instance().getPropertySet().getStringOrURIAsString(LOG4J_DOM_CONFIG_PROPERTY_OLD); if (log4jConfigURL != null) { Processor url = PipelineUtils.createURLGenerator(log4jConfigURL); DOMSerializer dom = new DOMSerializer(); PipelineUtils.connect(url, ProcessorImpl.OUTPUT_DATA, dom, ProcessorImpl.INPUT_DATA); PipelineContext ctx = new PipelineContext(); dom.reset(ctx); dom.start(ctx); Object o = dom.getW3CDocument(ctx).getDocumentElement(); DOMConfigurator.configure( ( org.w3c.dom.Element )o ); } else { logger.info("Property " + LOG4J_DOM_CONFIG_PROPERTY + " not set. Skipping logging initialization."); } } catch (Throwable e) { logger.error("Cannot load Log4J configuration. Skipping logging initialization", e); } } }
package org.orbeon.oxf.xforms; import org.apache.log4j.Logger; import org.dom4j.Document; import org.dom4j.Element; import org.orbeon.oxf.common.OXFException; import org.orbeon.oxf.common.ValidationException; import org.orbeon.oxf.pipeline.api.ExternalContext; import org.orbeon.oxf.pipeline.api.PipelineContext; import org.orbeon.oxf.processor.ProcessorImpl; import org.orbeon.oxf.resources.URLFactory; import org.orbeon.oxf.util.*; import org.orbeon.oxf.xforms.event.*; import org.orbeon.oxf.xforms.event.events.*; import org.orbeon.oxf.xforms.function.xxforms.XXFormsExtractDocument; import org.orbeon.oxf.xforms.submission.BaseSubmission; import org.orbeon.oxf.xforms.submission.OptimizedSubmission; import org.orbeon.oxf.xforms.submission.XFormsModelSubmission; import org.orbeon.oxf.xforms.xbl.XBLBindings; import org.orbeon.oxf.xforms.xbl.XBLContainer; import org.orbeon.oxf.xml.TransformerUtils; import org.orbeon.oxf.xml.dom4j.Dom4jUtils; import org.orbeon.oxf.xml.dom4j.ExtendedLocationData; import org.orbeon.oxf.xml.dom4j.LocationData; import org.orbeon.saxon.om.DocumentInfo; import org.orbeon.saxon.om.Item; import org.orbeon.saxon.om.NodeInfo; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.util.*; /** * Represents an XForms model. */ public class XFormsModel implements XFormsEventTarget, XFormsEventObserver, XFormsObjectResolver { public static final String LOGGING_CATEGORY = "model"; public static final Logger logger = LoggerFactory.createLogger(XFormsModel.class); public final IndentedLogger indentedLogger; private final Document modelDocument; // Model attributes private final String staticId; private String prefixedId; // not final because can change if model within repeat iteration private String effectiveId; // not final because can change if model within repeat iteration // Instances private final List<String> instanceIds; private final List<XFormsInstance> instances; private final Map<String, XFormsInstance> instancesMap; // Submissions private final Map<String, XFormsModelSubmission> submissions; // Binds private final XFormsModelBinds binds; private final boolean mustBindValidate; // Schema validation private XFormsModelSchemaValidator schemaValidator; private boolean mustSchemaValidate; // Container private final XBLContainer container; private final XFormsContextStack contextStack; // context stack for evaluation, used by binds, submissions, event handlers // Containing document private final XFormsContainingDocument containingDocument; public XFormsModel(XBLContainer container, String effectiveId, Document modelDocument) { // Set container this.container = container; this.containingDocument = container.getContainingDocument(); this.indentedLogger = containingDocument.getIndentedLogger(LOGGING_CATEGORY); // Remember document this.modelDocument = modelDocument; // Basic check trying to make sure this is an XForms model // TODO: should rather use schema here or when obtaining document passed to this constructor final Element modelElement = modelDocument.getRootElement(); final String rootNamespaceURI = modelElement.getNamespaceURI(); if (!rootNamespaceURI.equals(XFormsConstants.XFORMS_NAMESPACE_URI)) throw new ValidationException("Root element of XForms model must be in namespace '" + XFormsConstants.XFORMS_NAMESPACE_URI + "'. Found instead: '" + rootNamespaceURI + "'", (LocationData) modelElement.getData()); staticId = modelElement.attributeValue("id"); this.effectiveId = effectiveId; // Extract list of instances ids { final List<Element> instanceContainers = Dom4jUtils.elements(modelElement, XFormsConstants.XFORMS_INSTANCE_QNAME); if (instanceContainers.isEmpty()) { // No instance in this model instanceIds = Collections.emptyList(); instances = Collections.emptyList(); instancesMap = Collections.emptyMap(); } else { // At least one instance in this model instanceIds = new ArrayList<String>(instanceContainers.size()); for (Element instanceContainer: instanceContainers) { final String instanceId = XFormsInstance.getInstanceStaticId(instanceContainer); instanceIds.add(instanceId); } instances = Arrays.asList(new XFormsInstance[instanceIds.size()]); instancesMap = new HashMap<String, XFormsInstance>(instanceIds.size()); } } // Get <xforms:submission> elements (may be missing) { final List<Element> submissionElements = Dom4jUtils.elements(modelElement, XFormsConstants.XFORMS_SUBMISSION_QNAME); if (submissionElements.isEmpty()) { // No submission in this model submissions = Collections.emptyMap(); } else { // At least one submission in this model submissions = new HashMap<String, XFormsModelSubmission>(); for (Element submissionElement: submissionElements) { final String submissionId = submissionElement.attributeValue("id"); submissions.put(submissionId, new XFormsModelSubmission(this.container, submissionId, submissionElement, this)); } } } // Create binds object binds = XFormsModelBinds.create(this); mustBindValidate = binds != null; // Create context stack this.contextStack = new XFormsContextStack(this); } public void updateEffectiveId(String effectiveId) { this.effectiveId = effectiveId; // Update effective ids of all nested instances for (XFormsInstance currentInstance: instances) { // NOTE: we pass the new model id, not the instance id currentInstance.updateModelEffectiveId(effectiveId); } } public String getPrefixedId() { if (prefixedId == null) { prefixedId = XFormsUtils.getPrefixedId(effectiveId); } return prefixedId; } public IndentedLogger getIndentedLogger() { return indentedLogger; } public XFormsContextStack getContextStack() { return contextStack; } public XBLContainer getXBLContainer() { return container; } public XBLContainer getXBLContainer(XFormsContainingDocument containingDocument) { return getXBLContainer(); } public XFormsContainingDocument getContainingDocument() { return containingDocument; } public Document getModelDocument() { return modelDocument; } /** * Get object with the id specified. */ public Object getObjectByEffectiveId(String effectiveId) { // If prefixes or suffixes don't match, object can't be found here if (!getXBLContainer().getFullPrefix().equals(XFormsUtils.getEffectiveIdPrefix(effectiveId)) || !XFormsUtils.getEffectiveIdSuffix(getXBLContainer().getEffectiveId()).equals(XFormsUtils.getEffectiveIdSuffix(effectiveId))) { return null; } // Find by static id return resolveObjectById(null, XFormsUtils.getStaticIdFromId(effectiveId), null); } /** * Resolve an object. This optionally depends on a source, and involves resolving whether the source is within a * repeat or a component. * * @param sourceEffectiveId effective id of the source, or null * @param targetStaticId static id of the target * @param contextItem context item, or null (used for bind resolution only) * @return object, or null if not found */ public Object resolveObjectById(String sourceEffectiveId, String targetStaticId, Item contextItem) { if (targetStaticId.indexOf(XFormsConstants.COMPONENT_SEPARATOR) != -1 || targetStaticId.indexOf(XFormsConstants.REPEAT_HIERARCHY_SEPARATOR_1) != -1) throw new OXFException("Target id must be static id: " + targetStaticId); // Check this id if (targetStaticId.equals(getId())) return this; // Search instances final XFormsInstance instance = instancesMap.get(targetStaticId); if (instance != null) return instance; // Search submissions if (submissions != null) { final XFormsModelSubmission resultSubmission = submissions.get(targetStaticId); if (resultSubmission != null) return resultSubmission; } // Search binds if (binds != null) { final XFormsModelBinds.Bind bind = binds.resolveBind(targetStaticId, contextItem); if (bind != null) return bind; } return null; } /** * Return the default instance for this model, i.e. the first instance. Return null if there is * no instance in this model. * * @return XFormsInstance or null */ public XFormsInstance getDefaultInstance() { return instances.size() > 0 ? instances.get(0) : null; } /** * Return all XFormsInstance objects for this model, in the order they appear in the model. */ public List<XFormsInstance> getInstances() { return instances; } /** * Return the XFormsInstance with given id, null if not found. */ public XFormsInstance getInstance(String instanceStaticId) { return instancesMap.get(instanceStaticId); } /** * Return the XFormsInstance object containing the given node. */ public XFormsInstance getInstanceForNode(NodeInfo nodeInfo) { final DocumentInfo documentInfo = nodeInfo.getDocumentRoot(); for (XFormsInstance currentInstance: instances) { if (currentInstance.getDocumentInfo().isSameNodeInfo(documentInfo)) return currentInstance; } return null; } /** * Set an instance document for this model. There may be multiple instance documents. Each instance document may * have an associated id that identifies it. */ public XFormsInstance setInstanceDocument(Object instanceDocument, String modelEffectiveId, String instanceStaticId, String instanceSourceURI, String username, String password, boolean cached, long timeToLive, String validation, boolean handleXInclude) { // Prepare and set instance final int instancePosition = instanceIds.indexOf(instanceStaticId); final XFormsInstance newInstance; { if (instanceDocument instanceof Document) { newInstance = new XFormsInstance(modelEffectiveId, instanceStaticId, (Document) instanceDocument, instanceSourceURI, null, username, password, cached, timeToLive, validation, handleXInclude, XFormsProperties.isExposeXPathTypes(containingDocument)); } else if (instanceDocument instanceof DocumentInfo) { newInstance = new ReadonlyXFormsInstance(modelEffectiveId, instanceStaticId, (DocumentInfo) instanceDocument, instanceSourceURI, null, username, password, cached, timeToLive, validation, handleXInclude, XFormsProperties.isExposeXPathTypes(containingDocument)); } else { throw new OXFException("Invalid type for instance document: " + instanceDocument.getClass().getName()); } } instances.set(instancePosition, newInstance); // Create mapping instance id -> instance if (instanceStaticId != null) instancesMap.put(instanceStaticId, newInstance); return newInstance; } /** * Set an instance. The id of the instance must exist in the model. * * @param instance XFormsInstance to set * @param replaced whether this is an instance replacement (as result of a submission) */ private void setInstance(XFormsInstance instance, boolean replaced) { // Mark the instance as replaced if needed instance.setReplaced(replaced); // Prepare and set instance final String instanceId = instance.getId();// use static id as instanceIds contains static ids final int instancePosition = instanceIds.indexOf(instanceId); instances.set(instancePosition, instance); // Create mapping instance id -> instance instancesMap.put(instanceId, instance); } public String getId() { return staticId; } public String getEffectiveId() { return effectiveId; } public XBLBindings.Scope getResolutionScope() { return containingDocument.getStaticState().getXBLBindings().getResolutionScopeByPrefixedId(getPrefixedId()); } public LocationData getLocationData() { return (LocationData) modelDocument.getRootElement().getData(); } public XFormsModelBinds getBinds() { return binds; } public XFormsModelSchemaValidator getSchemaValidator() { return schemaValidator; } private void loadSchemasIfNeeded(PropertyContext propertyContext) { if (schemaValidator == null) { if (!XFormsProperties.isSkipSchemaValidation(containingDocument)) { final Element modelElement = modelDocument.getRootElement(); schemaValidator = new XFormsModelSchemaValidator(modelElement, indentedLogger); schemaValidator.loadSchemas(propertyContext); mustSchemaValidate = schemaValidator.hasSchema(); } } } public String[] getSchemaURIs() { if (schemaValidator != null) { return schemaValidator.getSchemaURIs(); } else { return null; } } /** * Restore the state of the model when the model object was just recreated. * * @param propertyContext current context */ public void restoreState(PropertyContext propertyContext) { // Ensure schema are loaded loadSchemasIfNeeded(propertyContext); // Restore instances restoreInstances(propertyContext); // Refresh binds, but do not recalculate (only evaluate "computed expression binds") deferredActionContext.rebuild = true; deferredActionContext.revalidate = true; doRebuild(propertyContext); if (binds != null) binds.applyComputedExpressionBinds(propertyContext); doRevalidate(propertyContext); } /** * Serialize this model's instances. * * @param instancesElement container element for serialized instances */ public void serializeInstances(Element instancesElement) { for (XFormsInstance currentInstance: instances) { // TODO: can we avoid storing the instance in the dynamic state if it has not changed from static state? final boolean isReadonlyNonReplacedInline = currentInstance.isReadOnly() && !currentInstance.isReplaced() && currentInstance.getSourceURI() == null; if (!isReadonlyNonReplacedInline) { // Serialize full instance of instance metadata (latter if instance is cached) // If it is readonly, not replaced, and inline, then don't even add information to the dynamic state instancesElement.add(currentInstance.createContainerElement(!currentInstance.isCache())); indentedLogger.logDebug("serialize", currentInstance.isCache() ? "storing instance metadata to dynamic state" : "storing full instance to dynamic state", "model effective id", effectiveId, "instance static id", currentInstance.getId()); // Log instance if needed if (XFormsProperties.getDebugLogging().contains("model-serialized-instance")) currentInstance.logInstance(indentedLogger, "serialized instance"); } } } /** * Restore all the instances serialized as children of the given container element. * * @param propertyContext current context */ private void restoreInstances(PropertyContext propertyContext) { // Find serialized instances from context final Element instancesElement = (Element) propertyContext.getAttribute(XBLContainer.XFORMS_DYNAMIC_STATE_RESTORE_INSTANCES); // Get instances from dynamic state first if (instancesElement != null) { for (Element currentInstanceElement: Dom4jUtils.elements(instancesElement)) { // Check that the instance belongs to this model final String currentModelEffectiveId = currentInstanceElement.attributeValue("model-id"); if (effectiveId.equals(currentModelEffectiveId)) { // Create and set instance document on current model final XFormsInstance newInstance = new XFormsInstance(currentInstanceElement); final boolean isReadonlyHint = XFormsInstance.isReadonlyHint(currentInstanceElement); // NOTE: Here instance must contain document setInstanceLoadFromCacheIfNecessary(propertyContext, isReadonlyHint, newInstance, null); indentedLogger.logDebug("restore", "restoring instance from dynamic state", "model effective id", effectiveId, "instance static id", newInstance.getId()); } } } // Then get instances from static state if necessary // This can happen if the instance is inline, readonly, and not replaced for (Element containerElement: containingDocument.getStaticState().getInstanceContainers(getPrefixedId())) { final String instanceStaticId = XFormsInstance.getInstanceStaticId(containerElement); if (instancesMap.get(instanceStaticId) == null) { // Must create instance final String xxformsExcludeResultPrefixes = containerElement.attributeValue(XFormsConstants.XXFORMS_EXCLUDE_RESULT_PREFIXES); final List<Element> children = Dom4jUtils.elements(containerElement); final boolean isReadonlyHint = XFormsInstance.isReadonlyHint(containerElement); final String xxformsValidation = containerElement.attributeValue(XFormsConstants.XXFORMS_VALIDATION_QNAME); // Extract document final Object instanceDocument = XXFormsExtractDocument.extractDocument(children.get(0), xxformsExcludeResultPrefixes, isReadonlyHint); // Set instance and associated information setInstanceDocument(instanceDocument, effectiveId, instanceStaticId, null, null, null, false, -1, xxformsValidation, false); } } } public void performDefaultAction(final PropertyContext propertyContext, XFormsEvent event) { final String eventName = event.getEventName(); if (XFormsEvents.XFORMS_MODEL_CONSTRUCT.equals(eventName)) { // 4.2.1 The xforms-model-construct Event // Bubbles: Yes / Cancelable: No / Context Info: None doModelConstruct(propertyContext); } else if (XFormsEvents.XXFORMS_READY.equals(eventName)) { // This is called after xforms-ready events have been dispatched to all models doAfterReady(); } else if (XFormsEvents.XFORMS_MODEL_CONSTRUCT_DONE.equals(eventName)) { // 4.2.2 The xforms-model-construct-done Event // Bubbles: Yes / Cancelable: No / Context Info: None // TODO: implicit lazy instance construction } else if (XFormsEvents.XFORMS_REBUILD.equals(eventName)) { // 4.3.7 The xforms-rebuild Event // Bubbles: Yes / Cancelable: Yes / Context Info: None doRebuild(propertyContext); } else if (XFormsEvents.XFORMS_RECALCULATE.equals(eventName)) { // 4.3.6 The xforms-recalculate Event // Bubbles: Yes / Cancelable: Yes / Context Info: None doRecalculate(propertyContext); } else if (XFormsEvents.XFORMS_REVALIDATE.equals(eventName)) { // 4.3.5 The xforms-revalidate Event // Bubbles: Yes / Cancelable: Yes / Context Info: None doRevalidate(propertyContext); } else if (XFormsEvents.XFORMS_REFRESH.equals(eventName)) { // 4.3.4 The xforms-refresh Event // Bubbles: Yes / Cancelable: Yes / Context Info: None doRefresh(propertyContext); } else if (XFormsEvents.XFORMS_RESET.equals(eventName)) { // 4.3.8 The xforms-reset Event // Bubbles: Yes / Cancelable: Yes / Context Info: None doReset(propertyContext); } else if (XFormsEvents.XFORMS_COMPUTE_EXCEPTION.equals(eventName) || XFormsEvents.XFORMS_LINK_EXCEPTION.equals(eventName)) { // 4.5.4 The xforms-compute-exception Event // Bubbles: Yes / Cancelable: No / Context Info: Implementation-specific error string. // The default action for this event results in the following: Fatal error. // 4.5.2 The xforms-link-exception Event // Bubbles: Yes / Cancelable: No / Context Info: The URI that failed to load (xsd:anyURI) // The default action for this event results in the following: Fatal error. final XFormsExceptionEvent exceptionEvent = (XFormsExceptionEvent) event; final Throwable throwable = exceptionEvent.getThrowable(); if (throwable instanceof RuntimeException) throw (RuntimeException) throwable; else throw new ValidationException("Received fatal error event: " + eventName, throwable, (LocationData) modelDocument.getRootElement().getData()); } } private void doReset(PropertyContext propertyContext) { // TODO // "The instance data is reset to the tree structure and values it had immediately // after having processed the xforms-ready event." // "Then, the events xforms-rebuild, xforms-recalculate, xforms-revalidate and // xforms-refresh are dispatched to the model element in sequence." container.dispatchEvent(propertyContext, new XFormsRebuildEvent(containingDocument, XFormsModel.this)); container.dispatchEvent(propertyContext, new XFormsRecalculateEvent(containingDocument, XFormsModel.this)); container.dispatchEvent(propertyContext, new XFormsRevalidateEvent(containingDocument, XFormsModel.this)); container.dispatchEvent(propertyContext, new XFormsRefreshEvent(containingDocument, XFormsModel.this)); } private void doAfterReady() { } private void doModelConstruct(PropertyContext propertyContext) { final Element modelElement = modelDocument.getRootElement(); // 1. All XML Schema loaded (throws xforms-link-exception) loadSchemasIfNeeded(propertyContext); // TODO: throw exception event // 2. Create XPath data model from instance (inline or external) (throws xforms-link-exception) // Instance may not be specified. { // Build initial instance documents final List<Element> instanceContainers = Dom4jUtils.elements(modelElement, XFormsConstants.XFORMS_INSTANCE_QNAME); if (instanceContainers.size() > 0) { // Iterate through all instances int instancePosition = 0; for (Element containerElement : instanceContainers) { // Skip processing in case somebody has already set this particular instance if (instances.get(instancePosition++) != null) { // NOP } else { // Did not get the instance from static state final LocationData locationData = (LocationData) containerElement.getData(); final String instanceStaticId = XFormsInstance.getInstanceStaticId(containerElement); final boolean isReadonlyHint = XFormsInstance.isReadonlyHint(containerElement); final boolean isCacheHint = XFormsInstance.isCacheHint(containerElement); final long xxformsTimeToLive = XFormsInstance.getTimeToLive(containerElement); final String xxformsValidation = containerElement.attributeValue(XFormsConstants.XXFORMS_VALIDATION_QNAME); // Load instance. This might throw an exception event (and therefore a Java exception) in case of fatal problem. loadInstance(propertyContext, containerElement, instanceStaticId, isReadonlyHint, isCacheHint, xxformsTimeToLive, xxformsValidation, locationData); } } } } // 3. P3P (N/A) // 4. Instance data is constructed. Evaluate binds: // a. Evaluate nodeset // b. Apply model item properties on nodes // c. Throws xforms-binding-exception if the node has already model item property with same name // TODO: a, b, c // 5. xforms-rebuild, xforms-recalculate, xforms-revalidate deferredActionContext.rebuild = true; deferredActionContext.recalculate = true; deferredActionContext.revalidate = true; doRebuild(propertyContext); doRecalculate(propertyContext); doRevalidate(propertyContext); } private void setInstanceLoadFromCacheIfNecessary(PropertyContext propertyContext, boolean readonlyHint, XFormsInstance newInstance, Element locationDataElement) { if (newInstance.getDocumentInfo() == null && newInstance.getSourceURI() != null) { // Instance not initialized yet and must be loaded from URL // This means that the instance was cached if (!newInstance.isCache()) throw new ValidationException("Non-initialized instance has to be cacheable for id: " + newInstance.getEffectiveId(), (locationDataElement != null) ? (LocationData) locationDataElement.getData() : getLocationData()); if (indentedLogger.isDebugEnabled()) indentedLogger.logDebug("restore", "using instance from instance cache (instance was not initialized)", "id", newInstance.getEffectiveId()); // NOTE: No XInclude supported to read instances with @src for now // TODO: must pass method and request body in case of POST/PUT final XFormsInstance cachedInstance = XFormsServerSharedInstancesCache.instance().findConvert(propertyContext, indentedLogger, newInstance.getId(), newInstance.getEffectiveModelId(), newInstance.getSourceURI(), newInstance.getRequestBodyHash(), readonlyHint, false, XFormsProperties.isExposeXPathTypes(containingDocument), newInstance.getTimeToLive(), newInstance.getValidation(), INSTANCE_LOADER); setInstance(cachedInstance, newInstance.isReplaced()); } else { // Instance is initialized, just use it // This means that the instance was not cached if (newInstance.isCache()) throw new ValidationException("Initialized instance has to be non-cacheable for id: " + newInstance.getEffectiveId(), (locationDataElement != null) ? (LocationData) locationDataElement.getData() : getLocationData()); if (indentedLogger.isDebugEnabled()) indentedLogger.logDebug("restore", "using initialized instance from state", "id", newInstance.getEffectiveId()); setInstance(newInstance, newInstance.isReplaced()); } } private void loadInstance(PropertyContext propertyContext, Element instanceContainer, String instanceStaticId, boolean readonlyHint, boolean isCacheHint, long xxformsTimeToLive, String xxformsValidation, LocationData locationData) { indentedLogger.startHandleOperation("load", "loading instance", "instance id", instanceContainer.attributeValue("id")); { // Get instance resource URI, can be from @src or @resource final String srcAttribute = instanceContainer.attributeValue("src"); final String resourceAttribute = instanceContainer.attributeValue("resource"); final List<Element> children = Dom4jUtils.elements(instanceContainer); if (srcAttribute != null) { // "If the src attribute is given, then it takes precedence over inline content and the resource // attribute, and the XML data for the instance is obtained from the link." if (srcAttribute.trim().equals("")) { // Got a blank src attribute, just dispatch xforms-link-exception final LocationData extendedLocationData = new ExtendedLocationData(locationData, "processing XForms instance", instanceContainer); final Throwable throwable = new ValidationException("Invalid blank URL specified for instance: " + instanceStaticId, extendedLocationData); container.dispatchEvent(propertyContext, new XFormsLinkExceptionEvent(containingDocument, XFormsModel.this, srcAttribute, instanceContainer, throwable)); } // Load instance loadExternalInstance(propertyContext, instanceContainer, instanceStaticId, srcAttribute, locationData, readonlyHint, isCacheHint, xxformsTimeToLive, xxformsValidation); } else if (children != null && children.size() >= 1) { // "If the src attribute is omitted, then the data for the instance is obtained from inline content if // it is given or the resource attribute otherwise. If both the resource attribute and inline content // are provided, the inline content takes precedence." final String xxformsExcludeResultPrefixes = instanceContainer.attributeValue(XFormsConstants.XXFORMS_EXCLUDE_RESULT_PREFIXES); if (children.size() > 1) { final LocationData extendedLocationData = new ExtendedLocationData(locationData, "processing XForms instance", instanceContainer); final Throwable throwable = new ValidationException("xforms:instance element must contain exactly one child element", extendedLocationData); container.dispatchEvent(propertyContext, new XFormsLinkExceptionEvent(containingDocument, XFormsModel.this, null, instanceContainer, throwable)); } try { // Extract document final Object instanceDocument = XXFormsExtractDocument.extractDocument((Element) children.get(0), xxformsExcludeResultPrefixes, readonlyHint); // Set instance and associated information if everything went well // NOTE: No XInclude supported to read instances with @src for now setInstanceDocument(instanceDocument, effectiveId, instanceStaticId, null, null, null, false, -1, xxformsValidation, false); } catch (Exception e) { final LocationData extendedLocationData = new ExtendedLocationData(locationData, "processing XForms instance", instanceContainer); final Throwable throwable = new ValidationException("Error extracting or setting inline instance", extendedLocationData); container.dispatchEvent(propertyContext, new XFormsLinkExceptionEvent(containingDocument, XFormsModel.this, null, instanceContainer, throwable)); } } else if (resourceAttribute != null) { // "the data for the instance is obtained from inline content if it is given or the // resource attribute otherwise" // Load instance loadExternalInstance(propertyContext, instanceContainer, instanceStaticId, resourceAttribute, locationData, readonlyHint, isCacheHint, xxformsTimeToLive, xxformsValidation); } else { // Everything missing final LocationData extendedLocationData = new ExtendedLocationData(locationData, "processing XForms instance", instanceContainer); final Throwable throwable = new ValidationException("Required @src attribute, @resource attribute, or inline content for instance: " + instanceStaticId, extendedLocationData); container.dispatchEvent(propertyContext, new XFormsLinkExceptionEvent(containingDocument, XFormsModel.this, "", instanceContainer, throwable)); } } indentedLogger.endHandleOperation(); } private void loadExternalInstance(final PropertyContext propertyContext, Element instanceContainer, final String instanceStaticId, String instanceResource, LocationData locationData, boolean readonlyHint, boolean cacheHint, long xxformsTimeToLive, String xxformsValidation) { try { // Perform HHRI encoding final String instanceResourceHHRI = XFormsUtils.encodeHRRI(instanceResource, true); if (cacheHint && ProcessorImpl.getProcessorInputSchemeInputName(instanceResourceHHRI) == null) { // Instance 1) has cache hint and 2) is not input:*, so it can be cached // NOTE: We don't allow sharing for input:* URLs as the data will likely differ per request // TODO: This doesn't handle optimized submissions. // Resolve to absolute URL final String absoluteURLString = XFormsUtils.resolveServiceURL(propertyContext, instanceContainer, instanceResourceHHRI, ExternalContext.Response.REWRITE_MODE_ABSOLUTE); // NOTE: No XInclude supported to read instances with @src for now final XFormsInstance sharedXFormsInstance = XFormsServerSharedInstancesCache.instance().findConvert(propertyContext, indentedLogger, instanceStaticId, effectiveId, absoluteURLString, null, readonlyHint, false, XFormsProperties.isExposeXPathTypes(containingDocument), xxformsTimeToLive, xxformsValidation, INSTANCE_LOADER); setInstance(sharedXFormsInstance, false); } else { // Instance cannot be cached // NOTE: Optimizing with include() for servlets has limitations, in particular // the proper split between servlet path and path info is not done. final ExternalContext externalContext = (ExternalContext) propertyContext.getAttribute(PipelineContext.EXTERNAL_CONTEXT); final ExternalContext.Request request = externalContext.getRequest(); final boolean optimizeLocal = !NetUtils.urlHasProtocol(instanceResourceHHRI) && (request.getContainerType().equals("portlet") || request.getContainerType().equals("servlet") && XFormsProperties.isOptimizeLocalInstanceInclude(containingDocument)); if (optimizeLocal) { // Use URL resolved against current context final URI resolvedURI = XFormsUtils.resolveXMLBase(instanceContainer, instanceResourceHHRI); loadInstanceOptimized(propertyContext, externalContext, instanceContainer, instanceStaticId, resolvedURI.toString(), readonlyHint, xxformsValidation); } else { // Use full resolved resource URL // o absolute path relative to server root, e.g. /orbeon/foo/bar/instance.xml // Resolve to absolute URL final String absoluteURLString = XFormsUtils.resolveServiceURL(propertyContext, instanceContainer, instanceResourceHHRI, ExternalContext.Response.REWRITE_MODE_ABSOLUTE); loadInstance(externalContext, instanceContainer, instanceStaticId, absoluteURLString, readonlyHint, xxformsValidation); } } } catch (Exception e) { final ValidationException validationException = ValidationException.wrapException(e, new ExtendedLocationData(locationData, "reading external instance", instanceContainer)); container.dispatchEvent(propertyContext, new XFormsLinkExceptionEvent(containingDocument, XFormsModel.this, instanceResource, instanceContainer, validationException)); } } private final InstanceLoader INSTANCE_LOADER = new InstanceLoader(); // TODO: Use XFormsModelSubmission instead of duplicating code here private class InstanceLoader implements XFormsServerSharedInstancesCache.Loader { public ReadonlyXFormsInstance load(PropertyContext propertyContext, String instanceStaticId, String modelEffectiveId, String instanceSourceURI, boolean handleXInclude, long timeToLive, String validation) { final URL sourceURL; try { sourceURL = URLFactory.createURL(instanceSourceURI); } catch (MalformedURLException e) { throw new OXFException(e); } if (indentedLogger.isDebugEnabled()) indentedLogger.logDebug("load", "loading instance into cache", "id", instanceStaticId, "URI", instanceSourceURI); final ExternalContext externalContext = (ExternalContext) propertyContext.getAttribute(PipelineContext.EXTERNAL_CONTEXT); final ConnectionResult connectionResult = new Connection().open(externalContext, indentedLogger, BaseSubmission.isLogBody(), Connection.Method.GET.name(), sourceURL, null, null, null, null, null, XFormsProperties.getForwardSubmissionHeaders(containingDocument)); // Handle connection errors if (connectionResult.statusCode != 200) { connectionResult.close(); throw new OXFException("Got invalid return code while loading instance from URI: " + instanceSourceURI + ", " + connectionResult.statusCode); } try { // Read result as XML and create new shared instance // TODO: Handle validating? final DocumentInfo documentInfo = TransformerUtils.readTinyTree(connectionResult.getResponseInputStream(), connectionResult.resourceURI, handleXInclude); return new ReadonlyXFormsInstance(effectiveId, instanceStaticId, documentInfo, instanceSourceURI, null, null, null, true, timeToLive, validation, handleXInclude, XFormsProperties.isExposeXPathTypes(containingDocument)); } catch (Exception e) { throw new OXFException("Got exception while loading instance from URI: " + instanceSourceURI, e); } finally { // Clean-up connectionResult.close(); } } } /* * Load an external instance using an absolute URL. */ private void loadInstance(ExternalContext externalContext, Element instanceContainer, String instanceId, String absoluteURLString, boolean isReadonlyHint, String xxformsValidation) { assert NetUtils.urlHasProtocol(absoluteURLString); // Connect using external protocol // Extension: username and password // NOTE: Those don't use AVTs for now, because XPath expressions in those could access // instances that haven't been loaded yet. final String xxformsUsername = instanceContainer.attributeValue(XFormsConstants.XXFORMS_USERNAME_QNAME); final String xxformsPassword = instanceContainer.attributeValue(XFormsConstants.XXFORMS_PASSWORD_QNAME); final Object instanceDocument;// Document or DocumentInfo if (containingDocument.getURIResolver() == null) { // Connect directly if there is no resolver or if the instance is globally cached // NOTE: If there is no resolver, URLs of the form input:* are not allowed assert ProcessorImpl.getProcessorInputSchemeInputName(absoluteURLString) == null; if (indentedLogger.isDebugEnabled()) indentedLogger.logDebug("load", "getting document from URI", "URI", absoluteURLString); final URL absoluteResolvedURL; try { absoluteResolvedURL = URLFactory.createURL(absoluteURLString); } catch (MalformedURLException e) { throw new OXFException("Invalid URL: " + absoluteURLString); } final ConnectionResult connectionResult = new Connection().open(externalContext, indentedLogger, BaseSubmission.isLogBody(), Connection.Method.GET.name(), absoluteResolvedURL, xxformsUsername, xxformsPassword, null, null, null, XFormsProperties.getForwardSubmissionHeaders(containingDocument)); try { // Handle connection errors if (connectionResult.statusCode != 200) { throw new OXFException("Got invalid return code while loading instance: " + absoluteURLString + ", " + connectionResult.statusCode); } // TODO: Handle validating and XInclude! // Read result as XML // TODO: use submission code if (!isReadonlyHint) { instanceDocument = TransformerUtils.readDom4j(connectionResult.getResponseInputStream(), connectionResult.resourceURI, false); } else { instanceDocument = TransformerUtils.readTinyTree(connectionResult.getResponseInputStream(), connectionResult.resourceURI, false); } } finally { // Clean-up connectionResult.close(); } } else { // Optimized case that uses the provided resolver if (indentedLogger.isDebugEnabled()) indentedLogger.logDebug("load", "getting document from resolver", "URI", absoluteURLString); // TODO: Handle validating and handleXInclude! if (!isReadonlyHint) { instanceDocument = containingDocument.getURIResolver().readURLAsDocument(absoluteURLString, xxformsUsername, xxformsPassword, XFormsProperties.getForwardSubmissionHeaders(containingDocument)); } else { instanceDocument = containingDocument.getURIResolver().readURLAsDocumentInfo(absoluteURLString, xxformsUsername, xxformsPassword, XFormsProperties.getForwardSubmissionHeaders(containingDocument)); } } // Set instance and associated information if everything went well // NOTE: No XInclude supported to read instances with @src for now setInstanceDocument(instanceDocument, effectiveId, instanceId, absoluteURLString, xxformsUsername, xxformsPassword, false, -1, xxformsValidation, false); } private void loadInstanceOptimized(PropertyContext propertyContext, ExternalContext externalContext, Element instanceContainer, String instanceId, String resourceAbsolutePathOrAbsoluteURL, boolean isReadonlyHint, String xxformsValidation) { // Whether or not to rewrite URLs final boolean isNoRewrite = XFormsUtils.resolveUrlNorewrite(instanceContainer); if (indentedLogger.isDebugEnabled()) indentedLogger.logDebug("load", "getting document from optimized URI", "URI", resourceAbsolutePathOrAbsoluteURL, "norewrite", Boolean.toString(isNoRewrite)); // Run submission final ConnectionResult connectionResult = OptimizedSubmission.openOptimizedConnection(propertyContext, externalContext, containingDocument, indentedLogger, null, "get", resourceAbsolutePathOrAbsoluteURL, isNoRewrite, null, null, null, false, OptimizedSubmission.MINIMAL_HEADERS_TO_FORWARD, null); final Object instanceDocument;// Document or DocumentInfo try { // Handle connection errors if (connectionResult.statusCode != 200) { throw new OXFException("Got invalid return code while loading instance: " + resourceAbsolutePathOrAbsoluteURL + ", " + connectionResult.statusCode); } // TODO: Handle validating and handleXInclude! // Read result as XML // TODO: use submission code if (!isReadonlyHint) { instanceDocument = TransformerUtils.readDom4j(connectionResult.getResponseInputStream(), connectionResult.resourceURI, false); } else { instanceDocument = TransformerUtils.readTinyTree(connectionResult.getResponseInputStream(), connectionResult.resourceURI, false); } } finally { // Clean-up connectionResult.close(); } // Set instance and associated information if everything went well // NOTE: No XInclude supported to read instances with @src for now setInstanceDocument(instanceDocument, effectiveId, instanceId, resourceAbsolutePathOrAbsoluteURL, null, null, false, -1, xxformsValidation, false); } public void performTargetAction(PropertyContext propertyContext, XBLContainer container, XFormsEvent event) { // NOP } public void doRebuild(PropertyContext propertyContext) { // Rebuild bind tree only if needed. if (binds != null && deferredActionContext.rebuild) { binds.rebuild(propertyContext); // TODO: rebuild computational dependency data structures // Controls may have @bind or xxforms:bind() references, so we need to mark them as dirty. Will need dependencies for controls to fix this. containingDocument.getControls().requireRefresh(); } // "Actions that directly invoke rebuild, recalculate, revalidate, or refresh always // have an immediate effect, and clear the corresponding flag." deferredActionContext.rebuild = false; } public void doRecalculate(PropertyContext propertyContext) { // Recalculate only if needed if (instances.size() > 0 && binds != null && deferredActionContext.recalculate) { // Apply calculate binds binds.applyCalculateBinds(propertyContext); } // "Actions that directly invoke rebuild, recalculate, revalidate, or refresh always // have an immediate effect, and clear the corresponding flag." deferredActionContext.recalculate = false; } public void doRevalidate(final PropertyContext propertyContext) { // Validate only if needed, including checking the flags, because if validation state is clean, validation // being idempotent, revalidating is not needed. if (instances.size() > 0 && (mustBindValidate || mustSchemaValidate) && deferredActionContext.revalidate) { if (indentedLogger.isDebugEnabled()) indentedLogger.startHandleOperation("validation", "performing revalidate", "model id", getEffectiveId()); // Clear validation state for (XFormsInstance currentInstance: instances) { XFormsUtils.iterateInstanceData(currentInstance, new XFormsUtils.InstanceWalker() { public void walk(NodeInfo nodeInfo) { InstanceData.clearValidationState(nodeInfo); } }, true); } // Run validation final Set<String> invalidInstances = new LinkedHashSet<String>(); // Validate using schemas if needed if (mustSchemaValidate) { // Apply schemas to all instances for (XFormsInstance currentInstance: instances) { // Currently we don't support validating read-only instances if (!currentInstance.isReadOnly()) { if (!schemaValidator.validateInstance(currentInstance)) { // Remember that instance is invalid invalidInstances.add(currentInstance.getEffectiveId()); } } } } // Validate using binds if needed if (mustBindValidate) binds.applyValidationBinds(propertyContext, invalidInstances); // NOTE: It is possible, with binds and the use of xxforms:instance(), that some instances in // invalidInstances do not belong to this model. Those instances won't get events with the dispatching // algorithm below. for (XFormsInstance currentInstance: instances) { if (invalidInstances.contains(currentInstance.getEffectiveId())) { container.dispatchEvent(propertyContext, new XXFormsInvalidEvent(containingDocument, currentInstance)); } else { container.dispatchEvent(propertyContext, new XXFormsValidEvent(containingDocument, currentInstance)); } } if (indentedLogger.isDebugEnabled()) indentedLogger.endHandleOperation(); } // "Actions that directly invoke rebuild, recalculate, revalidate, or refresh always // have an immediate effect, and clear the corresponding flag." deferredActionContext.revalidate = false; } private void doRefresh(PropertyContext propertyContext) { getXBLContainer().refreshIfNeeded(propertyContext); } /** * Handle an updated instance after a submission with instance replacement/update. * * @param updatedInstance instance to replace or update (can be new instance object or existing one) */ public void handleUpdatedInstance(final XFormsInstance updatedInstance) { // Set the instance on this model // Instance object might already be there, or might be a new one. In any case, instance needs to be marked as updated. setInstance(updatedInstance, true); { final XFormsModel.DeferredActionContext deferredActionContext = getDeferredActionContext(); deferredActionContext.rebuild = true; deferredActionContext.recalculate = true; deferredActionContext.revalidate = true; } final XFormsControls xformsControls = containingDocument.getControls(); if (xformsControls.isInitialized()) { // Controls exist, otherwise there is no point in doing anything controls-related // As of 2009-03-18 decision, XForms 1.1 specifies that deferred event handling flags are set instead of // performing RRRR directly deferredActionContext.setAllDeferredFlags(true); } } private final DeferredActionContext deferredActionContext = new DeferredActionContext(); public class DeferredActionContext { public boolean rebuild; public boolean recalculate; public boolean revalidate; public void setAllDeferredFlags(boolean value) { rebuild = value; recalculate = value; revalidate = value; if (value) getXBLContainer().requireRefresh(); } } public DeferredActionContext getDeferredActionContext() { return deferredActionContext; } public void setAllDeferredFlags(boolean value) { deferredActionContext.setAllDeferredFlags(value); } public void startOutermostActionHandler() { // NOP now that deferredActionContext is always created } public boolean needRebuildRecalculateRevalidate() { return deferredActionContext.rebuild || deferredActionContext.recalculate || deferredActionContext.revalidate; } public void rebuildRecalculateRevalidateIfNeeded(PropertyContext propertyContext) { // Process deferred behavior final DeferredActionContext currentDeferredActionContext = deferredActionContext; // NOTE: We used to clear deferredActionContext , but this caused events to be dispatched in a different // order. So we are now leaving the flag as is, and waiting until they clear themselves. if (currentDeferredActionContext.rebuild) { containingDocument.startOutermostActionHandler(); container.dispatchEvent(propertyContext, new XFormsRebuildEvent(containingDocument, this)); containingDocument.endOutermostActionHandler(propertyContext); } if (currentDeferredActionContext.recalculate) { containingDocument.startOutermostActionHandler(); container.dispatchEvent(propertyContext, new XFormsRecalculateEvent(containingDocument, this)); containingDocument.endOutermostActionHandler(propertyContext); } if (currentDeferredActionContext.revalidate) { containingDocument.startOutermostActionHandler(); container.dispatchEvent(propertyContext, new XFormsRevalidateEvent(containingDocument, this)); containingDocument.endOutermostActionHandler(propertyContext); } } public void rebuildRecalculateIfNeeded(PropertyContext propertyContext) { doRebuild(propertyContext); doRecalculate(propertyContext); } public XFormsEventObserver getParentEventObserver(XBLContainer container) { // There is no point for events to propagate beyond the model // NOTE: This could change in the future once models are more integrated in the components hierarchy return null; } /** * Return the List of XFormsEventHandler objects within this object. */ public List getEventHandlers(XBLContainer container) { return containingDocument.getStaticState().getEventHandlers(XFormsUtils.getPrefixedId(getEffectiveId())); } public XFormsContextStack.BindingContext getBindingContext(PropertyContext propertyContext, XFormsContainingDocument containingDocument) { contextStack.resetBindingContext(propertyContext, this); return contextStack.getCurrentBindingContext(); } }
package org.jaxen.test; import java.util.List; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.jaxen.JaxenException; import org.jaxen.UnresolvableException; import org.jaxen.XPath; import org.jaxen.dom.DOMXPath; import org.w3c.dom.Attr; import org.w3c.dom.Element; import junit.framework.TestCase; public class NamespaceTest extends TestCase { private org.w3c.dom.Document doc; public NamespaceTest(String name) { super(name); } protected void setUp() throws ParserConfigurationException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); doc = factory.newDocumentBuilder().newDocument(); } public void testMultipleNamespaceAxis() throws JaxenException { org.w3c.dom.Element root = doc.createElement("root"); doc.appendChild(root); Element child = doc.createElementNS("http: child.setAttributeNS("http: root.appendChild(child); XPath xpath = new DOMXPath("namespace::node()"); List result = xpath.selectNodes(child); assertEquals(3, result.size()); } public void testNumberOfNamespaceNodes() throws JaxenException { org.w3c.dom.Element root = doc.createElement("root"); doc.appendChild(root); Element child = doc.createElementNS("http: root.appendChild(child); XPath xpath = new DOMXPath("//namespace::node()"); List result = xpath.selectNodes(doc); assertEquals(3, result.size()); // 1 for xml prefix on root; 1 for foo prefix on child; 1 for xml prefix on child } public void testNamespaceAxis() throws JaxenException { org.w3c.dom.Element root = doc.createElement("root"); doc.appendChild(root); Element child = doc.createElementNS("http: root.appendChild(child); XPath xpath = new DOMXPath("namespace::node()"); List result = xpath.selectNodes(child); assertEquals(2, result.size()); } public void testUnprefixedNamespaceAxis() throws JaxenException { org.w3c.dom.Element root = doc.createElement("root"); doc.appendChild(root); Element child = doc.createElementNS("http: root.appendChild(child); XPath xpath = new DOMXPath("namespace::node()"); List result = xpath.selectNodes(child); assertEquals(2, result.size()); } public void testNamespaceNodesReadFromAttributes() throws JaxenException { org.w3c.dom.Element root = doc.createElement("root"); doc.appendChild(root); Attr a = doc.createAttributeNS("http: a.setNodeValue("value"); root.setAttributeNode(a); XPath xpath = new DOMXPath("namespace::node()"); List result = xpath.selectNodes(root); // one for the xml prefix; one from the attribute node assertEquals(2, result.size()); } public void testUnboundNamespaceUsedInXPathExpression() throws JaxenException { org.w3c.dom.Element root = doc.createElementNS("http: doc.appendChild(root); XPath xpath = new DOMXPath("/pre:root"); try { xpath.selectNodes(root); fail("Used unresolvable prefix"); } catch (UnresolvableException ex) { assertNotNull(ex.getMessage()); } } }
package com.Ryan.Calculator; public class Complex { public double real; public double imaginary; public double epsilon; // The tolerance for comparisons. Can be changed if a certain Complex is known to need a different epsilon static public double default_epsilon = 1E-6; // The default tolerance for all new Complex's. Can be changed if all or most will need a different epsilon. Defaults to a reasonable value // CONSTANTS final static public Complex ZERO=new Complex(0); final static public Complex ONE=new Complex(1); final static public Complex I=new Complex(0, 1); final static public Complex PI=new Complex(Math.PI); final static public Complex E=new Complex(Math.E); final static public Complex ERROR=new Complex(Double.NaN, Double.NaN); // Signifies an invalid operation public Complex() { real=0; imaginary=0; epsilon=default_epsilon; } public Complex(double Creal) { real=Creal; imaginary=0; epsilon=default_epsilon; } public Complex(double Creal, double Cimaginary) { real=Creal; imaginary=Cimaginary; epsilon=default_epsilon; } public Complex(double Creal, double Cimaginary, double Cepsilon) { real=Creal; imaginary=Cimaginary; epsilon=Cepsilon; } public Complex(Complex c) { real=c.real; imaginary=c.imaginary; epsilon=c.epsilon; } public Complex(Complex c, double Cepsilon) { real=c.real; imaginary=c.imaginary; epsilon=Cepsilon; } public String toString() { StringBuilder out=new StringBuilder(); if (isReal()) out.append(real); else if (isImaginary()) { out.append(imaginary); out.append('i'); } else { out.append(real); out.append( (imaginary==Math.abs(imaginary)) ? '+' : '-'); if (epsilonNotEqualTo(Math.abs(imaginary), 1)) out.append(Math.abs(imaginary)); out.append('i'); } return out.toString(); } public static String toString (Complex c) { return c.toString(); } @Override public boolean equals(Object o) { if (o instanceof Complex) { Complex c=(Complex)o; return epsilonEqualTo(c.real, real) && epsilonEqualTo(c.imaginary, imaginary); } else if (o instanceof Double || o instanceof Integer) return epsilonEqualTo(real, (double)o); return super.equals(o); } public static Complex parseString(String str) // Parses a string from the format used above to return a Complex { if (str.equals("0")) // Special case, for simplicity return ZERO; double real=Double.parseDouble(str); double imaginary=0; if (str.contains("i")) { int idx=str.indexOf('i')-1; if (str.charAt(idx)=='+') imaginary=1; else if (str.charAt(idx)=='-') imaginary=-1; else { if (str.contains("+")) imaginary=Double.parseDouble(str.substring(str.indexOf('+')+1)); else imaginary=Double.parseDouble(str.substring(str.indexOf("-", 1))); } } return new Complex(real, imaginary); } public String toNaiveString() // Ignores any special values and always returns a+bi, even when that makes no sense. Useful mostly with parseNaiveString() { return String.valueOf(real) + '+' + imaginary + 'i'; } public static Complex parseNaiveString(String str) // Create a complex based on the format used above. Much faster than parseString(), but does not play well with differently formatted inputs { double real; double imaginary; real=Double.parseDouble(str); int idx=str.indexOf('+'); str=str.substring(++idx); imaginary=Double.parseDouble(str); return new Complex(real, imaginary); } private boolean epsilonEqualTo(double lhs, double rhs) { return lhs == rhs || Math.abs(lhs - rhs) < epsilon; } private boolean epsilonNotEqualTo(double lhs, double rhs) { return !epsilonEqualTo(lhs, rhs); } private boolean epsilonGreaterThan(double lhs, double rhs) { return (lhs-rhs)>epsilon; } private boolean epsilonGreaterThanOrEqualTo(double lhs, double rhs) { return epsilonGreaterThan(lhs, rhs) || epsilonEqualTo(lhs, rhs); } private boolean epsilonLessThan(double lhs, double rhs) { return !epsilonGreaterThanOrEqualTo(lhs, rhs); } private boolean epsilonLessThanOrEqualTo(double lhs, double rhs) { return !epsilonGreaterThan(lhs, rhs); } public boolean isReal() { return Math.abs(imaginary)<epsilon; } public boolean isImaginary() { return Math.abs(real)<epsilon; } public Complex addTo(Complex target) { real+=target.real; imaginary+=target.imaginary; return this; } public Complex subtractTo (Complex target) // This name doesn't make sense, but none do. In addition, operationTo will be defined for all binary operators,for consistency { real-=target.real; imaginary-=target.imaginary; return this; } public Complex multiplyTo (Complex target) { real*=target.real; real-=(imaginary*target.imaginary); imaginary*=target.real; imaginary+=(real+target.imaginary); return this; } public Complex multiplyWith (Complex target) // Alias, for logic's sake { return multiplyTo(target); } public Complex divideTo (Complex target) { real*=target.real; real-=(imaginary*target.imaginary); imaginary*=target.real; imaginary-=(real*target.imaginary); double fac=(target.real*target.real)-(target.imaginary*target.imaginary); if (fac==0) // Divide-by-zero check return ERROR; real/=fac; imaginary/=fac; return this; } /* FOR HISTORY The following function was produced as an alternative to the above one. It is no better, but it is far more clever public Complex divideTo(Complex target) { if (!target.isReal()) return divideTo(target.rationalized()); real/=target.real; imaginary/=target.real; return this; } */ public Complex divideWith (Complex target) // Alias, for logic's sake { return divideTo(target); } public static Complex add (Complex lhs, Complex rhs) { Complex out=new Complex(lhs, default_epsilon); // Reset the epsilon, to hide what we're doing and prevent odd behavior out.addTo(rhs); return out; } public static Complex subtract (Complex lhs, Complex rhs) { Complex out=new Complex(lhs, default_epsilon); // Reset the epsilon, to hide what we're doing and prevent odd behavior out.subtractTo(rhs); return out; } public static Complex multiply (Complex lhs, Complex rhs) { Complex out=new Complex(lhs, default_epsilon); // Reset the epsilon, to hide what we're doing and prevent odd behavior out.multiplyTo(rhs); return out; } public static Complex divide (Complex lhs, Complex rhs) { Complex out=new Complex(lhs, default_epsilon); // Reset the epsilon, to hide what we're doing and prevent odd behavior out.divideTo(rhs); return out; } public Complex conjugate () { return new Complex(real, -imaginary, epsilon); } public Complex rationalize() { this.multiplyTo(conjugate()); return this; } public Complex rationalized() { return multiply(this, conjugate()); } public Complex negate() { real=-real; imaginary=-imaginary; return this; } public static Complex negate (Complex rhs) { Complex out =new Complex (rhs, default_epsilon); // Reset epsilon return out.negate(); } public Complex round() { real=Math.round(real); imaginary=Math.round(imaginary); return this; } public static Complex round(Complex val) { Complex out=new Complex(val, default_epsilon); // Reset epsilon return out.round(); } public Complex rounded() { return round(this); } public Complex floor() { real=Math.floor(real); imaginary=Math.floor(imaginary); return this; } public static Complex floor(Complex val) { Complex out=new Complex(val, default_epsilon); // Reset epsilon return out.floor(); } public Complex floored() { return floor(this); } public Complex ceil() { real=Math.ceil(real); imaginary=Math.ceil(imaginary); return this; } public static Complex ceil(Complex val) { Complex out=new Complex(val, default_epsilon); // Reset epsilon return out.ceil(); } public Complex ceiled() // This is a fantastic name for this. Definitely. { return ceil(this); } public Complex modulo (Complex target) // Doesn't modify the current instance { // Extension of the algorithm for general real modulo return subtract(this, multiply(floor(divide(this, target)), target)); } public Complex moduloTo (Complex target) // Does modify the current instance { Complex result=modulo(target); real=result.real; imaginary=result.imaginary; return this; } public Complex moduloWith (Complex target) // For sanity { return moduloTo(target); } // All functions below here do not modify the object they're called on // I've changed my mind. Complex will now be immutable unless its data is directly touched // TODO: Make it so that this comment is at the top of the file, then delete it. public static Complex modulo (Complex lhs, Complex rhs) // Static wrapper { return lhs.modulo(rhs); } public double magnitude() { return Math.sqrt((real*real)+(imaginary*imaginary)); } public double argument() // Result in radians { return Math.atan2(imaginary, real); } public double argumentd() // Result in degrees { return Math.toDegrees(Math.atan2(imaginary, real)); } public static Complex fromPolar(double magnitude, double argument) // Argument in radians { return new Complex(magnitude*Math.cos(argument), magnitude*Math.sin(argument)); } public static Complex fromPolarDegrees(double magnitude, double argument) // Sugar for argument in degrees { return fromPolar(magnitude, Math.toRadians(argument)); } public static Complex fromExponential(double magnitude, double argument) { // The values are the same as polar form, just written differently // This just exists to let people forget that fact return fromPolar(magnitude, argument); } public static Complex fromExponentialDegrees(double magnitude, double argument) { // The values are the same as polar form, just written differently // This just exists to let people forget that fact return fromPolarDegrees(magnitude, argument); } public Complex ln() // Natural log { return new Complex(Math.log(magnitude()), argument()); } public Complex log(Complex base) // Log in arbitrary base { return Complex.divide(ln(), base.ln()); } public Complex log10() // Common (base 10) log { return log(new Complex(10)); } public static Complex ln(Complex target) // Syntactic sugar { return target.ln(); } public static Complex log10(Complex target) // More syntactic sugar { return target.log10(); } public static Complex log(Complex target, Complex base) // Syntactic aspartame { return target.log(base); } public Complex sin() { return new Complex(Math.sin(real)*Math.cosh(imaginary), Math.cos(real)*Math.sinh(imaginary)); } public Complex cos() { return new Complex(Math.cos(real)*Math.cosh(imaginary), -(Math.sin(real)*Math.sinh(imaginary))); } public Complex tan() { return divide(sin(), cos()); } public static Complex sin(Complex target) { return target.sin(); } public static Complex cos(Complex target) { return target.cos(); } public static Complex tan(Complex target) { return target.tan(); } public Complex sind() { return new Complex(Math.toRadians(real), Math.toRadians(imaginary)).sin(); } public Complex cosd() { return new Complex(Math.toRadians(real), Math.toRadians(imaginary)).cos(); } public Complex tand() { return new Complex(Math.toRadians(real), Math.toRadians(imaginary)).tan(); } public static Complex sind(Complex target) { return target.sind(); } public static Complex cosd(Complex target) { return target.cosd(); } public static Complex tand(Complex target) { return target.tand(); } public static Complex exp (Complex exponent) { // Slight extension of deMoivre's formula // Derived using the standard rules of real exponentiation return multiply(new Complex(Math.exp(exponent.real)), new Complex(Math.cos(exponent.imaginary), Math.sin(exponent.imaginary))); } public Complex exp() { return exp(this); } public static Complex pow (double base, Complex exponent) // Necessary overload for the next function { // Slight extension of the last slight extension // Derived by representing base as e^ln(base) return multiply(new Complex(Math.pow(base, exponent.real)), new Complex(Math.cos(exponent.imaginary*Math.log(base)), Math.sin(exponent.imaginary*Math.log(base)))); } public Complex pow(Complex exponent) { // We start with special cases that are easier to compute if (equals(ZERO)) return ZERO; // Zero to the anything is zero if (exponent.equals(ZERO)) return ONE; // Anything to the zeroth is one if (exponent.isReal()) { if (isReal()) return new Complex(Math.pow(real, exponent.real)); if (isImaginary()) { double coefficient=Math.pow(imaginary, exponent.real); if (Math.round(exponent.real)==exponent.real) { Complex[] results = new Complex[] // The results of raising I to powers { new Complex(coefficient), new Complex(0, coefficient), new Complex(-coefficient), new Complex(0, -coefficient) }; return results [((int)exponent.real)%4]; } } } // If execution proceeds to this point, then we have to use the general formula for complex powers // There is almost certainly a nicer way to write this. I'm so sorry // TODO: Comment this silly mess double fac=exponent.real*argument()+.5*exponent.imaginary*Math.log((real*real)+(imaginary*imaginary)); return multiply(new Complex(Math.pow((real*real)+(imaginary*imaginary), exponent.real/2) *Math.exp(-exponent.imaginary*argument())), new Complex(Math.cos(fac), Math.sin(fac))); // Yes, I know the indentation is messy. It's used mostly to clarify which expression pairs with which } public static Complex pow(Complex base, Complex exponent) { Complex out = new Complex(base, default_epsilon); // Reset epsilon return out.pow(exponent); } public Complex sqrt() // Syntactic sugar. For now at least, I'll probably find a better way to to this.. later { return pow(new Complex(0.5)); } public static Complex sqrt(Complex out) { return pow(out, new Complex(0.5)); } public Complex square() { return multiply(this, this); } public static Complex square(Complex val) { return val.square(); } public Complex asin() { return multiply(negate(I), ln(multiply(I, this).addTo(sqrt(subtract(ONE, square()))))); } public static Complex asin(Complex target) { return target.asin(); } public Complex acos() { return multiply(negate(I), ln(add(this, sqrt(subtract(ONE, square()))))); } public static Complex acos(Complex target) { return target.acos(); } public Complex atan() { return multiply(new Complex(0,.5), ln(add(this, I).divideTo(subtract(I, this)))); } public static Complex atan(Complex target) { return target.atan(); } public Complex sinh() { return new Complex(Math.sinh(real)*Math.cos(imaginary), Math.cosh(real)*Math.sin(imaginary)); } public static Complex sinh(Complex target) { return target.sinh(); } public Complex cosh() { return new Complex(Math.cosh(real)*Math.cos(imaginary), Math.sinh(real)*Math.sin(imaginary)); } public static Complex cosh(Complex target) { return target.cosh(); } public Complex tanh() { return divide(sinh(), cosh()); } public static Complex tanh(Complex target) { return target.tanh(); } public Complex asinh() { return ln(add(this, sqrt(add(square(this), ONE)))); } public static Complex asinh(Complex target) { return target.asinh(); } public Complex acosh() { return ln(add(this, sqrt(subtract(square(this), ONE)))); } public static Complex acosh(Complex target) { return target.acosh(); } public Complex atanh() { return divide(subtract(ln(add(ONE, this)), ln(subtract(ONE, this))), new Complex(2)); } public static Complex atanh(Complex target) { return target.atanh(); } public Complex toDegrees() { return new Complex (Math.toDegrees(real), Math.toDegrees(imaginary)); } public static Complex toDegrees(Complex target) { return target.toDegrees(); } public Complex toRadians() { return new Complex(Math.toRadians(real), Math.toRadians(imaginary)); } public static Complex toRadians(Complex target) { return target.toRadians(); } }
package juc; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; public class SemaphoreTest { public static void main(String[] args) { WC wc = new WC(); new Thread(() -> wc.use()).start(); new Thread(() -> wc.use()).start(); new Thread(() -> wc.use()).start(); new Thread(() -> wc.use()).start(); new Thread(() -> wc.use()).start(); /** Thread-1 Thread-2 Thread-0 Thread-0 Thread-2 Thread-1 Thread-3 Thread-4 Thread-4 Thread-3 */ } } class WC { private Semaphore semaphore = new Semaphore(3); public void use() { try { semaphore.acquire(); System.out.println(Thread.currentThread().getName() +" "); TimeUnit.SECONDS.sleep(3); System.out.println(Thread.currentThread().getName() +" "); } catch (InterruptedException e) { e.printStackTrace(); } finally{ semaphore.release(); } } }
package com.Ryan.Calculator; public class Complex { public double real; public double imaginary; public double epsilon; // The tolerance for comparisons. Can be changed if a certain Complex is known to need a different epsilon static public double default_epsilon = 1E-6; // The default tolerance for all new Complex's. Can be changed if all or most will need a different epsilon. Defaults to a reasonable value // CONSTANTS final static public Complex ZERO=new Complex(0); final static public Complex ONE=new Complex(1); final static public Complex I=new Complex(0, 1); final static public Complex PI=new Complex(Math.PI); final static public Complex E=new Complex(Math.E); final static public Complex ERROR=new Complex(Double.NaN, Double.NaN); // Signifies an invalid operation public Complex() { real=0; imaginary=0; epsilon=default_epsilon; } public Complex(double Creal) { real=Creal; imaginary=0; epsilon=default_epsilon; } public Complex(double Creal, double Cimaginary) { real=Creal; imaginary=Cimaginary; epsilon=default_epsilon; } public Complex(double Creal, double Cimaginary, double Cepsilon) { real=Creal; imaginary=Cimaginary; epsilon=Cepsilon; } public Complex(Complex c) { real=c.real; imaginary=c.imaginary; epsilon=c.epsilon; } public Complex(Complex c, double Cepsilon) { real=c.real; imaginary=c.imaginary; epsilon=Cepsilon; } public String toString() { StringBuilder out=new StringBuilder(); if (isReal()) out.append(real); else if (isImaginary()) { if (epsilonNotEqualTo(Math.abs(imaginary), 1)) out.append(imaginary); else if (epsilonLessThan(imaginary, 0)) out.append('-'); out.append('i'); } else { out.append(real); out.append( (imaginary==Math.abs(imaginary)) ? '+' : '-'); if (epsilonNotEqualTo(Math.abs(imaginary), 1)) out.append(Math.abs(imaginary)); out.append('i'); } return out.toString(); } public static String toString (Complex c) { return c.toString(); } @Override public boolean equals(Object o) { if (o instanceof Complex) { Complex c=(Complex)o; return epsilonEqualTo(c.real, real) && epsilonEqualTo(c.imaginary, imaginary); } else if (o instanceof Double || o instanceof Integer) return epsilonEqualTo(real, (double)o); return super.equals(o); } public static Complex parseString(String str) // Parses a string from the format used above to return a Complex { if (str==null) return ERROR; if (str.equals("0")) // Special case, for simplicity return ZERO; if (str.equals("i")) // Special case... return I; if (str.equals("-i")) // ... for simplicity. return new Complex(0, -1); double real=parseDoublePrefix(str); double imaginary=0; if (str.contains("i")) { if (str.equals(Double.toString(real)+'i')) return new Complex(0, real); int idx=str.indexOf('i')-1; if (str.charAt(idx)=='+') imaginary=1; else if (str.charAt(idx)=='-') imaginary=-1; else { if (str.contains("+")) imaginary=parseDoublePrefix(str.substring(str.indexOf('+')+1)); else imaginary=parseDoublePrefix(str.substring(str.indexOf("-", 1))); } } return new Complex(real, imaginary); } public String toNaiveString() // Ignores any special values and always returns a+bi, even when that makes no sense. Useful mostly with parseNaiveString() { return String.valueOf(real) + '+' + imaginary + 'i'; } public static Complex parseNaiveString(String str) // Create a complex based on the format used above. Much faster than parseString(), but does not play well with differently formatted inputs { double real; double imaginary; real=parseDoublePrefix(str); int idx=str.indexOf('+'); str=str.substring(++idx); imaginary=parseDoublePrefix(str); return new Complex(real, imaginary); } private boolean epsilonEqualTo(double lhs, double rhs) { return lhs == rhs || Math.abs(lhs - rhs) < epsilon; } private boolean epsilonNotEqualTo(double lhs, double rhs) { return !epsilonEqualTo(lhs, rhs); } private boolean epsilonGreaterThan(double lhs, double rhs) { return (lhs-rhs)>epsilon; } private boolean epsilonGreaterThanOrEqualTo(double lhs, double rhs) { return epsilonGreaterThan(lhs, rhs) || epsilonEqualTo(lhs, rhs); } private boolean epsilonLessThan(double lhs, double rhs) { return !epsilonGreaterThanOrEqualTo(lhs, rhs); } private boolean epsilonLessThanOrEqualTo(double lhs, double rhs) { return !epsilonGreaterThan(lhs, rhs); } public boolean isReal() { return Math.abs(imaginary)<epsilon; } public boolean isImaginary() { return Math.abs(real)<epsilon; } public Complex addTo(Complex target) { real+=target.real; imaginary+=target.imaginary; return this; } public Complex subtractTo (Complex target) // This name doesn't make sense, but none do. In addition, operationTo will be defined for all binary operators,for consistency { real-=target.real; imaginary-=target.imaginary; return this; } public Complex multiplyTo (Complex target) { real*=target.real; real-=(imaginary*target.imaginary); imaginary*=target.real; imaginary+=(real*target.imaginary); return this; } public Complex multiplyWith (Complex target) // Alias, for logic's sake { return multiplyTo(target); } public Complex divideTo (Complex target) { real*=target.real; real-=(imaginary*target.imaginary); imaginary*=target.real; imaginary-=(real*target.imaginary); double fac=(target.real*target.real)-(target.imaginary*target.imaginary); if (fac==0) // Divide-by-zero check return ERROR; real/=fac; imaginary/=fac; return this; } /* FOR HISTORY The following function was produced as an alternative to the above one. It is no better, but it is far more clever public Complex divideTo(Complex target) { if (!target.isReal()) return divideTo(target.rationalized()); real/=target.real; imaginary/=target.real; return this; } */ public Complex divideWith (Complex target) // Alias, for logic's sake { return divideTo(target); } public static Complex add (Complex lhs, Complex rhs) { Complex out=new Complex(lhs, default_epsilon); // Reset the epsilon, to hide what we're doing and prevent odd behavior out.addTo(rhs); return out; } public static Complex subtract (Complex lhs, Complex rhs) { Complex out=new Complex(lhs, default_epsilon); // Reset the epsilon, to hide what we're doing and prevent odd behavior out.subtractTo(rhs); return out; } public static Complex multiply (Complex lhs, Complex rhs) { Complex out=new Complex(lhs, default_epsilon); // Reset the epsilon, to hide what we're doing and prevent odd behavior out.multiplyTo(rhs); return out; } public static Complex divide (Complex lhs, Complex rhs) { Complex out=new Complex(lhs, default_epsilon); // Reset the epsilon, to hide what we're doing and prevent odd behavior out.divideTo(rhs); return out; } public Complex conjugate () { return new Complex(real, -imaginary, epsilon); } public Complex rationalize() { this.multiplyTo(conjugate()); return this; } public Complex rationalized() { return multiply(this, conjugate()); } public Complex negate() { real=-real; imaginary=-imaginary; return this; } public static Complex negate (Complex rhs) { Complex out =new Complex (rhs, default_epsilon); // Reset epsilon return out.negate(); } public Complex round() { real=Math.round(real); imaginary=Math.round(imaginary); return this; } public static Complex round(Complex val) { Complex out=new Complex(val, default_epsilon); // Reset epsilon return out.round(); } public Complex rounded() { return round(this); } public Complex floor() { real=Math.floor(real); imaginary=Math.floor(imaginary); return this; } public static Complex floor(Complex val) { Complex out=new Complex(val, default_epsilon); // Reset epsilon return out.floor(); } public Complex floored() { return floor(this); } public Complex ceil() { real=Math.ceil(real); imaginary=Math.ceil(imaginary); return this; } public static Complex ceil(Complex val) { Complex out=new Complex(val, default_epsilon); // Reset epsilon return out.ceil(); } public Complex ceiled() // This is a fantastic name for this. Definitely. { return ceil(this); } public Complex modulo (Complex target) // Doesn't modify the current instance { // Extension of the algorithm for general real modulo return subtract(this, multiply(floor(divide(this, target)), target)); } public Complex moduloTo (Complex target) // Does modify the current instance { Complex result=modulo(target); real=result.real; imaginary=result.imaginary; return this; } public Complex moduloWith (Complex target) // For sanity { return moduloTo(target); } // All functions below here do not modify the object they're called on // I've changed my mind. Complex will now be immutable unless its data is directly touched // TODO: Make it so that this comment is at the top of the file, then delete it. public static Complex modulo (Complex lhs, Complex rhs) // Static wrapper { return lhs.modulo(rhs); } public double magnitude() { return Math.sqrt((real*real)+(imaginary*imaginary)); } public double argument() // Result in radians { return Math.atan2(imaginary, real); } public double argumentd() // Result in degrees { return Math.toDegrees(Math.atan2(imaginary, real)); } public static Complex fromPolar(double magnitude, double argument) // Argument in radians { return new Complex(magnitude*Math.cos(argument), magnitude*Math.sin(argument)); } public static Complex fromPolarDegrees(double magnitude, double argument) // Sugar for argument in degrees { return fromPolar(magnitude, Math.toRadians(argument)); } public static Complex fromExponential(double magnitude, double argument) { // The values are the same as polar form, just written differently // This just exists to let people forget that fact return fromPolar(magnitude, argument); } public static Complex fromExponentialDegrees(double magnitude, double argument) { // The values are the same as polar form, just written differently // This just exists to let people forget that fact return fromPolarDegrees(magnitude, argument); } public Complex ln() // Natural log { return new Complex(Math.log(magnitude()), argument()); } public Complex log(Complex base) // Log in arbitrary base { return Complex.divide(ln(), base.ln()); } public Complex log10() // Common (base 10) log { return log(new Complex(10)); } public Complex ln1p() { return ln(add(ONE,this)); // There is probably a better way to do this } public static Complex ln(Complex target) // Syntactic sugar { return target.ln(); } public static Complex log10(Complex target) // More syntactic sugar { return target.log10(); } public static Complex log(Complex target, Complex base) // Syntactic aspartame { return target.log(base); } public static Complex ln1p(Complex target) { return target.ln1p(); } public Complex sin() { return new Complex(Math.sin(real)*Math.cosh(imaginary), Math.cos(real)*Math.sinh(imaginary)); } public Complex cos() { return new Complex(Math.cos(real)*Math.cosh(imaginary), -(Math.sin(real)*Math.sinh(imaginary))); } public Complex tan() { return divide(sin(), cos()); } public static Complex sin(Complex target) { return target.sin(); } public static Complex cos(Complex target) { return target.cos(); } public static Complex tan(Complex target) { return target.tan(); } public Complex sind() { return new Complex(Math.toRadians(real), Math.toRadians(imaginary)).sin(); } public Complex cosd() { return new Complex(Math.toRadians(real), Math.toRadians(imaginary)).cos(); } public Complex tand() { return new Complex(Math.toRadians(real), Math.toRadians(imaginary)).tan(); } public static Complex sind(Complex target) { return target.sind(); } public static Complex cosd(Complex target) { return target.cosd(); } public static Complex tand(Complex target) { return target.tand(); } public static Complex exp (Complex exponent) { // Slight extension of deMoivre's formula // Derived using the standard rules of real exponentiation return multiply(new Complex(Math.exp(exponent.real)), new Complex(Math.cos(exponent.imaginary), Math.sin(exponent.imaginary))); } public Complex exp() { return exp(this); } public static Complex expm1 (Complex exponent) { // This doesn't make a ton of sense, but it was at least very easy to implement return multiply(new Complex(Math.expm1(exponent.real)), new Complex(Math.cos(exponent.imaginary), Math.sin(exponent.imaginary))); } public Complex expm1() { return expm1(this); } public static Complex pow (double base, Complex exponent) // Necessary overload for the next function { // Slight extension of the last slight extension // Derived by representing base as e^ln(base) return multiply(new Complex(Math.pow(base, exponent.real)), new Complex(Math.cos(exponent.imaginary*Math.log(base)), Math.sin(exponent.imaginary*Math.log(base)))); } public Complex pow(Complex exponent) { // We start with special cases that are easier to compute if (equals(ZERO)) return ZERO; // Zero to the anything is zero if (exponent.equals(ZERO)) return ONE; // Anything to the zeroth is one if (exponent.isReal()) { if (isReal()) { if (Math.pow(exponent.real, -1)%2==0 && real<0) // If our computation will generate a true complex... return new Complex(0, Math.pow(-real, exponent.real)); return new Complex(Math.pow(real, exponent.real)); } if (isImaginary()) { double coefficient=Math.pow(imaginary, exponent.real); if (Math.round(exponent.real)==exponent.real) { Complex[] results = new Complex[] // The results of raising I to powers { new Complex(coefficient), new Complex(0, coefficient), new Complex(-coefficient), new Complex(0, -coefficient) }; return results [((int)exponent.real)%4]; } } } // If execution proceeds to this point, then we have to use the general formula for complex powers // There is almost certainly a nicer way to write this. I'm so sorry // TODO: Comment this silly mess double fac=exponent.real*argument()+.5*exponent.imaginary*Math.log((real*real)+(imaginary*imaginary)); return multiply(new Complex(Math.pow((real*real)+(imaginary*imaginary), exponent.real/2) *Math.exp(-exponent.imaginary*argument())), new Complex(Math.cos(fac), Math.sin(fac))); // Yes, I know the indentation is messy. It's used mostly to clarify which expression pairs with which } public static Complex pow(Complex base, Complex exponent) { Complex out = new Complex(base, default_epsilon); // Reset epsilon return out.pow(exponent); } public Complex sqrt() // Syntactic sugar. For now at least, I'll probably find a better way to to this.. later { return pow(new Complex(0.5)); } public static Complex sqrt(Complex out) { return pow(out, new Complex(0.5)); } public Complex cbrt() // More syntactic sugar that should be improved later { return pow(new Complex(1/3)); } public static Complex cbrt(Complex out) { return pow(out, new Complex(1/3)); } public Complex square() { return multiply(this, this); } public static Complex square(Complex val) { return val.square(); } public Complex asin() { return multiply(negate(I), ln(multiply(I, this).addTo(sqrt(subtract(ONE, square()))))); } public static Complex asin(Complex target) { return target.asin(); } public Complex acos() { return multiply(negate(I), ln(add(this, sqrt(subtract(ONE, square()))))); } public static Complex acos(Complex target) { return target.acos(); } public Complex atan() { return multiply(new Complex(0,.5), ln(add(this, I).divideTo(subtract(I, this)))); } public static Complex atan(Complex target) { return target.atan(); } public Complex sinh() { return new Complex(Math.sinh(real)*Math.cos(imaginary), Math.cosh(real)*Math.sin(imaginary)); } public static Complex sinh(Complex target) { return target.sinh(); } public Complex cosh() { return new Complex(Math.cosh(real)*Math.cos(imaginary), Math.sinh(real)*Math.sin(imaginary)); } public static Complex cosh(Complex target) { return target.cosh(); } public Complex tanh() { return divide(sinh(), cosh()); } public static Complex tanh(Complex target) { return target.tanh(); } public Complex asinh() { return ln(add(this, sqrt(add(square(this), ONE)))); } public static Complex asinh(Complex target) { return target.asinh(); } public Complex acosh() { return ln(add(this, sqrt(subtract(square(this), ONE)))); } public static Complex acosh(Complex target) { return target.acosh(); } public Complex atanh() { return divide(subtract(ln(add(ONE, this)), ln(subtract(ONE, this))), new Complex(2)); } public static Complex atanh(Complex target) { return target.atanh(); } public Complex toDegrees() { return new Complex (Math.toDegrees(real), Math.toDegrees(imaginary)); } public static Complex toDegrees(Complex target) { return target.toDegrees(); } public Complex toRadians() { return new Complex(Math.toRadians(real), Math.toRadians(imaginary)); } public static Complex toRadians(Complex target) { return target.toRadians(); } public double abs() { // Easy naming overload. The absolute value of a complex number is just its magnitude return magnitude(); } public static double abs(Complex target) { return target.abs(); } // Helper methods private static double parseDoublePrefix(String str) // Acts like parseDouble, except it will not fail on strings like "2.0i" { StringBuilder proc=new StringBuilder(); for (int i=0; i<str.length(); ++i) { Character c=str.charAt(i); if (!(Character.isDigit(c) || c=='.')) // Double in base 10 break; proc.append(c); } return Double.parseDouble(proc.toString()); } }
package com.example.textmate; import android.content.ContentValues; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import java.lang.Class; import java.lang.String; public class textDB extends SQLiteOpenHelper { public static final String DataBase_Name = "TextMate.db"; public static final String Table_Name = "TextMateData"; public static final String Column1 = "ContactID"; public static final String Column2 = "ContactName"; public static final String Column3= "CharCount"; public static final String Column4 = "MessageCount"; public static final String Column5 = "TimeDiff"; //public static final String Column6 = "NumUpdates"; public textDB(Context context) { super(context, DataBase_Name, null, 1); } @Override public void onCreate(SQLiteDatabase db) { String createTable="CREATE TABLE "+Table_Name+"("+Column1+ "INTEGER PRIMARY KEY AUTOINCREMENT," +Column2+ "TEXT "+Column3+" INTEGER " +Column4+" INTEGER"+Column5+"DOUBLE" + ")"; db.execSQL(createTable); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS "+Table_Name); onCreate(db); } public boolean insertData(String ID,String name,int charCount, int messageCount, double diffTime){ ContentValues val = new ContentValues(); val.put(Column1, ID); val.put(Column2, name); val.put(Column3,charCount); val.put(Column4,messageCount); val.put(Column5,diffTime); SQLiteDatabase db = this.getWritableDatabase(); long check = db.insert(Table_Name, null, val); db.close(); return check != -1; } public boolean updateData(String ID,String name,int charCount, int messageCount, double diffTime) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues val = new ContentValues(); val.put(Column1, ID); val.put(Column2, name); val.put(Column3,charCount); val.put(Column4,messageCount); val.put(Column5,diffTime); db.update(Table_Name, val, "ID = ?", new String[]{ID}); return true; } }
package com.platform; import android.content.Context; import android.util.Log; import com.breadwallet.BreadApp; import com.breadwallet.presenter.activities.util.ActivityUTILS; import com.breadwallet.tools.util.Utils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.util.Iterator; import java.util.Map; import java.util.concurrent.TimeUnit; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; public class JsonRpcRequest { private static final String TAG = "JsonRpcRequest"; private JsonRpcRequestListener mRequestListener; private Response mResponse; public JsonRpcRequest() { } public interface JsonRpcRequestListener { void onRpcRequestCompleted(String jsonResult); } public Response makeRpcRequest(Context app, String url, JSONObject payload, JsonRpcRequestListener listener) { this.mRequestListener = listener; if (ActivityUTILS.isMainThread()) { Log.e(TAG, "makeRpcRequest: network on main thread"); throw new RuntimeException("network on main thread"); } Map<String, String> headers = BreadApp.getBreadHeaders(); final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); RequestBody requestBody = RequestBody.create(JSON, payload.toString()); Log.d(TAG, "JSON params -> " + payload.toString()); Request.Builder builder = new Request.Builder() .url(url) .header("Content-Type", "application/json") .header("Accept", "application/json") .header("User-agent", Utils.getAgentString(app, "android/HttpURLConnection")) .post(requestBody); Iterator it = headers.entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry) it.next(); builder.header((String) pair.getKey(), (String) pair.getValue()); } String response = null; Request request = builder.build(); //Log.d(TAG, "Request body -> " + request.body().); //Response resp = APIClient.getInstance(app).sendRequest(request, true, 0); Response resp = null; OkHttpClient client = new OkHttpClient.Builder().followRedirects(false).connectTimeout(10, TimeUnit.SECONDS)/*.addInterceptor(new LoggingInterceptor())*/.build(); try { request = APIClient.getInstance(app).authenticateRequest(request); resp = client.newCall(request).execute(); if(mRequestListener != null) { mRequestListener.onRpcRequestCompleted(resp.body().string()); } if (resp == null) { Log.e(TAG, "makeRpcRequest: " + url + ", resp is null"); return null; } else{ setResponse(resp); } } catch (IOException e) { e.printStackTrace(); } return resp; } private void setResponse(Response response){ this.mResponse = response; } public Response getResponse(){ return this.mResponse; } }
package com.weedz.dice; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Typeface; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.preference.PreferenceManager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.util.SparseIntArray; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; import com.weedz.dice.Bookmarks.BookmarksActivity; import java.lang.ref.WeakReference; import java.util.Observable; import java.util.Observer; public class MainActivity extends AppCompatActivity implements Observer { private static final String TAG = "HomeActivity"; // IDs private int summaryTextFieldStart = 0x000000ff; // Threading stuff private RollUpdateUIThread mRollUpdateThread; private PopulateSummaryTableThread mSummaryUpdateThread; private UpdateTableThread mUpdateTableThread; WeakReference<MainActivity> ref = new WeakReference<>(this); RollUpdateUIHandler handler = new RollUpdateUIHandler(ref); private SharedPreferences pref; @Override protected void onCreate(Bundle savedInstanceState) { pref = PreferenceManager.getDefaultSharedPreferences(this); // Set default values for settings PreferenceManager.setDefaultValues(this, R.xml.pref_main, false); ViewUtils.ApplyTheme(this, pref); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar); setSupportActionBar(toolbar); Button bt_add_die = (Button)findViewById(R.id.add_die_button); bt_add_die.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (mRollUpdateThread != null) { mRollUpdateThread.interrupt(); mRollUpdateThread = null; } if (mSummaryUpdateThread != null) { mSummaryUpdateThread.interrupt(); mSummaryUpdateThread = null; } if (mUpdateTableThread != null) { mUpdateTableThread.interrupt(); mUpdateTableThread = null; } EditText add_die_nr = (EditText)findViewById(R.id.add_die_nr); EditText add_die_sides = (EditText)findViewById(R.id.add_die_sides); try { int nr = Integer.parseInt(add_die_nr.getText().toString()); int sides = Integer.parseInt(add_die_sides.getText().toString()); if (nr > 0 && sides > 1) { Data.getInstance().addMultiDice(nr, sides); } } catch (NumberFormatException e) { //Log.i(TAG, "AddDie():NumberFormatException"); } } }); Button bt_remove_die = (Button)findViewById(R.id.remove_die_button); bt_remove_die.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (mRollUpdateThread != null) { mRollUpdateThread.interrupt(); mRollUpdateThread = null; } if (mSummaryUpdateThread != null) { mSummaryUpdateThread.interrupt(); mSummaryUpdateThread = null; } if (mUpdateTableThread != null) { mUpdateTableThread.interrupt(); mUpdateTableThread = null; } EditText remove_die_nr = (EditText)findViewById(R.id.remove_die_nr); EditText remove_die_sides = (EditText)findViewById(R.id.remove_die_sides); try { int nr = Integer.parseInt(remove_die_nr.getText().toString()); int sides = Integer.parseInt(remove_die_sides.getText().toString()); if (nr > 0 && sides > 1) { Data.getInstance().removeMultiDice(nr, sides); } } catch (NumberFormatException e) { //Log.i(TAG, "RemoveDie():NumberFormatException"); } } }); Button bt_set_dice = (Button)findViewById(R.id.set_dice_button); bt_set_dice.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (mRollUpdateThread != null) { mRollUpdateThread.interrupt(); mRollUpdateThread = null; } if (mSummaryUpdateThread != null) { mSummaryUpdateThread.interrupt(); mSummaryUpdateThread = null; } if (mUpdateTableThread != null) { mUpdateTableThread.interrupt(); mUpdateTableThread = null; } EditText set_dice_nr = (EditText)findViewById(R.id.set_dice_nr); EditText set_dice_sides = (EditText)findViewById(R.id.set_dice_sides); try { int nr = Integer.parseInt(set_dice_nr.getText().toString()); int sides = Integer.parseInt(set_dice_sides.getText().toString()); if (nr >= 0 && sides > 1) { Data.getInstance().setMultiDice(nr, sides); } } catch (NumberFormatException e) { //Log.i(TAG, "SetDie():NumberFormatException"); } } }); final Button roll = (Button)findViewById(R.id.roll_die_button); roll.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (mRollUpdateThread != null) { mRollUpdateThread.interrupt(); mRollUpdateThread = null; } if (mSummaryUpdateThread != null) { mSummaryUpdateThread.interrupt(); mSummaryUpdateThread = null; } if (mUpdateTableThread != null) { mUpdateTableThread.interrupt(); mUpdateTableThread = null; } TextView rolls = (TextView) ref.get().findViewById(R.id.die_rolls); TextView total_result = (TextView)findViewById(R.id.total_result); total_result.setText("Calculating..."); if (pref.getBoolean("pref_settings_detailed_roll", true)) { rolls.setText("Rolling..."); } else { rolls.setText(""); } Data.getInstance().roll(); } }); showDices(); Data.getInstance().addObserver(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { Intent intent; switch (item.getItemId()) { case R.id.action_settings: intent = new Intent(this, SettingsActivity.class); startActivityForResult(intent, 1); break; case R.id.action_bookmarks: intent = new Intent(this, BookmarksActivity.class); startActivity(intent); break; } return super.onOptionsItemSelected(item); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // Settings activity if (requestCode == 1) { // Resources updated if (resultCode == 1) { recreate(); } } super.onActivityResult(requestCode, resultCode, data); } static class RollUpdateUIHandler extends Handler { WeakReference<MainActivity> ref; public RollUpdateUIHandler(WeakReference<MainActivity> ref) { this.ref = ref; } @Override public void handleMessage(Message msg) { if (!Thread.currentThread().isInterrupted()) { // Interrupted if (msg.what == 0) { TableLayout tl = (TableLayout)ref.get().findViewById(R.id.dice_summary); TableRow tr = new TableRow(ref.get()); TextView textView = new TextView(ref.get()); textView.setTextAppearance(android.R.style.TextAppearance_Material_Medium); textView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER); textView.setGravity(Gravity.CENTER_HORIZONTAL); textView.setTypeface(null, Typeface.NORMAL); textView.setText(R.string.interrupted); tr.addView(textView); tl.removeAllViews(); tl.addView(tr); } // Populate summary table if (msg.what == 4) { TableLayout tl = (TableLayout)ref.get().findViewById(R.id.dice_summary); SparseIntArray dice = (SparseIntArray)msg.obj; int totalDice = Data.getInstance().getMultiNrOfDice(); for (int i = 1; i < dice.size(); i++) { TextView existing = (TextView)tl.findViewWithTag(ref.get().summaryTextFieldStart + (dice.get(0) * totalDice) + dice.keyAt(i)-1); if (existing != null) { String str = existing.getText().toString(); int nr = Integer.parseInt(str.substring(str.indexOf(":") + 1)) + dice.get(dice.keyAt(i)); existing.setText(dice.keyAt(i) + ":" + Integer.toString(nr)); } } } // Create summary table if (msg.what == 5) { TableLayout tl = (TableLayout) ref.get().findViewById(R.id.dice_summary); for (TableRow row : (TableRow[])msg.obj) { if (row != null) { tl.addView(row); } } } // Show detailed roll if (msg.what == 6) { TextView rolls = (TextView) ref.get().findViewById(R.id.die_rolls); rolls.append((String)msg.obj); } } super.handleMessage(msg); } } private class PopulateSummaryTableThread extends Thread { public void run() { final int BUFFER_LENGTH = Integer.parseInt(ref.get().pref.getString("pref_Settings_summary_buffer", "100")); final int THREAD_SLEEP = Integer.parseInt(ref.get().pref.getString("pref_settings_summary_thread_sleep", "100")); SparseIntArray dice = new SparseIntArray(); // Multi dice for (Integer key : Data.getInstance().getMultiDice().keySet()) { dice.put(0, key); for (int i = 0; i < Data.getInstance().getMultiNrOfDice(key); i++) { if (Thread.interrupted()) { handler.sendEmptyMessage(0); return; } if (Data.getInstance().getMultiDie(key, i) == 0) { //Log.d(TAG, "PopulateSummaryTableThread(): getMultiDie(" + key + ", " + i + "): IndexOutOfBounds"); break; } if (dice.get(Data.getInstance().getMultiDie(key, i)) == 0) { dice.put(Data.getInstance().getMultiDie(key, i), 1); } else { dice.put(Data.getInstance().getMultiDie(key, i), dice.get(Data.getInstance().getMultiDie(key, i)) + 1); } if (i > 0 && i % BUFFER_LENGTH == 0) { handler.obtainMessage(4, dice.clone()).sendToTarget(); try { Thread.sleep(THREAD_SLEEP); } catch (InterruptedException e) { handler.sendEmptyMessage(0); return; } dice.clear(); dice.put(0, key); } } handler.obtainMessage(4, dice.clone()).sendToTarget(); try { Thread.sleep(THREAD_SLEEP); } catch (InterruptedException e) { handler.sendEmptyMessage(0); return; } dice.clear(); } handler.obtainMessage(4, dice).sendToTarget(); synchronized (MainActivity.this) { mSummaryUpdateThread = null; } } } private class RollUpdateUIThread extends Thread { public void run() { final int BUFFER_LENGTH = Integer.parseInt(ref.get().pref.getString("pref_Settings_detailed_roll_buffer", "100")); final int THREAD_SLEEP = Integer.parseInt(ref.get().pref.getString("pref_settings_detailed_roll_thread_sleep", "100")); StringBuilder stringBuilder = new StringBuilder(Data.getInstance().getMultiNrOfDice() * 2); // Multi dice for (Integer key : Data.getInstance().getMultiDice().keySet()) { if (Thread.interrupted()) { handler.sendEmptyMessage(0); return; } stringBuilder.append(Data.getInstance().getMultiDice().get(key).size()).append("d").append(key).append("("); for (int i = 0; i < Data.getInstance().getMultiNrOfDice(key); i++) { if (Thread.interrupted()) { handler.sendEmptyMessage(0); return; } stringBuilder.append(Data.getInstance().getMultiDie(key, i)).append(","); } if (stringBuilder.length() > 0) { stringBuilder.deleteCharAt(stringBuilder.length() - 1); } stringBuilder.append(") "); } // Buffer int start = 0; int end; while(start < stringBuilder.length()) { if (Thread.interrupted()) { handler.sendEmptyMessage(0); return; } end = start + BUFFER_LENGTH; if (end > stringBuilder.length()) { end = stringBuilder.length(); } handler.obtainMessage(6, stringBuilder.substring(start, end)).sendToTarget(); try { Thread.sleep(THREAD_SLEEP); } catch (InterruptedException e) { handler.sendEmptyMessage(0); return; } start += BUFFER_LENGTH; } synchronized (MainActivity.this) { mRollUpdateThread = null; } } } private class UpdateTableThread extends Thread { public void run() { final float TEXT_SIZE = Float.parseFloat(ref.get().pref.getString("pref_settings_summary_font_size", "20")); final int ROW_BUFFER = Integer.parseInt(ref.get().pref.getString("pref_settings_create_summary_row_buffer", "50")); final int COLUMNS = Integer.parseInt(ref.get().pref.getString("pref_settings_summary_table_columns", "50")); // Multi dice int counter; TableRow[] tr = new TableRow[ROW_BUFFER]; TextView[] tv; int rowIndex = 0; int rows; int rowbuffer_value = 0; int totalDice = Data.getInstance().getMultiNrOfDice(); for (Integer key : Data.getInstance().getMultiDice().keySet()) { rows = (int) Math.ceil(key / (float)COLUMNS) + 1; counter = 0; tv = new TextView[1]; tv[0] = new TextView(ref.get()); tv[0].setGravity(Gravity.CENTER_HORIZONTAL); tv[0].setTextAppearance(android.R.style.TextAppearance_Material_Medium); tv[0].setTypeface(null, Typeface.BOLD); tv[0].setTextSize(TEXT_SIZE); tv[0].setText(Data.getInstance().getMultiNrOfDice(key) + "d" + key); tr[rowIndex] = new TableRow(ref.get()); tr[rowIndex].setGravity(Gravity.CENTER_HORIZONTAL); tr[rowIndex].addView(tv[0]); rowbuffer_value++; for (int i = 0; i < rows; i++) { tv = new TextView[COLUMNS]; rowIndex = rowbuffer_value; tr[rowIndex] = new TableRow(ref.get()); for (int j = 0; j < COLUMNS; j++) { if (Thread.interrupted()) { handler.sendEmptyMessage(0); return; } tv[j] = new TextView(ref.get()); tv[j].setGravity(Gravity.CENTER_HORIZONTAL); tv[j].setTextAppearance(android.R.style.TextAppearance_Material_Medium); tv[j].setTypeface(null, Typeface.NORMAL); tv[j].setTextSize(TEXT_SIZE); if (counter < key) { tv[j].setTag(ref.get().summaryTextFieldStart + (key * totalDice) + counter); tv[j].setText((counter+1) + ":0"); } tr[rowIndex].addView(tv[j]); counter++; } if (rowIndex == ROW_BUFFER - 1) { handler.obtainMessage(5, tr.clone()).sendToTarget(); try { Thread.sleep(Integer.parseInt(ref.get().pref.getString("pref_settings_create_summary_thread_sleep", "100"))); } catch (InterruptedException e) { handler.sendEmptyMessage(0); return; } tr = new TableRow[ROW_BUFFER]; rowbuffer_value = 0; } rowbuffer_value++; } } handler.obtainMessage(5, tr.clone()).sendToTarget(); synchronized (MainActivity.this) { mUpdateTableThread = null; } populateTable(); } } private synchronized void populateTable() { if (mSummaryUpdateThread != null) { mSummaryUpdateThread.interrupt(); mSummaryUpdateThread = null; } mSummaryUpdateThread = new PopulateSummaryTableThread(); mSummaryUpdateThread.start(); } // TODO: add buttons for disabled features private synchronized void diceRolled() { int total = Data.getInstance().getmTotal(); TextView total_result = (TextView)findViewById(R.id.total_result); total_result.setText(String.valueOf(total)); TableLayout tl = (TableLayout)ref.get().findViewById(R.id.dice_summary); tl.removeAllViews(); TextView rolls = (TextView) ref.get().findViewById(R.id.die_rolls); rolls.setTextSize(Float.parseFloat(ref.get().pref.getString("pref_settings_detailed_roll_thread_font_size", "19"))); rolls.setText(""); if (mRollUpdateThread != null) { mRollUpdateThread.interrupt(); mRollUpdateThread = null; } if (mSummaryUpdateThread != null) { mSummaryUpdateThread.interrupt(); mSummaryUpdateThread = null; } if (mUpdateTableThread != null) { mUpdateTableThread.interrupt(); mUpdateTableThread = null; } if (ref.get().pref.getBoolean("pref_settings_summary", true)) { mUpdateTableThread = new UpdateTableThread(); mUpdateTableThread.start(); } if (ref.get().pref.getBoolean("pref_settings_detailed_roll", true)) { mRollUpdateThread = new RollUpdateUIThread(); mRollUpdateThread.start(); } } private void showDices() { TextView dice = (TextView) findViewById(R.id.nrOfDice); StringBuilder diceSet = new StringBuilder("Dice: (").append(Data.getInstance().getMultiNrOfDice()).append("), "); for (Integer key : Data.getInstance().getMultiDice().keySet()) { diceSet.append(Data.getInstance().getMultiDice().get(key).size()).append("d").append(key).append(", "); } diceSet.delete(diceSet.length() - 2, diceSet.length() - 1); dice.setText(diceSet.toString()); } @Override protected void onStart() { Data.getInstance().addObserver(this); showDices(); super.onStart(); } @Override protected void onStop() { if (mRollUpdateThread != null) { mRollUpdateThread.interrupt(); mRollUpdateThread = null; } if (mSummaryUpdateThread != null) { mSummaryUpdateThread.interrupt(); mSummaryUpdateThread = null; } Data.getInstance().deleteObserver(this); super.onStop(); } @Override public void update(Observable o, Object obj) { if (Data.getInstance().getFlag(Data.FLAG_DICE_ROLL)) { diceRolled(); Data.getInstance().setFlag(Data.FLAG_DICE_ROLL, false); } if (Data.getInstance().getFlag(Data.FLAG_DICESET_UPDATE)) { showDices(); Data.getInstance().setFlag(Data.FLAG_DICE_ROLL, false); } if (Data.getInstance().getFlag(Data.FLAG_INTERRUPTED)) { TextView total_result = (TextView)findViewById(R.id.total_result); total_result.setText(R.string.interrupted); Data.getInstance().setFlag(Data.FLAG_INTERRUPTED, false); } } }
package org.sugr.volumetile; import android.content.Context; import android.media.AudioManager; import android.provider.Settings; import android.support.v7.app.AlertDialog; import android.support.v7.view.ContextThemeWrapper; import android.telephony.TelephonyManager; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.ImageView; import android.widget.SeekBar; import com.jakewharton.rxbinding.view.RxView; import com.jakewharton.rxbinding.widget.RxSeekBar; import java.util.HashMap; import java.util.Map; import butterknife.Bind; import butterknife.ButterKnife; import rx.Observable; import rx.Subscription; import rx.android.MainThreadSubscription; import rx.subjects.PublishSubject; public class Service extends android.service.quicksettings.TileService { private AudioManager audioManager; private PublishSubject<State> uiState = PublishSubject.create(); private PublishSubject<State> volumeState = PublishSubject.create(); private ViewHolder holder; private int focusedStream = AudioManager.STREAM_MUSIC; private Map<Integer, Integer> streamVolumeCache = new HashMap<>(); @Override public void onCreate() { super.onCreate(); audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE); } @Override public void onClick() { if (isLocked()) { unlockAndRun(this::createAndShow); } else { createAndShow(); } } private void createAndShow() { View root = LayoutInflater.from(this).inflate(R.layout.dialog, null); AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.AppTheme)); builder.setView(root); AlertDialog dialog = builder.create(); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); holder = new ViewHolder(root); Subscription uiStateSubscription = uiState.map( state -> new ViewTupleState(holder.tuples.get(state.stream), state) ).subscribe(tupleState -> { if (tupleState.state.muted || tupleState.state.volume == 0) { tupleState.tuple.bar.animate().alpha(0.3f).start(); tupleState.tuple.bar.setProgress(0); tupleState.tuple.mute.setVisibility(View.GONE); tupleState.tuple.unmute.setVisibility(View.VISIBLE); } else { if (tupleState.state.volume == -1 || tupleState.tuple.bar.getAlpha() != 1f) { if (tupleState.state.volume == -1) { tupleState.state.volume = intOrDefault(streamVolumeCache.get(tupleState.state.stream)); if (tupleState.state.volume == 0) { tupleState.state.volume = audioManager.getStreamVolume(tupleState.state.stream); } if (tupleState.state.volume == 0) { tupleState.state.volume = tupleState.tuple.bar.getMax() / 10; if (tupleState.state.volume == 0) { tupleState.state.volume = 1; } } } tupleState.tuple.bar.animate().alpha(1f).start(); tupleState.tuple.mute.setVisibility(View.VISIBLE); tupleState.tuple.unmute.setVisibility(View.GONE); } if (tupleState.state.volume > -1) { tupleState.tuple.bar.setProgress(tupleState.state.volume); } } }); Subscription volumeStateSubscription = volumeState.subscribe(state -> { if (state.muted || state.volume == 0) { streamVolumeCache.put(state.stream, audioManager.getStreamVolume(state.stream)); audioManager.adjustStreamVolume(state.stream, AudioManager.ADJUST_MUTE, 0); audioManager.setStreamVolume(state.stream, 0, AudioManager.FLAG_PLAY_SOUND); } else { if (state.volume == -1 || audioManager.isStreamMute(state.stream)) { if (state.volume == -1) { if (audioManager.getStreamVolume(state.stream) == 0) { state.volume = intOrDefault(streamVolumeCache.get(state.stream)); if (state.stream == 0) { state.volume = audioManager.getStreamMaxVolume(state.stream) / 10; } if (state.volume == 0) { state.volume = 1; } } } audioManager.adjustStreamVolume(state.stream, AudioManager.ADJUST_UNMUTE, 0); } if (state.volume > -1) { audioManager.setStreamVolume(state.stream, state.volume, AudioManager.FLAG_PLAY_SOUND); } } }); Subscription dialogKeySubscription = Observable.<Integer>create(subscriber -> { dialog.setOnKeyListener((dialogInterface, i, keyEvent) -> { if (!subscriber.isUnsubscribed() && keyEvent.getAction() == KeyEvent.ACTION_DOWN) { switch (i) { case KeyEvent.KEYCODE_VOLUME_DOWN: case KeyEvent.KEYCODE_VOLUME_UP: case KeyEvent.KEYCODE_VOLUME_MUTE: subscriber.onNext(i); return true; } } return false; }); subscriber.add(new MainThreadSubscription() { @Override protected void onUnsubscribe() { dialog.setOnKeyListener(null); } }); }).subscribe(i -> { int current = audioManager.getStreamVolume(focusedStream); int max = audioManager.getStreamMaxVolume(focusedStream); int step = audioManager.getStreamMaxVolume(focusedStream) / 10; if (step == 0) { step = 1; } State state; switch (i) { case KeyEvent.KEYCODE_VOLUME_DOWN: if (current - step < 0) { return; } state = new State(focusedStream, current - step, false); break; case KeyEvent.KEYCODE_VOLUME_UP: if (current + step > max) { return; } state = new State(focusedStream, current + step, false); break; case KeyEvent.KEYCODE_VOLUME_MUTE: if (audioManager.isStreamMute(focusedStream)) { state = new State(focusedStream, -1, true); } else { if (current == 0) { current += step; } state = new State(focusedStream, current, false); } break; default: return; } volumeState.onNext(state); uiState.onNext(state); }); dialog.setOnDismissListener(d -> { uiStateSubscription.unsubscribe(); volumeStateSubscription.unsubscribe(); dialogKeySubscription.unsubscribe(); holder = null; }); boolean voiceCapable = isVoiceCapable(); setupVolume(holder.mediaSeek, holder.mediaMute, holder.mediaUnmute, AudioManager.STREAM_MUSIC); setupVolume(holder.alarmSeek, holder.alarmMute, holder.alarmUnmute, AudioManager.STREAM_ALARM); if (voiceCapable) { setupVolume(holder.ringSeek, holder.ringMute, holder.ringUnmute, AudioManager.STREAM_RING); } else { holder.ringSeek.setVisibility(View.GONE); } boolean linked = Settings.System.getInt(getContentResolver(), "notifications_use_ring_volume", 1) == 1; if (linked && voiceCapable) { holder.notificationRow.setVisibility(View.GONE); } else { setupVolume(holder.notificationSeek, holder.notificationMute, holder.notificationUnmute, AudioManager.STREAM_NOTIFICATION); } showDialog(dialog); } private void setupVolume(SeekBar bar, ImageView mute, ImageView unmute, int stream) { int max = audioManager.getStreamMaxVolume(stream); bar.setMax(max); uiState.onNext(new State(stream, audioManager.getStreamVolume(stream), audioManager.isStreamMute(stream))); // Skip the initial value to avoid setting the focused stream RxSeekBar.userChanges(bar).skip(1).subscribe(v -> { focusedStream = stream; uiState.onNext(new State(stream, v, false)); volumeState.onNext(new State(stream, v, false)); }); RxView.clicks(mute).subscribe(v -> { focusedStream = stream; uiState.onNext(new State(stream, -1, true)); volumeState.onNext(new State(stream, -1, true)); }); RxView.clicks(unmute).subscribe(v -> { focusedStream = stream; uiState.onNext(new State(stream, -1, false)); volumeState.onNext(new State(stream, -1, false)); }); } private boolean isVoiceCapable() { TelephonyManager telephony = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); return telephony != null && telephony.isVoiceCapable(); } private static int intOrDefault(Integer in) { if (in == null) { return 0; } return in; } static class ViewHolder { @Bind(R.id.media_mute) ImageView mediaMute; @Bind(R.id.media_unmute) ImageView mediaUnmute; @Bind(R.id.media_seek) SeekBar mediaSeek; @Bind(R.id.alarm_mute) ImageView alarmMute; @Bind(R.id.alarm_unmute) ImageView alarmUnmute; @Bind(R.id.alarm_seek) SeekBar alarmSeek; @Bind(R.id.ring_mute) ImageView ringMute; @Bind(R.id.ring_unmute) ImageView ringUnmute; @Bind(R.id.ring_seek) SeekBar ringSeek; @Bind(R.id.notification_mute) ImageView notificationMute; @Bind(R.id.notification_unmute) ImageView notificationUnmute; @Bind(R.id.notification_seek) SeekBar notificationSeek; @Bind(R.id.notification_row) ViewGroup notificationRow; private Map<Integer, ViewTuple> tuples = new HashMap<>(); ViewHolder(View root) { ButterKnife.bind(this, root); tuples.put(AudioManager.STREAM_MUSIC, new ViewTuple(mediaMute, mediaUnmute, mediaSeek)); tuples.put(AudioManager.STREAM_ALARM, new ViewTuple(alarmMute, alarmUnmute, alarmSeek)); tuples.put(AudioManager.STREAM_RING, new ViewTuple(ringMute, ringUnmute, ringSeek)); tuples.put(AudioManager.STREAM_NOTIFICATION, new ViewTuple(notificationMute, notificationUnmute, notificationSeek)); } } private static class State { int stream; int volume; boolean muted; public State(int stream, int volume, boolean muted) { this.stream = stream; this.volume = volume; this.muted = muted; } } private static class ViewTuple { ImageView mute; ImageView unmute; SeekBar bar; public ViewTuple(ImageView mute, ImageView unmute, SeekBar bar) { this.mute = mute; this.unmute = unmute; this.bar = bar; } } private static class ViewTupleState { ViewTuple tuple; State state; ViewTupleState(ViewTuple tuple, State state) { this.tuple = tuple; this.state = state; } } }
package com.brogrammers.agora.test; import java.util.Date; import junit.framework.TestCase; public class SortByDateTest extends TestCase { QuestionController controller = QuestionController.getController(); WebServiceModel webModel = WebServiceModel.getModel(); List<Question> questions = weModel.getQuestions(); Question firstDate= new Question("Test post please ignore", "ignore pls", null ); Question secondDate = new Question("Why can't my Meowth talk?", "talk pls", null ); Question thirdDate = new Question("Where is infinity and beyond?", "the claw", null ); Question fourthDate = new Question("There's a snake in my boot.", "howdy howdy howdy", null ); //Order should be {fourthDate, secondDate, thirdDate, firstDate} //because automatically, newest is first long firstID = controller.addQuestion(noVote); long thirdID= controller.addQuestion(threeVote); long secondID = controller.addQuestion(fiveVote); long fourthID = controller.addQuestion(tenVote); //manually set date so fourth is oldest and first is now newest controller.getQuestionById(fourthID).setDate(Date()); controller.getQuestionById(thirdID).setDate(Date()); controller.getQuestionById(secondID).setDate(Date()); controller.getQuestionById(firstID).setDate(Date()); //assuming enum {VOTES, DATE}; questions.setFilter(1); //order should now be { firstDate, secondDate, thirdDate, fourthDate} assertTrue("firstDate not first", questions[0] == firstDate); assertTrue("secondDate not second", questions[1] == secondDate); assertTrue("thirdDate not third", questions[2] == thirdDate); assertTrue("fourthDate not last", questions[-1] == fourthDate); assertTrue("Correct count", questions.size() = 4); }
package de.golfgl.gdxgamesvcs; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Net; import com.badlogic.gdx.net.HttpParametersUtils; import com.badlogic.gdx.utils.JsonReader; import com.badlogic.gdx.utils.JsonValue; import com.badlogic.gdx.utils.Timer; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.HashMap; import java.util.Map; public class GameJoltClient implements IGameServiceClient { public static final String GAMESERVICE_ID = "GS_GAMEJOLT"; public static final String GJ_GATEWAY = "http://gamejolt.com/api/game/v1/"; public static final String GJ_USERNAME_PARAM = "gjapi_username"; public static final String GJ_USERTOKEN_PARAM = "gjapi_token"; protected static final int GJ_PING_INTERVAL = 30; protected IGameServiceListener gsListener; protected String userName; protected String userToken; protected String gjAppId; protected String gjAppPrivateKey; protected boolean connected; protected boolean connectionPending; protected boolean initialized; protected IGameServiceIdMapper<Integer> scoreTableMapper; protected IGameServiceIdMapper<Integer> trophyMapper; protected Timer.Task pingTask; private String eventKeyPrefix; private String guestName; public void initialize(String gjAppId, String gjAppPrivateKey) { this.gjAppId = gjAppId; this.gjAppPrivateKey = gjAppPrivateKey; initialized = true; } /** * sets up the mapper for score table calls * * @param scoreTableMapper * @return this for method chaining */ public GameJoltClient setGjScoreTableMapper(IGameServiceIdMapper<Integer> scoreTableMapper) { this.scoreTableMapper = scoreTableMapper; return this; } /** * sets up the mapper for trophy calls * * @param trophyMapper * @return this for method chaining */ public GameJoltClient setGjTrophyMapper(IGameServiceIdMapper<Integer> trophyMapper) { this.trophyMapper = trophyMapper; return this; } public String getUserToken() { return userToken; } /** * Sets the GameJolt user token. Not possible when connected! * * @param userToken * @return */ public GameJoltClient setUserToken(String userToken) { if (isConnected()) throw new IllegalStateException(); this.userToken = userToken; return this; } /** * Sets the GameJolt user name. Not possible when connected! * * @param userName * @return */ public GameJoltClient setUserName(String userName) { if (isConnected()) throw new IllegalStateException(); this.userName = userName; return this; } /** * see {@link #setGuestName(String)} * * @return */ public String getGuestName() { return guestName; } /** * GameJolt can post scores to scoreboards without an authenticated user. Set a guest name to enable this featuee. * * @param guestName */ public GameJoltClient setGuestName(String guestName) { this.guestName = guestName; return this; } @Override public String getGameServiceId() { return GAMESERVICE_ID; } @Override public void setListener(IGameServiceListener gsListener) { this.gsListener = gsListener; } @Override public boolean connect(final boolean silent) { if (!initialized) { Gdx.app.error(GAMESERVICE_ID, "Cannot connect before app ID is set via initialize()"); return false; } if (connected) return true; if (userName == null || userToken == null) { //show UI via Gdx.input.getTextInput not possible in GWT w/o gdx-dialog. //to avoid a dependency and keep this simple, nothing is done here but //GameJolt branch Gdx.app.log(GAMESERVICE_ID, "Cannot connect without user name and user's token."); return false; } Map<String, String> params = new HashMap<String, String>(); addGameIDUserNameUserToken(params); final Net.HttpRequest http = buildJsonRequest("users/auth/", params); if (http == null) return false; connectionPending = true; Gdx.net.sendHttpRequest(http, new Net.HttpResponseListener() { @Override public void handleHttpResponse(Net.HttpResponse httpResponse) { connectionPending = false; JsonValue response = null; String json = httpResponse.getResultAsString(); try { response = new JsonReader().parse(json).get("response"); } catch (Throwable t) { // eat } if (response == null) { Gdx.app.error(GAMESERVICE_ID, "Could not parse answer from GameJolt: " + json); authenticationFailed(silent, "Cannot authenticate. Response not in right format."); } else { connected = response.getBoolean("success"); if (connected) { // Open a session sendOpenSessionEvent(); if (gsListener != null) gsListener.gsConnected(); } else { Gdx.app.log(GAMESERVICE_ID, "Authentification from GameJolt failed. Check username, token, " + "app id and private key."); authenticationFailed(silent, "GameJolt authentication failed."); } } } @Override public void failed(Throwable t) { Gdx.app.log(GAMESERVICE_ID, "Auth HTTP Request failed"); authenticationFailed(silent, "Cannot connect to GameJolt due to network problems."); } @Override public void cancelled() { Gdx.app.log(GAMESERVICE_ID, "Auth HTTP Request cancelled."); authenticationFailed(silent, "Cannot connect to GameJolt. Request cancelled."); } }); return true; } protected void sendOpenSessionEvent() { if (!isConnected()) return; Map<String, String> params = new HashMap<String, String>(); addGameIDUserNameUserToken(params); final Net.HttpRequest http = buildJsonRequest("sessions/open/", params); if (http != null) Gdx.net.sendHttpRequest(http, new NoOpResponseListener()); pingTask = Timer.schedule(new Timer.Task() { @Override public void run() { sendKeepSessionOpenEvent(); } }, GJ_PING_INTERVAL, GJ_PING_INTERVAL); } protected void sendKeepSessionOpenEvent() { if (!isConnected()) return; Map<String, String> params = new HashMap<String, String>(); addGameIDUserNameUserToken(params); final Net.HttpRequest http = buildJsonRequest("sessions/ping/", params); if (http != null) Gdx.net.sendHttpRequest(http, new NoOpResponseListener()); } protected void authenticationFailed(boolean silent, String msg) { connected = false; connectionPending = false; if (gsListener != null) { gsListener.gsDisconnected(); if (!silent) gsListener.gsErrorMsg(IGameServiceListener.GsErrorType.errorLoginFailed, msg); } } @Override public void disconnect() { if (pingTask != null) pingTask.cancel(); sendCloseSessionEvent(); connected = false; if (gsListener != null) gsListener.gsDisconnected(); } protected void sendCloseSessionEvent() { if (!isConnected()) return; Map<String, String> params = new HashMap<String, String>(); addGameIDUserNameUserToken(params); final Net.HttpRequest http = buildJsonRequest("sessions/close/", params); if (http != null) Gdx.net.sendHttpRequest(http, new NoOpResponseListener()); } @Override public void logOff() { disconnect(); userName = null; userToken = null; } @Override public String getPlayerDisplayName() { return (connected ? userName : null); } @Override public boolean isConnected() { return connected; } @Override public boolean isConnectionPending() { return connectionPending && !connected; } @Override public boolean providesLeaderboardUI() { return false; } @Override public void showLeaderboards(String leaderBoardId) throws GameServiceException { throw new GameServiceException.NotSupportedException(); } @Override public boolean providesAchievementsUI() { return false; } @Override public void showAchievements() throws GameServiceException { throw new GameServiceException.NotSupportedException(); } @Override public void submitToLeaderboard(String leaderboardId, long score, String tag) { //GameJolt allows submitting scores without an open session. //Enable it by setting guest name. if (!initialized) { Gdx.app.error(GAMESERVICE_ID, "Cannot post score: set app ID via initialize()"); return; } if (scoreTableMapper == null) { Gdx.app.log(GAMESERVICE_ID, "Cannot post score: No mapper for score table ids provided."); return; } Integer boardId = scoreTableMapper.mapToGsId(leaderboardId); // no board available if (boardId == null) return; Map<String, String> params = new HashMap<String, String>(); if (isConnected()) addGameIDUserNameUserToken(params); else if (guestName != null) { params.put("game_id", gjAppId); params.put("guest", guestName); } else { Gdx.app.log(GAMESERVICE_ID, "Cannot post to scoreboard. No guest name and no user given."); } params.put("score", String.valueOf(score)); params.put("sort", String.valueOf(score)); if (tag != null) params.put("extra_data", tag); params.put("table_id", boardId.toString()); final Net.HttpRequest http = buildJsonRequest("scores/add/", params); if (http == null) return; Gdx.net.sendHttpRequest(http, new NoOpResponseListener()); } /** * see {@link #getEventKeyPrefix()} * * @return */ public String getEventKeyPrefix() { return eventKeyPrefix; } /** * GameJolt does not have a dedicated API for events, but it is encouraged by documentation to use the * global data store. Use this method to set a prefix to use for event keys for no conflicts with other * keys you are using. * <p> * Please note: GameJolt does not provide a user interface for reading the event stats. You have to write * your own program to read the event stats regularly. * <p> * You have to set the key yourself the first time. submitEvents performs an add operation on the key, which * fails when the key is not already created. * * @param eventKeyPrefix Your prefix for event keys, or null to deactivate using global data storage for events. * Default is null. */ public GameJoltClient setEventKeyPrefix(String eventKeyPrefix) { this.eventKeyPrefix = eventKeyPrefix; return this; } @Override public void submitEvent(String eventId, int increment) { if (!initialized) { Gdx.app.error(GAMESERVICE_ID, "Cannot submit event: set app ID via initialize() first"); return; } if (eventKeyPrefix == null) { Gdx.app.log(GAMESERVICE_ID, "No event logged - no event key prefix provided."); return; } Map<String, String> params = new HashMap<String, String>(); // no user name or token added! We want to use the global storage. params.put("game_id", gjAppId); params.put("key", eventKeyPrefix + eventId); params.put("value", Integer.toString(increment)); params.put("operation", "add"); final Net.HttpRequest http = buildJsonRequest("data-store/update/", params); if (http == null) return; Gdx.net.sendHttpRequest(http, new NoOpResponseListener()); } /** * Use careful! It resets your event to 0. Needed for first time initialization. * * @param eventId */ public void initializeOrResetEventKey(String eventId) { if (!initialized) { Gdx.app.error(GAMESERVICE_ID, "Cannot submit event: set app ID via initialize() first"); return; } if (eventKeyPrefix == null) { Gdx.app.log(GAMESERVICE_ID, "No event key prefix provided."); return; } // no user name or token added! We want to use the global storage. storeData(eventKeyPrefix + eventId, true, "0"); } @Override public void unlockAchievement(String achievementId) { if (trophyMapper == null) { Gdx.app.log(GAMESERVICE_ID, "Cannot unlock achievement: No mapper for trophy ids provided."); return; } if (!isConnected()) return; Integer trophyId = trophyMapper.mapToGsId(achievementId); // no board available or not connected if (trophyId == null) return; Map<String, String> params = new HashMap<String, String>(); addGameIDUserNameUserToken(params); params.put("trophy_id", String.valueOf(trophyId)); final Net.HttpRequest http = buildJsonRequest("trophies/add-achieved/", params); if (http == null) return; Gdx.net.sendHttpRequest(http, new NoOpResponseListener()); } @Override public void incrementAchievement(String achievementId, int incNum) { // not supported - fall back unlockAchievement(achievementId); } @Override public void saveGameState(String fileId, byte[] gameState, long progressValue) { //TODO - it is supported by Gamejolt, but not by this client //see storeData throw new UnsupportedOperationException(); } protected void storeData(String dataKey, boolean globalKey, String content) { Map<String, String> params = new HashMap<String, String>(); if (globalKey) params.put("game_id", gjAppId); else addGameIDUserNameUserToken(params); params.put("key", dataKey); // should better be POSTed, which should work according to the documentation. But it did not (see below). params.put("data", content); final Net.HttpRequest http = buildJsonRequest("data-store/set/", params); if (http == null) return; //This does not work: //http.setMethod(Net.HttpMethods.POST); //http.setContent("data=" + content); //This also does not work: //http.setMethod(Net.HttpMethods.POST); //http.setContent(content); Gdx.net.sendHttpRequest(http, new NoOpResponseListener()); } @Override public void loadGameState(String fileId) { //TODO - it is supported by Gamejolt, but not by this client throw new UnsupportedOperationException(); } @Override public CloudSaveCapability supportsCloudGameState() { //TODO - it is supported by Gamejolt, but not by this client return CloudSaveCapability.NotSupported; } protected void addGameIDUserNameUserToken(Map<String, String> params) { params.put("game_id", String.valueOf(gjAppId)); params.put("username", userName); params.put("user_token", userToken); } protected /* @Nullable */ Net.HttpRequest buildJsonRequest(String component, Map<String, String> params) { component = component + "?format=json&"; return buildRequest(component, params); } protected Net.HttpRequest buildRequest(String component, Map<String, String> params) { String request = GJ_GATEWAY + component; request += HttpParametersUtils.convertHttpParameters(params); /* Generate signature */ final String signature; try { signature = md5(request + gjAppPrivateKey); } catch (Exception e) { /* Do not leak 'gamePrivateKey' in log */ Gdx.app.error(GAMESERVICE_ID, "Cannot honor request: " + request, e); return null; } /* Append signature */ String complete = request; complete += "&"; complete += "signature"; complete += "="; complete += signature; final Net.HttpRequest http = new Net.HttpRequest(); http.setMethod(Net.HttpMethods.GET); http.setUrl(complete); return http; } protected String md5(String s) throws UnsupportedEncodingException, NoSuchAlgorithmException { final MessageDigest md = MessageDigest.getInstance("MD5"); final byte[] bytes = s.getBytes("UTF-8"); final byte[] digest = md.digest(bytes); final StringBuffer sb = new StringBuffer(); for (int i = 0; i < digest.length; ++i) { sb.append(Integer.toHexString((digest[i] & 0xFF) | 0x100).substring(1, 3)); } return sb.toString(); } protected static class NoOpResponseListener implements Net.HttpResponseListener { @Override public void handleHttpResponse(Net.HttpResponse httpResponse) { Gdx.app.debug(GAMESERVICE_ID, httpResponse.getResultAsString()); } @Override public void failed(Throwable t) { Gdx.app.log(GAMESERVICE_ID, t.getMessage(), t); } @Override public void cancelled() { } } }
import constant.Region; import dto.Static.Champion; import main.java.riotapi.RiotApiException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Map; public class ChampionCollector extends AbstractCollector { private List<database.models.Champion> champions; private URL staticChampionURL; private String url = "http://ddragon.leagueoflegends.com/cdn/5.17.1/data/en_US/champion/Aatrox.json"; public ChampionCollector(String apiKey) { super(apiKey); this.champions = new ArrayList<>(); } public void collectChampionInfo() throws RiotApiException { Map<String, Champion> championMap = api.getDataChampionList().getData(); for (String name : championMap.keySet()) { //champions.add(new database.models.Champion(name, championMap.get(name).getId())); Champion champion = championMap.get(name); System.out.println(champion.getSpells().size()); } //this.insertIntoDatbase(champions); } public void insertIntoDatbase(List<database.models.Champion> champions) { champions.forEach(champ -> new database.models.Champion().insertObject(champ));; } }
package imagej.legacy; import java.awt.GraphicsEnvironment; import java.lang.reflect.Field; import java.net.URL; import javassist.NotFoundException; import javassist.bytecode.DuplicateMemberException; import org.scijava.Context; import org.scijava.util.ClassUtils; /** * Overrides class behavior of ImageJ1 classes using bytecode manipulation. This * class uses the {@link CodeHacker} (which uses Javassist) to inject method * hooks, which are implemented in the {@link imagej.legacy.patches} package. * * @author Curtis Rueden */ public class LegacyInjector { private CodeHacker hacker; /** Overrides class behavior of ImageJ1 classes by injecting method hooks. */ public void injectHooks(final ClassLoader classLoader) { hacker = new CodeHacker(classLoader); injectHooks(hacker); } /** Overrides class behavior of ImageJ1 classes by injecting method hooks. */ protected void injectHooks(final CodeHacker hacker) { // NB: Override class behavior before class loading gets too far along. if (GraphicsEnvironment.isHeadless()) { new LegacyHeadless(hacker).patch(); } // override behavior of ij.ImageJ hacker.insertNewMethod("ij.ImageJ", "public java.awt.Point getLocationOnScreen()"); hacker.insertAtTopOfMethod("ij.ImageJ", "public java.awt.Point getLocationOnScreen()", "if ($isLegacyMode()) return super.getLocationOnScreen();"); hacker.insertAtTopOfMethod("ij.ImageJ", "public void quit()", "if (!($service instanceof imagej.legacy.DummyLegacyService)) $service.getContext().dispose();" + "if (!$isLegacyMode()) return;"); // override behavior of ij.IJ hacker.insertAtTopOfMethod("ij.IJ", "public static java.lang.Object runPlugIn(java.lang.String className, java.lang.String arg)", "if (\"MacAdapter\".equals(className)) return null;"); hacker.insertAtBottomOfMethod("ij.IJ", "public static void showProgress(double progress)"); hacker.insertAtBottomOfMethod("ij.IJ", "public static void showProgress(int currentIndex, int finalIndex)"); hacker.insertAtBottomOfMethod("ij.IJ", "public static void showStatus(java.lang.String s)"); hacker.insertPrivateStaticField("ij.IJ", Context.class, "_context"); hacker.insertNewMethod("ij.IJ", "public synchronized static org.scijava.Context getContext()", "if (_context == null) _context = new org.scijava.Context();" + "return _context;"); hacker.insertAtTopOfMethod("ij.IJ", "public static Object runPlugIn(java.lang.String className, java.lang.String arg)", "if (\"" + LegacyService.class.getName() + "\".equals($1))" + " return getLegacyService();" + "if (\"" + Context.class.getName() + "\".equals($1))" + " return getContext();"); hacker.insertAtTopOfMethod("ij.IJ", "public static void log(java.lang.String message)"); hacker.insertAtTopOfMethod("ij.IJ", "static java.lang.Object runUserPlugIn(java.lang.String commandName, java.lang.String className, java.lang.String arg, boolean createNewLoader)", "if (classLoader != null) Thread.currentThread().setContextClassLoader(classLoader);"); // override behavior of ij.ImagePlus hacker.insertAtBottomOfMethod("ij.ImagePlus", "public void updateAndDraw()"); hacker.insertAtBottomOfMethod("ij.ImagePlus", "public void repaintWindow()"); hacker.insertAtBottomOfMethod("ij.ImagePlus", "public void show(java.lang.String statusMessage)"); hacker.insertAtBottomOfMethod("ij.ImagePlus", "public void hide()"); hacker.insertAtBottomOfMethod("ij.ImagePlus", "public void close()"); // override behavior of ij.gui.ImageWindow hacker.insertNewMethod("ij.gui.ImageWindow", "public void setVisible(boolean vis)"); hacker.insertAtTopOfMethod("ij.gui.ImageWindow", "public void setVisible(boolean vis)", "if ($isLegacyMode()) { super.setVisible($1); }"); hacker.insertNewMethod("ij.gui.ImageWindow", "public void show()"); hacker.insertAtTopOfMethod("ij.gui.ImageWindow", "public void show()", "if ($isLegacyMode()) { super.show(); }"); hacker.insertAtTopOfMethod("ij.gui.ImageWindow", "public void close()"); // override behavior of PluginClassLoader hacker.insertAtTopOfMethod("ij.io.PluginClassLoader", "void init(java.lang.String path)"); // override behavior of ij.macro.Functions hacker .insertAtTopOfMethod("ij.macro.Functions", "void displayBatchModeImage(ij.ImagePlus imp2)", "imagej.legacy.patches.FunctionsMethods.displayBatchModeImageBefore($service, $1);"); hacker .insertAtBottomOfMethod("ij.macro.Functions", "void displayBatchModeImage(ij.ImagePlus imp2)", "imagej.legacy.patches.FunctionsMethods.displayBatchModeImageAfter($service, $1);"); // override behavior of MacAdapter, if needed if (ClassUtils.hasClass("com.apple.eawt.ApplicationListener")) { // NB: If com.apple.eawt package is present, override IJ1's MacAdapter. hacker.insertAtTopOfMethod("MacAdapter", "public void run(java.lang.String arg)", "if (!$isLegacyMode()) return;"); } // override behavior of ij.plugin.frame.RoiManager hacker.insertNewMethod("ij.plugin.frame.RoiManager", "public void show()", "if ($isLegacyMode()) { super.show(); }"); hacker.insertNewMethod("ij.plugin.frame.RoiManager", "public void setVisible(boolean b)", "if ($isLegacyMode()) { super.setVisible($1); }"); // Below are patches to make ImageJ 1.x more backwards-compatible // add back the (deprecated) killProcessor(), and overlay methods final String[] imagePlusMethods = { "public void killProcessor()", "{}", "public void setDisplayList(java.util.Vector list)", "getCanvas().setDisplayList(list);", "public java.util.Vector getDisplayList()", "return getCanvas().getDisplayList();", "public void setDisplayList(ij.gui.Roi roi, java.awt.Color strokeColor," + " int strokeWidth, java.awt.Color fillColor)", "setOverlay(roi, strokeColor, strokeWidth, fillColor);" }; for (int i = 0; i < imagePlusMethods.length; i++) try { hacker.insertNewMethod("ij.ImagePlus", imagePlusMethods[i], imagePlusMethods[++i]); } catch (Exception e) { /* ignore */ } // make sure that ImageJ has been initialized in batch mode hacker.insertAtTopOfMethod("ij.IJ", "public static java.lang.String runMacro(java.lang.String macro, java.lang.String arg)", "if (ij==null && ij.Menus.getCommands()==null) init();"); try { hacker.insertNewMethod("ij.CompositeImage", "public ij.ImagePlus[] splitChannels(boolean closeAfter)", "ij.ImagePlus[] result = ij.plugin.ChannelSplitter.split(this);" + "if (closeAfter) close();" + "return result;"); hacker.insertNewMethod("ij.plugin.filter.RGBStackSplitter", "public static ij.ImagePlus[] splitChannelsToArray(ij.ImagePlus imp, boolean closeAfter)", "if (!imp.isComposite()) {" + " ij.IJ.error(\"splitChannelsToArray was called on a non-composite image\");" + " return null;" + "}" + "ij.ImagePlus[] result = ij.plugin.ChannelSplitter.split(imp);" + "if (closeAfter)" + " imp.close();" + "return result;"); } catch (IllegalArgumentException e) { final Throwable cause = e.getCause(); if (cause != null && !(cause instanceof DuplicateMemberException)) { throw e; } } // handle mighty mouse (at least on old Linux, Java mistakes the horizontal wheel for a popup trigger) for (String fullClass : new String[] { "ij.gui.ImageCanvas", "ij.plugin.frame.RoiManager", "ij.text.TextPanel", "ij.gui.Toolbar" }) { hacker.handleMightyMousePressed(fullClass); } // tell IJ#runUserPlugIn to catch NoSuchMethodErrors final String runUserPlugInSig = "static java.lang.Object runUserPlugIn(java.lang.String commandName, java.lang.String className, java.lang.String arg, boolean createNewLoader)"; hacker.addCatch("ij.IJ", runUserPlugInSig, "java.lang.NoSuchMethodError", "if (" + IJ1Helper.class.getName() + ".handleNoSuchMethodError($e))" + " throw new RuntimeException(ij.Macro.MACRO_CANCELED);" + "throw $e;"); // tell IJ#runUserPlugIn to be more careful about catching NoClassDefFoundError hacker.insertPrivateStaticField("ij.IJ", String.class, "originalClassName"); hacker.insertAtTopOfMethod("ij.IJ", runUserPlugInSig, "originalClassName = $2;"); hacker.insertAtTopOfExceptionHandlers("ij.IJ", runUserPlugInSig, "java.lang.NoClassDefFoundError", "java.lang.String realClassName = $1.getMessage();" + "int spaceParen = realClassName.indexOf(\" (\");" + "if (spaceParen > 0) realClassName = realClassName.substring(0, spaceParen);" + "if (!originalClassName.replace('.', '/').equals(realClassName)) {" + " if (realClassName.startsWith(\"javax/vecmath/\") || realClassName.startsWith(\"com/sun/j3d/\") || realClassName.startsWith(\"javax/media/j3d/\"))" + " ij.IJ.error(\"The class \" + originalClassName + \" did not find Java3D (\" + realClassName + \")\\nPlease call Plugins>3D Viewer to install\");" + " else" + " ij.IJ.handleException($1);" + " return null;" + "}"); // let the plugin class loader find stuff in $HOME/.plugins, too hacker.addExtraPlugins(); // make sure that the GenericDialog is disposed in macro mode try { hacker.insertAtTopOfMethod("ij.gui.GenericDialog", "public void showDialog()", "if (macro) dispose();"); } catch (IllegalArgumentException e) { // ignore if the headless patcher renamed the method away if (e.getCause() == null || !(e.getCause() instanceof NotFoundException)) { throw e; } } // make sure NonBlockingGenericDialog does not wait in macro mode hacker.replaceCallInMethod("ij.gui.NonBlockingGenericDialog", "public void showDialog()", "java.lang.Object", "wait", "if (isShowing()) wait();"); // tell the showStatus() method to show the version() instead of empty status hacker.insertAtTopOfMethod("ij.ImageJ", "void showStatus(java.lang.String s)", "if ($1 == null || \"\".equals($1)) $1 = version();"); // handle custom icon (e.g. for Fiji) if (!hacker.hasField("ij.IJ", "_iconURL")) { // Fiji will already have called CodeHacker#setIcon(File icon) hacker.insertPublicStaticField("ij.IJ", URL.class, "_iconURL", null); } hacker.replaceCallInMethod("ij.ImageJ", "void setIcon()", "java.lang.Class", "getResource", "if (ij.IJ._iconURL == null) $_ = $0.getResource($1);" + "else $_ = ij.IJ._iconURL;"); hacker.insertAtTopOfMethod("ij.ImageJ", "public <init>(java.applet.Applet applet, int mode)", "if ($2 != 2 /* ij.ImageJ.NO_SHOW */) setIcon();"); hacker.insertAtTopOfMethod("ij.WindowManager", "public void addWindow(java.awt.Frame window)", "if (ij.IJ._iconURL != null && $1 != null) {" + " java.awt.Image img = $1.createImage((java.awt.image.ImageProducer)ij.IJ._iconURL.getContent());" + " if (img != null) {" + " $1.setIconImage(img);" + " }" + "}"); // optionally disallow batch mode from calling System.exit() hacker.insertPrivateStaticField("ij.ImageJ", Boolean.TYPE, "batchModeMayExit"); hacker.insertAtTopOfMethod("ij.ImageJ", "public static void main(java.lang.String[] args)", "batchModeMayExit = true;" + "for (int i = 0; i < $1.length; i++) {" + " if (\"-batch-no-exit\".equals($1[i])) {" + " batchModeMayExit = false;" + " $1[i] = \"-batch\";" + " }" + "}"); hacker.replaceCallInMethod("ij.ImageJ", "public static void main(java.lang.String[] args)", "java.lang.System", "exit", "if (batchModeMayExit) System.exit($1);" + "if ($1 == 0) return;" + "throw new RuntimeException(\"Exit code: \" + $1);"); // do not use the current directory as IJ home on Windows String prefsDir = System.getenv("IJ_PREFS_DIR"); if (prefsDir == null && System.getProperty("os.name").startsWith("Windows")) { prefsDir = System.getenv("user.home"); } if (prefsDir != null) { hacker.overrideFieldWrite("ij.Prefs", "public java.lang.String load(java.lang.Object ij, java.applet.Applet applet)", "prefsDir", "$_ = \"" + prefsDir + "\";"); } // tool names can be prefixes of other tools, watch out for that! hacker.replaceCallInMethod("ij.gui.Toolbar", "public int getToolId(java.lang.String name)", "java.lang.String", "startsWith", "$_ = $0.equals($1) || $0.startsWith($1 + \"-\") || $0.startsWith($1 + \" -\");"); // make sure Rhino gets the correct class loader hacker.insertAtTopOfMethod("JavaScriptEvaluator", "public void run()", "Thread.currentThread().setContextClassLoader(ij.IJ.getClassLoader());"); // make sure that the check for Bio-Formats is correct hacker.addToClassInitializer("ij.io.Opener", "try {" + " ij.IJ.getClassLoader().loadClass(\"loci.plugins.LociImporter\");" + " bioformats = true;" + "} catch (ClassNotFoundException e) {" + " bioformats = false;" + "}"); // make sure that symbolic links are *not* resolved (because then the parent info in the FileInfo would be wrong) hacker.replaceCallInMethod("ij.plugin.DragAndDrop", "public void openFile(java.io.File f)", "java.io.File", "getCanonicalPath", "$_ = $0.getAbsolutePath();"); // make sure no dialog is opened in headless mode hacker.insertAtTopOfMethod("ij.macro.Interpreter", "void showError(java.lang.String title, java.lang.String msg, java.lang.String[] variables)", "if (ij.IJ.getInstance() == null) {" + " java.lang.System.err.println($1 + \": \" + $2);" + " return;" + "}"); // let IJ.handleException override the macro interpreter's call()'s exception handling hacker.insertAtTopOfExceptionHandlers("ij.macro.Functions", "java.lang.String call()", "java.lang.reflect.InvocationTargetException", "ij.IJ.handleException($1);" + "return null;"); // Add back the "Convert to 8-bit Grayscale" checkbox to Import>Image Sequence if (!hacker.hasField("ij.plugin.FolderOpener", "convertToGrayscale")) { hacker.insertPrivateStaticField("ij.plugin.FolderOpener", Boolean.TYPE, "convertToGrayscale"); hacker.replaceCallInMethod("ij.plugin.FolderOpener", "public void run(java.lang.String arg)", "ij.io.Opener", "openImage", "$_ = $0.openImage($1, $2);" + "if (convertToGrayscale)" + " ij.IJ.run($_, \"8-bit\", \"\");"); hacker.replaceCallInMethod("ij.plugin.FolderOpener", "boolean showDialog(ij.ImagePlus imp, java.lang.String[] list)", "ij.gui.GenericDialog", "addCheckbox", "i$0.addCheckbox(\"Convert to 8-bit Grayscale\", convertToGrayscale);" + "$0.addCheckbox($1, $2);", 1); hacker.replaceCallInMethod("ij.plugin.FolderOpener", "boolean showDialog(ij.ImagePlus imp, java.lang.String[] list)", "ij.gui.GenericDialog", "getNextBoolean", "convertToGrayscale = $0.getNextBoolean();" + "$_ = $0.getNextBoolean();" + "if (convertToGrayscale && $_) {" + " ij.IJ.error(\"Cannot convert to grayscale and RGB at the same time.\");" + " return false;" + "}", 1); } // commit patches hacker.loadClasses(); // make sure that there is a legacy service if (this.hacker != null) { setLegacyService(new DummyLegacyService()); } } void setLegacyService(final LegacyService legacyService) { try { final Class<?> ij = hacker.classLoader.loadClass("ij.IJ"); Field field = ij.getDeclaredField("_legacyService"); field.setAccessible(true); field.set(null, legacyService); Context context; try { context = legacyService.getContext(); } catch (UnsupportedOperationException e) { // DummyLegacyService does not have a context context = null; } field = ij.getDeclaredField("_context"); field.setAccessible(true); field.set(null, context); } catch (ClassNotFoundException e) { throw new IllegalArgumentException("Cannot find ij.IJ", e); } catch (SecurityException e) { throw new IllegalArgumentException("Cannot find ij.IJ", e); } catch (NoSuchFieldException e) { throw new IllegalArgumentException("Cannot find field in ij.IJ", e); } catch (IllegalAccessException e) { throw new IllegalArgumentException("Cannot access field in ij.IJ", e); } } }
package net.time4j.format; import net.time4j.engine.AttributeQuery; import net.time4j.engine.ChronoElement; import net.time4j.engine.ChronoEntity; import net.time4j.engine.ChronoValues; import java.io.IOException; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.Map; import java.util.Set; /** * <p>Fraktionale Formatierung eines Sekundenbruchteils. </p> * * @author Meno Hochschild * @concurrency <immutable> */ final class FractionProcessor implements FormatProcessor<Integer> { private static final Integer MRD_MINUS_1 = Integer.valueOf(999999999); private final FormatProcessor<Void> decimalSeparator; private final ChronoElement<Integer> element; private final int minDigits; private final int maxDigits; private final boolean fixedWidth; /** * <p>Konstruiert eine neue Instanz. </p> * * @param element element to be formatted in a fractional way * @param minDigits minimum count of digits * @param maxDigits maximum count of digits * @param decimalSeparator shall decimal separator be visible? */ FractionProcessor( ChronoElement<Integer> element, int minDigits, int maxDigits, boolean decimalSeparator ) { super(); this.element = element; this.minDigits = minDigits; this.maxDigits = maxDigits; this.fixedWidth = (!decimalSeparator && (minDigits == maxDigits)); this.decimalSeparator = ( decimalSeparator ? new LiteralProcessor(Attributes.DECIMAL_SEPARATOR) : null); if (element == null) { throw new NullPointerException("Missing element."); } else if (minDigits < 0) { throw new IllegalArgumentException( "Negative min digits: " + minDigits); } else if (minDigits > maxDigits) { throw new IllegalArgumentException( "Max smaller than min: " + maxDigits + " < " + minDigits); } if (minDigits > 9) { throw new IllegalArgumentException( "Min digits out of range: " + minDigits); } else if (maxDigits > 9) { throw new IllegalArgumentException( "Max digits out of range: " + maxDigits); } } @Override public void print( ChronoValues formattable, Appendable buffer, AttributeQuery attributes, Set<ElementPosition> positions, // optional FormatStep step ) throws IOException { BigDecimal value = toDecimal(formattable.get(this.element)); BigDecimal min = toDecimal(formattable.getMinimum(this.element)); BigDecimal max = toDecimal(formattable.getMaximum(this.element)); if (value.compareTo(max) > 0) { value = max; } BigDecimal fraction = value.subtract(min).divide( max.subtract(min).add(BigDecimal.ONE), 9, RoundingMode.FLOOR); fraction = ( (fraction.compareTo(BigDecimal.ZERO) == 0) ? BigDecimal.ZERO : fraction.stripTrailingZeros() ); char zeroDigit = step.getAttribute( Attributes.ZERO_DIGIT, attributes, Character.valueOf('0') ).charValue(); int start = -1; int printed = 0; if (buffer instanceof CharSequence) { start = ((CharSequence) buffer).length(); } if (fraction.scale() == 0) { // scale ist 0, wenn value das Minimum ist if (this.minDigits > 0) { if (this.decimalSeparator != null) { this.decimalSeparator.print( formattable, buffer, attributes, positions, step); printed++; } for (int i = 0; i < this.minDigits; i++) { buffer.append(zeroDigit); } printed += this.minDigits; } } else { if (this.decimalSeparator != null) { this.decimalSeparator.print( formattable, buffer, attributes, positions, step); printed++; } int outputScale = Math.min( Math.max(fraction.scale(), this.minDigits), this.maxDigits); fraction = fraction.setScale(outputScale, RoundingMode.FLOOR); String digits = fraction.toPlainString(); int diff = zeroDigit - '0'; for (int i = 2, n = digits.length(); i < n; i++) { char c = (char) (digits.charAt(i) + diff); buffer.append(c); printed++; } } if ( (start != -1) && (printed > 1) && (positions != null) ) { positions.add( new ElementPosition(this.element, start + 1, start + printed)); } } @Override public void parse( CharSequence text, ParseLog status, AttributeQuery attributes, Map<ChronoElement<?>, Object> parsedResult, FormatStep step ) { Leniency leniency = step.getAttribute( Attributes.LENIENCY, attributes, Leniency.SMART); int effectiveMin = 0; int effectiveMax = 9; if ( !leniency.isLax() || this.fixedWidth ) { effectiveMin = this.minDigits; effectiveMax = this.maxDigits; } int len = text.length(); if (status.getPosition() >= len) { if (effectiveMin > 0) { status.setError( status.getPosition(), "Expected fraction digits not found for: " + this.element.name()); } return; } if (this.decimalSeparator != null) { this.decimalSeparator.parse( text, status, attributes, null, step); if (status.isError()) { if (effectiveMin == 0) { status.clearError(); } return; } } int current = status.getPosition(); int minEndPos = current + effectiveMin; int maxEndPos = Math.min(current + effectiveMax, len); if (minEndPos > len) { status.setError( status.getPosition(), "Expected at least " + effectiveMin + " digits."); return; } char zeroDigit = step.getAttribute( Attributes.ZERO_DIGIT, attributes, Character.valueOf('0') ).charValue(); long total = 0; while (current < maxEndPos) { int digit = text.charAt(current) - zeroDigit; if ((digit >= 0) && (digit <= 9)) { total = total * 10 + digit; current++; } else if (current < minEndPos) { status.setError( status.getPosition(), "Expected at least " + effectiveMin + " digits."); return; } else { break; } } BigDecimal fraction = new BigDecimal(total); fraction = fraction.movePointLeft(current - status.getPosition()); if (this.element.name().equals("NANO_OF_SECOND")) { Integer min = Integer.valueOf(0); Integer max = MRD_MINUS_1; Integer num = this.getRealValue(fraction, min, max); parsedResult.put(this.element, num); } else { parsedResult.put(FractionalElement.FRACTION, fraction); parsedResult.put(this.element, this.element.getDefaultMinimum()); } status.setPosition(current); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } else if (obj instanceof FractionProcessor) { FractionProcessor that = (FractionProcessor) obj; return ( this.element.equals(that.element) && (this.minDigits == that.minDigits) && (this.maxDigits == that.maxDigits) ); } else { return false; } } @Override public int hashCode() { return ( 7 * this.element.hashCode() + 31 * (this.minDigits + this.maxDigits * 10) ); } @Override public String toString() { StringBuilder sb = new StringBuilder(64); sb.append(this.getClass().getName()); sb.append("[element="); sb.append(this.element.name()); sb.append(", min-digits="); sb.append(this.minDigits); sb.append(", max-digits="); sb.append(this.maxDigits); sb.append(']'); return sb.toString(); } @Override public ChronoElement<Integer> getElement() { return this.element; } @Override public FormatProcessor<Integer> withElement( ChronoElement<Integer> element ) { if (this.element == element) { return this; } return new FractionProcessor( element, this.minDigits, this.maxDigits, (this.decimalSeparator != null) ); } @Override public boolean isNumerical() { return true; } /** * <p>Aktualisiert das prototypische Parse-Ergebnis mit dem richtigen * Wert. </p> * * <p>In der ersten Phase wurde prototypisch nur das Standardminimum * des Elements als Wert angenommen. In dieser Phase wird stattdessen der * geparste {@code BigDecimal}-Wert in den neuen Elementwert * &uuml;bersetzt und damit das Ergebnis angepasst. </p> * * @param entity prototypical result of parsing * @param parsed intermediate buffer for parsed values * @return updated result object */ <T extends ChronoEntity<T>> T update( T entity, ParsedValues parsed ) { if (!parsed.contains(FractionalElement.FRACTION)) { return entity; } BigDecimal fraction = parsed.get(FractionalElement.FRACTION); Integer min = entity.getMinimum(this.element); Integer max = entity.getMaximum(this.element); Integer num = this.getRealValue(fraction, min, max); parsed.with(FractionalElement.FRACTION, null); // mutable parsed.with(this.element, num); // mutable return entity.with(this.element, num); } private Integer getRealValue( BigDecimal fraction, Integer min, Integer max ) { BigDecimal low = BigDecimal.valueOf(min.intValue()); BigDecimal range = BigDecimal.valueOf(max.intValue()) .subtract(low) .add(BigDecimal.ONE); BigDecimal value = fraction.multiply(range) .setScale(0, RoundingMode.FLOOR) .add(low); return Integer.valueOf(value.intValueExact()); } private static BigDecimal toDecimal(Number num) { return BigDecimal.valueOf(num.longValue()); } }
package be.ecam.ecalendar; public class CalendarType { private String id = null; private String description = null; CalendarType(String id, String description) { this.description = description; this.id = id; } public String getId() { return id;} public String getDescription() { return description;} }
package com.t28.rxweather; import android.content.Intent; import android.location.LocationManager; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import com.android.volley.RequestQueue; import com.t28.rxweather.data.model.Coordinate; import com.t28.rxweather.data.model.Forecast; import com.t28.rxweather.data.model.Photo; import com.t28.rxweather.data.model.PhotoSize; import com.t28.rxweather.data.model.Photos; import com.t28.rxweather.data.model.Weather; import com.t28.rxweather.data.service.FlickerService; import com.t28.rxweather.data.service.LocationService; import com.t28.rxweather.data.service.WeatherService; import com.t28.rxweather.volley.RequestQueueRetriever; import rx.Observable; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Func1; import rx.schedulers.Schedulers; public class MainActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override protected void onResume() { super.onResume(); final LocationManager manager = (LocationManager) getSystemService(LOCATION_SERVICE); final LocationService location = new LocationService(manager); final RequestQueue queue = RequestQueueRetriever.retrieve(); final FlickerService flicker = new FlickerService(queue); location.find() .subscribeOn(Schedulers.from(AsyncTask.THREAD_POOL_EXECUTOR)) .flatMap(new Func1<Coordinate, Observable<Photos>>() { @Override public Observable<Photos> call(Coordinate coordinate) { return flicker.searchPhotos(coordinate); } }) .compose(new Observable.Transformer<Photos, Photo>() { @Override public Observable<Photo> call(Observable<Photos> source) { return source.map(new Func1<Photos, Photo>() { @Override public Photo call(Photos photos) { return photos.getPhotos().get(0); } }); } }) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<Photo>() { @Override public void onCompleted() { } @Override public void onError(Throwable cause) { Log.d("TAG", "Thread:" + Thread.currentThread().getName()); Log.d("TAG", "onError:" + cause); } @Override public void onNext(Photo result) { Log.d("TAG", "Thread:" + Thread.currentThread().getName()); Log.d("TAG", "onNext:" + result.toImageUri(PhotoSize.MEDIUM)); final Intent intent = new Intent(Intent.ACTION_VIEW, result.toPhotoUri()); MainActivity.this.startActivity(intent); } }); final WeatherService weather = new WeatherService(queue); location.find() .subscribeOn(Schedulers.from(AsyncTask.THREAD_POOL_EXECUTOR)) .flatMap(new Func1<Coordinate, Observable<Weather>>() { @Override public Observable<Weather> call(Coordinate coordinate) { return weather.findWeather(coordinate); } }) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<Weather>() { @Override public void onCompleted() { } @Override public void onError(Throwable cause) { Log.d("TAG", "Thread:" + Thread.currentThread().getName()); Log.d("TAG", "onError:" + cause); } @Override public void onNext(Weather result) { Log.d("TAG", "Thread:" + Thread.currentThread().getName()); Log.d("TAG", "onNext:" + result); } }); location.find() .subscribeOn(Schedulers.from(AsyncTask.THREAD_POOL_EXECUTOR)) .flatMap(new Func1<Coordinate, Observable<Forecast>>() { @Override public Observable<Forecast> call(Coordinate coordinate) { return weather.findForecast(coordinate); } }) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<Forecast>() { @Override public void onCompleted() { } @Override public void onError(Throwable cause) { Log.d("TAG", "Thread:" + Thread.currentThread().getName()); Log.d("TAG", "onError:" + cause); } @Override public void onNext(Forecast result) { Log.d("TAG", "Thread:" + Thread.currentThread().getName()); Log.d("TAG", "onNext:" + result); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { final int itemId = item.getItemId(); if (itemId == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
package nl.svendubbeld.car; import android.app.Activity; import android.app.ActivityOptions; import android.app.AlertDialog; import android.app.UiModeManager; import android.content.ComponentName; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.ColorStateList; import android.graphics.Color; import android.location.GpsStatus; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.media.AudioManager; import android.media.MediaMetadata; import android.media.session.MediaController; import android.media.session.MediaSession; import android.media.session.MediaSessionManager; import android.media.session.PlaybackState; import android.net.Uri; import android.os.Bundle; import android.os.SystemClock; import android.preference.PreferenceManager; import android.provider.Settings; import android.support.v7.widget.CardView; import android.text.format.DateFormat; import android.util.Pair; import android.view.KeyEvent; import android.view.View; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.ScrollView; import android.widget.TextClock; import android.widget.TextView; import java.text.SimpleDateFormat; import java.util.List; public class CarActivity extends Activity implements LocationListener, GpsStatus.Listener, SharedPreferences.OnSharedPreferenceChangeListener, MediaSessionManager.OnActiveSessionsChangedListener, View.OnClickListener { public static final int PREF_SPEED_UNIT_KMH = 1; public static final int PREF_SPEED_UNIT_MPH = 2; public static final int PREF_SPEED_UNIT_MS = 0; public static final int PREF_TEMP_UNIT_C = 0; public static final int PREF_TEMP_UNIT_F = 1; // Background ScrollView mBackground; String mPrefBackground = "launcher"; // Buttons CardView mButtonDialer; CardView mButtonExit; CardView mButtonNavigation; CardView mButtonSettings; CardView mButtonSpeakNotifications; ImageView mButtonSpeakNotificationsIcon; CardView mButtonVoice; boolean mPrefSpeakNotifications = true; String mPrefAppsDialer = "default"; AlertDialog mNotificationListenerDialog; // Date CardView mDateContainer; TextClock mDate; TextClock mTime; boolean mPrefShowDate = true; // Media CardView mMediaContainer; ImageView mMediaArt; TextView mMediaTitle; TextView mMediaArtist; TextView mMediaAlbum; ImageView mMediaVolDown; ImageView mMediaPrev; ImageView mMediaPlay; ProgressBar mMediaPlayProgress; ImageView mMediaNext; ImageView mMediaVolUp; MediaSessionManager mMediaSessionManager; MediaController mMediaController = null; boolean mPrefShowMedia = true; // Speed CardView mSpeedContainer; TextView mSpeed; TextView mSpeedUnit; int mPrefSpeedUnit = 1; boolean mPrefShowSpeed = true; UiModeManager mUiModeManager; Log mLog = new Log(); SharedPreferences mSharedPref; boolean mPrefKeepScreenOn = true; String mPrefNightMode = "auto"; // Location long mLastLocationMillis = 0l; LocationManager mLocationManager; private static final String LOCATION_PROVIDER = "gps"; private static final int GPS_UPDATE_INTERVAL = 1000; private static final int GPS_UPDATE_FIX_THRESHOLD = 2 * GPS_UPDATE_INTERVAL; private void resetLayout() { setContentView(R.layout.activity_car); // Get date views mDateContainer = ((CardView) findViewById(R.id.date_container)); mDate = ((TextClock) findViewById(R.id.date)); mTime = ((TextClock) findViewById(R.id.time)); // Get speed views mSpeedContainer = ((CardView) findViewById(R.id.speed_container)); mSpeed = ((TextView) findViewById(R.id.speed)); mSpeedUnit = ((TextView) findViewById(R.id.speed_unit)); // Get media views mMediaContainer = ((CardView) findViewById(R.id.media_container)); mMediaArt = ((ImageView) findViewById(R.id.media_art)); mMediaTitle = ((TextView) findViewById(R.id.media_title)); mMediaArtist = ((TextView) findViewById(R.id.media_artist)); mMediaAlbum = ((TextView) findViewById(R.id.media_album)); mMediaVolDown = ((ImageView) findViewById(R.id.media_vol_down)); mMediaPrev = ((ImageView) findViewById(R.id.media_prev)); mMediaPlay = ((ImageView) findViewById(R.id.media_play)); mMediaPlayProgress = ((ProgressBar) findViewById(R.id.media_play_progress)); mMediaNext = ((ImageView) findViewById(R.id.media_next)); mMediaVolUp = ((ImageView) findViewById(R.id.media_vol_up)); // Get buttons mButtonSettings = ((CardView) findViewById(R.id.btn_settings)); mButtonNavigation = ((CardView) findViewById(R.id.btn_navigation)); mButtonDialer = ((CardView) findViewById(R.id.btn_dialer)); mButtonVoice = ((CardView) findViewById(R.id.btn_voice)); mButtonSpeakNotifications = ((CardView) findViewById(R.id.btn_speak_notifications)); mButtonSpeakNotificationsIcon = ((ImageView) findViewById(R.id.btn_speak_notifications_icon)); mButtonExit = ((CardView) findViewById(R.id.btn_exit)); // Get background mBackground = ((ScrollView) findViewById(R.id.bg)); toggleDate(); toggleSpeed(); toggleMedia(); // Format the date String dateFormat = ((SimpleDateFormat) DateFormat.getMediumDateFormat(getApplicationContext())).toPattern(); mDate.setFormat12Hour(null); mDate.setFormat24Hour(dateFormat); // Set media controls mMediaVolDown.setOnClickListener(mMediaControlsListener); mMediaPrev.setOnClickListener(mMediaControlsListener); mMediaPlay.setOnClickListener(mMediaControlsListener); mMediaNext.setOnClickListener(mMediaControlsListener); mMediaVolUp.setOnClickListener(mMediaControlsListener); mMediaContainer.setOnClickListener(this); mMediaPlay.setImageTintList(ColorStateList.valueOf(getTheme().obtainStyledAttributes(new int[]{R.attr.cardBackgroundColor}).getColor(0, getResources().getColor(R.color.white)))); // Set buttons mButtonSettings.setOnClickListener(this); mButtonNavigation.setOnClickListener(this); mButtonDialer.setOnClickListener(this); mButtonVoice.setOnClickListener(this); mButtonSpeakNotifications.setOnClickListener(this); mButtonExit.setOnClickListener(this); mButtonSpeakNotificationsIcon.setBackgroundTintList(ColorStateList.valueOf(getTheme().obtainStyledAttributes(new int[]{android.R.attr.textColorSecondary}).getColor(0, getResources().getColor(android.R.color.secondary_text_light)))); toggleSpeakNotificationsIcon(); } private void toggleDate() { mDateContainer.setVisibility(mPrefShowDate ? View.VISIBLE : View.GONE); } private void toggleMedia() { mMediaContainer.setVisibility(mPrefShowMedia ? View.VISIBLE : View.GONE); } private void toggleNightMode() { switch (mPrefNightMode) { default: case "auto": mUiModeManager.setNightMode(UiModeManager.MODE_NIGHT_AUTO); break; case "always": mUiModeManager.setNightMode(UiModeManager.MODE_NIGHT_YES); break; case "never": mUiModeManager.setNightMode(UiModeManager.MODE_NIGHT_NO); break; } } private void toggleSpeakNotificationsIcon() { if (!mPrefSpeakNotifications) { mButtonSpeakNotificationsIcon.setBackgroundResource(R.drawable.ic_notification_do_not_disturb); mButtonSpeakNotificationsIcon.setImageAlpha(64); } else { this.mButtonSpeakNotificationsIcon.setBackground(null); this.mButtonSpeakNotificationsIcon.setImageAlpha(255); } } private void toggleSpeed() { mSpeedContainer.setVisibility(mPrefShowSpeed ? View.VISIBLE : View.GONE); switch (mPrefSpeedUnit) { case PREF_SPEED_UNIT_MS: mSpeedUnit.setText("m/s"); break; case PREF_SPEED_UNIT_KMH: mSpeedUnit.setText("km/h"); break; case PREF_SPEED_UNIT_MPH: mSpeedUnit.setText("mph"); break; default: mSpeedUnit.setText("km/h"); break; } } public void onActiveSessionsChanged(List<MediaController> controllers) { if (mMediaController != null) { mMediaController.unregisterCallback(mMediaCallback); mLog.d("MediaController", "MediaController removed"); mMediaController = null; } if (controllers.size() > 0) { mMediaController = controllers.get(0); mMediaController.registerCallback(mMediaCallback); mMediaCallback.onMetadataChanged(mMediaController.getMetadata()); mMediaCallback.onPlaybackStateChanged(mMediaController.getPlaybackState()); mLog.d("MediaController", "MediaController set: " + mMediaController.getPackageName()); } } public void onBackPressed() { mUiModeManager.disableCarMode(0); startActivity(new Intent(this, HomeActivity.class)); finish(); } public void onClick(View v) { switch (v.getId()) { case R.id.btn_settings: Intent settingsIntent = new Intent(this, SettingsActivity.class); startActivity(settingsIntent, ActivityOptions.makeScaleUpAnimation(v, 0, 0, v.getWidth(), v.getWidth()).toBundle()); break; case R.id.btn_navigation: launchNavigation(v); break; case R.id.btn_dialer: launchDialer(v); break; case R.id.btn_voice: Intent voiceIntent = new Intent("android.intent.action.VOICE_ASSIST"); startActivity(voiceIntent); break; case R.id.btn_speak_notifications: mSharedPref.edit().putBoolean("pref_key_speak_notifications", !mPrefSpeakNotifications).apply(); break; case R.id.btn_exit: mUiModeManager.disableCarMode(0); startActivity(new Intent(this, HomeActivity.class)); finish(); break; case R.id.media_container: Intent mediaIntent = new Intent(this, MediaActivity.class); Pair[] elements = new Pair[9]; elements[0] = Pair.create((View) mMediaArt, getString(R.string.transition_media_art)); elements[1] = Pair.create((View) mMediaTitle, getString(R.string.transition_media_title)); elements[2] = Pair.create((View) mMediaArtist, getString(R.string.transition_media_artist)); elements[3] = Pair.create((View) mMediaAlbum, getString(R.string.transition_media_album)); elements[4] = Pair.create((View) mMediaVolDown, getString(R.string.transition_media_vol_down)); elements[5] = Pair.create((View) mMediaPrev, getString(R.string.transition_media_prev)); if (mMediaPlay.getVisibility() == View.VISIBLE) { elements[6] = Pair.create((View) mMediaPlay, getString(R.string.transition_media_play)); } else if (mMediaPlayProgress.getVisibility() == View.VISIBLE) { elements[6] = Pair.create((View) mMediaPlayProgress, getString(R.string.transition_media_play_progress)); } elements[7] = Pair.create((View) mMediaNext, getString(R.string.transition_media_next)); elements[8] = Pair.create((View) mMediaVolUp, getString(R.string.transition_media_vol_up)); startActivity(mediaIntent, ActivityOptions.makeSceneTransitionAnimation(this, elements).toBundle()); break; } } private void launchNavigation(View source) { Intent navigationIntent = new Intent("android.intent.action.VIEW", Uri.parse("geo:")); startActivity(navigationIntent, ActivityOptions.makeScaleUpAnimation(source, 0, 0, source.getWidth(), source.getWidth()).toBundle()); } private void launchDialer(View source) { switch (mPrefAppsDialer) { case "default": Intent defaultIntent = new Intent("android.intent.action.DIAL"); startActivity(defaultIntent, ActivityOptions.makeScaleUpAnimation(source, 0, 0, source.getWidth(), source.getWidth()).toBundle()); break; case "builtin": Intent builtinIntent = new Intent(this, DialerActivity.class); startActivity(builtinIntent, ActivityOptions.makeSceneTransitionAnimation(this, source, getString(R.string.transition_button_dialer)).toBundle()); break; } } protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().getDecorView().setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION); getWindow().setStatusBarColor(Color.TRANSPARENT); getWindow().setNavigationBarColor(Color.TRANSPARENT); mSharedPref = PreferenceManager.getDefaultSharedPreferences(this); mPrefShowDate = mSharedPref.getBoolean("pref_key_show_date", true); mPrefShowSpeed = mSharedPref.getBoolean("pref_key_show_speed", true); mPrefShowMedia = mSharedPref.getBoolean("pref_key_show_media", true); mPrefSpeakNotifications = mSharedPref.getBoolean("pref_key_speak_notifications", true); mPrefKeepScreenOn = mSharedPref.getBoolean("pref_key_keep_screen_on", true); mPrefNightMode = mSharedPref.getString("pref_key_night_mode", "auto"); mPrefSpeedUnit = Integer.parseInt(mSharedPref.getString("pref_key_unit_speed", "1")); mPrefBackground = mSharedPref.getString("pref_key_color_bg", "launcher"); mPrefAppsDialer = mSharedPref.getString("pref_key_dialer", "default"); mUiModeManager = ((UiModeManager) getSystemService(UI_MODE_SERVICE)); mUiModeManager.enableCarMode(mPrefKeepScreenOn ? 0 : UiModeManager.ENABLE_CAR_MODE_ALLOW_SLEEP); mNotificationListenerDialog = new AlertDialog.Builder(this) .setTitle(R.string.dialog_notification_access_title) .setMessage(R.string.dialog_notification_access_message) .setPositiveButton(R.string.dialog_notification_access_positive, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { startActivity(new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS")); dialog.dismiss(); } }) .setNegativeButton(R.string.dialog_notification_access_negative, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { mSharedPref.edit().putBoolean("pref_key_show_media", false).putBoolean("pref_key_speak_notifications", false).apply(); dialog.dismiss(); } }) .setCancelable(false) .create(); toggleNightMode(); resetLayout(); } protected void onDestroy() { super.onDestroy(); mLocationManager.removeUpdates(this); mUiModeManager.disableCarMode(UiModeManager.DISABLE_CAR_MODE_GO_HOME); } public void onGpsStatusChanged(int event) { } public void onLocationChanged(Location location) { float rawSpeed = location.getSpeed(); String speed = " if (rawSpeed > 1.0f) { switch (mPrefSpeedUnit) { default: rawSpeed *= 3.6f; break; case PREF_SPEED_UNIT_MS: break; case PREF_SPEED_UNIT_KMH: rawSpeed *= 3.6f; break; case PREF_SPEED_UNIT_MPH: rawSpeed /= 0.44704f; break; } speed = Integer.toString(Math.round(rawSpeed)); } mSpeed.setText(speed); mLastLocationMillis = SystemClock.elapsedRealtime(); } protected void onPause() { super.onPause(); if (mPrefShowMedia) { mMediaSessionManager.removeOnActiveSessionsChangedListener(this); if (mMediaController != null) { mMediaController.unregisterCallback(mMediaCallback); mLog.d("MediaController", "MediaController removed"); } } mSharedPref.unregisterOnSharedPreferenceChangeListener(this); } public void onProviderDisabled(String provider) { } public void onProviderEnabled(String provider) { } protected void onResume() { super.onResume(); mSharedPref.registerOnSharedPreferenceChangeListener(this); mPrefShowDate = mSharedPref.getBoolean("pref_key_show_date", true); mPrefShowSpeed = mSharedPref.getBoolean("pref_key_show_speed", true); mPrefShowMedia = mSharedPref.getBoolean("pref_key_show_media", true); mPrefSpeakNotifications = mSharedPref.getBoolean("pref_key_speak_notifications", true); mPrefKeepScreenOn = mSharedPref.getBoolean("pref_key_keep_screen_on", true); mPrefNightMode = mSharedPref.getString("pref_key_night_mode", "auto"); mPrefSpeedUnit = Integer.parseInt(mSharedPref.getString("pref_key_unit_speed", "1")); mPrefBackground = mSharedPref.getString("pref_key_color_bg", "launcher"); mPrefAppsDialer = mSharedPref.getString("pref_key_dialer", "default"); mUiModeManager.enableCarMode(mPrefKeepScreenOn ? 0 : UiModeManager.ENABLE_CAR_MODE_ALLOW_SLEEP); toggleDate(); toggleSpeed(); toggleMedia(); toggleNightMode(); toggleSpeakNotificationsIcon(); mLocationManager = ((LocationManager) getSystemService(LOCATION_SERVICE)); if (!mLocationManager.isProviderEnabled(LOCATION_PROVIDER)) { startActivity(new Intent("android.settings.LOCATION_SOURCE_SETTINGS")); } mLocationManager.requestLocationUpdates(LOCATION_PROVIDER, GPS_UPDATE_INTERVAL, 0.0f, this); Location location = mLocationManager.getLastKnownLocation(LOCATION_PROVIDER); if (location != null) { onLocationChanged(location); } if (mPrefShowMedia || mPrefSpeakNotifications) { String enabledNotificationListeners = Settings.Secure.getString(getContentResolver(), "enabled_notification_listeners"); if (enabledNotificationListeners == null || !enabledNotificationListeners.contains(getPackageName())) { if (!mNotificationListenerDialog.isShowing()) { mNotificationListenerDialog.show(); } } } if (mPrefShowMedia) { try { mMediaSessionManager = (MediaSessionManager) getSystemService(MEDIA_SESSION_SERVICE); List<MediaController> controllers = mMediaSessionManager.getActiveSessions(new ComponentName(this, NotificationListener.class)); if (controllers.size() > 0) { mMediaController = controllers.get(0); mMediaController.registerCallback(mMediaCallback); mMediaCallback.onMetadataChanged(mMediaController.getMetadata()); mMediaCallback.onPlaybackStateChanged(mMediaController.getPlaybackState()); mLog.d("MediaController", "MediaController set: " + mMediaController.getPackageName()); } mMediaSessionManager.addOnActiveSessionsChangedListener(this, new ComponentName(this, NotificationListener.class)); } catch (SecurityException localSecurityException) { mLog.w("NotificationListener", "No Notification Access"); } } } public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { switch (key) { case "pref_key_show_date": mPrefShowDate = sharedPreferences.getBoolean("pref_key_show_date", true); toggleDate(); break; case "pref_key_show_speed": mPrefShowSpeed = sharedPreferences.getBoolean("pref_key_show_speed", true); toggleSpeed(); break; case "pref_key_keep_screen_on": mPrefKeepScreenOn = sharedPreferences.getBoolean("pref_key_keep_screen_on", true); mUiModeManager.enableCarMode(mPrefKeepScreenOn ? 0 : UiModeManager.ENABLE_CAR_MODE_ALLOW_SLEEP); break; case "pref_key_show_media": mPrefShowMedia = sharedPreferences.getBoolean("pref_key_show_media", true); toggleMedia(); break; case "pref_key_speak_notifications": mPrefSpeakNotifications = sharedPreferences.getBoolean("pref_key_speak_notifications", true); if (mPrefSpeakNotifications) { String enabledNotificationListeners = Settings.Secure.getString(getContentResolver(), "enabled_notification_listeners"); if ((enabledNotificationListeners == null) || (!enabledNotificationListeners.contains(getPackageName()))) { mLog.w("NotificationListener", "No Notification Access"); if (!mNotificationListenerDialog.isShowing()) { mNotificationListenerDialog.show(); } } } toggleSpeakNotificationsIcon(); break; case "pref_key_night_mode": mPrefNightMode = sharedPreferences.getString("pref_key_night_mode", "auto"); toggleNightMode(); break; case "pref_key_dialer": mPrefAppsDialer = sharedPreferences.getString("pref_key_dialer", "default"); break; } } public void onStatusChanged(String provider, int status, Bundle extras) { } MediaController.Callback mMediaCallback = new MediaController.Callback() { public void onAudioInfoChanged(MediaController.PlaybackInfo playbackInfo) { super.onAudioInfoChanged(playbackInfo); } public void onMetadataChanged(MediaMetadata metadata) { super.onMetadataChanged(metadata); if ((mMediaArt != null) && (metadata != null)) { mMediaArt.setImageBitmap(metadata.getBitmap(MediaMetadata.METADATA_KEY_ALBUM_ART)); mMediaTitle.setText(metadata.getText(MediaMetadata.METADATA_KEY_TITLE)); mMediaArtist.setText(metadata.getText(MediaMetadata.METADATA_KEY_ARTIST)); mMediaAlbum.setText(metadata.getText(MediaMetadata.METADATA_KEY_ALBUM)); } } public void onPlaybackStateChanged(PlaybackState state) { super.onPlaybackStateChanged(state); if ((mMediaPlay != null) && (state != null)) { switch (state.getState()) { case PlaybackState.STATE_BUFFERING: case PlaybackState.STATE_CONNECTING: mMediaPlay.setVisibility(View.GONE); mMediaPlayProgress.setVisibility(View.VISIBLE); mMediaPlay.setImageResource(R.drawable.ic_av_pause); break; case PlaybackState.STATE_PLAYING: mMediaPlay.setVisibility(View.VISIBLE); mMediaPlayProgress.setVisibility(View.GONE); mMediaPlay.setImageResource(R.drawable.ic_av_pause); break; default: mMediaPlay.setVisibility(View.VISIBLE); mMediaPlayProgress.setVisibility(View.GONE); mMediaPlay.setImageResource(R.drawable.ic_av_play_arrow); break; } } } public void onQueueChanged(List<MediaSession.QueueItem> queue) { super.onQueueChanged(queue); } public void onQueueTitleChanged(CharSequence title) { super.onQueueTitleChanged(title); } }; View.OnClickListener mMediaControlsListener = new View.OnClickListener() { public void onClick(View v) { if (mMediaController != null) { switch (v.getId()) { case R.id.media_vol_down: mMediaController.adjustVolume(AudioManager.ADJUST_LOWER, 0); break; case R.id.media_prev: mMediaController.getTransportControls().skipToPrevious(); break; case R.id.media_play: switch (mMediaController.getPlaybackState().getState()) { case PlaybackState.STATE_BUFFERING: case PlaybackState.STATE_CONNECTING: mMediaPlay.setVisibility(View.GONE); mMediaPlayProgress.setVisibility(View.VISIBLE); case PlaybackState.STATE_PLAYING: mMediaController.getTransportControls().pause(); break; default: mMediaController.getTransportControls().play(); break; } break; case R.id.media_next: mMediaController.getTransportControls().skipToNext(); break; case R.id.media_vol_up: mMediaController.adjustVolume(AudioManager.ADJUST_RAISE, 0); break; } } else { Intent mediaIntent = new Intent("android.intent.action.MEDIA_BUTTON"); mediaIntent.putExtra("android.intent.extra.KEY_EVENT", new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_PLAY)); sendOrderedBroadcast(mediaIntent, null); mediaIntent.putExtra("android.intent.extra.KEY_EVENT", new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MEDIA_PLAY)); sendOrderedBroadcast(mediaIntent, null); mMediaPlay.setVisibility(View.GONE); mMediaPlayProgress.setVisibility(View.VISIBLE); } } }; }
import javafx.scene.control.Tab; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * DiveTable class * @author David A. */ public class DiveTable { // Table 1: Mapping depth (in ft.) to another map of dive time minutes mapped to pressure group. Map<Integer, Map<Integer, TableOneCellOutput>> endOfDiveTable = new LinkedHashMap<Integer, Map<Integer, TableOneCellOutput>>(); // Table 2: Mapping Pressure Group to another map of surface interval minutes mapped to pressure group. Map<String, Map<Integer, String>> surfaceIntervalTimeTable = new LinkedHashMap<String, Map<Integer, String>>(); // Table 3: Mapping Pressure Group to another map of depth mapped to an array of Residual Nitrogen Times and Max Dive Times. Map<String, Map<Integer, Integer[]>> repetitiveDiveTimeTable = new LinkedHashMap<String, Map<Integer, Integer[]>>(); Map<Integer, SingleDiveData> diveResultsMap = new LinkedHashMap<Integer, SingleDiveData>(); //If 0, no errors with input dive data. If > 0, the number indicates which dive# the FIRST error occurred at. //Can then use this number on diveResultsMap to grab the actual error. int errorFound = 0; public static void main(String[] args) { //Tests System.out.println("Legal dive test"); List<Integer> testDives = new ArrayList<Integer>(); testDives.add(80); //Depth testDives.add(41); //Time testDives.add(118); //SIT testDives.add(20); //Depth testDives.add(21); //Time testDives.add(22); //SIT testDives.add(10); testDives.add(11); testDives.add(12); DiveTable dt = new DiveTable(); dt.calculateDiveTableResults(testDives); System.out.println(dt); System.out.println("\n\nIllegal dive test"); List<Integer> testDives2 = new ArrayList<Integer>(); testDives2.add(50); testDives2.add(55); testDives2.add(110); testDives2.add(50); testDives2.add(51); testDives2.add(52); testDives2.add(10); testDives2.add(11); testDives2.add(12); DiveTable dt2 = new DiveTable(); dt2.calculateDiveTableResults(testDives2); System.out.println(dt2); } /** * Constructor that populates all three NAUI dive tables. */ public DiveTable() { // Populate Table 1: endOfDiveTable // Row 40 Map<Integer, TableOneCellOutput> row40Map = new LinkedHashMap<Integer, TableOneCellOutput>(); //Mapping time (in mins.) to Pressure Group row40Map.put(5, new TableOneCellOutput("A")); row40Map.put(15, new TableOneCellOutput("B")); row40Map.put(25, new TableOneCellOutput("C")); row40Map.put(30, new TableOneCellOutput("D")); row40Map.put(40, new TableOneCellOutput("E")); row40Map.put(50, new TableOneCellOutput("F")); row40Map.put(70, new TableOneCellOutput("G")); row40Map.put(80, new TableOneCellOutput("H")); row40Map.put(100, new TableOneCellOutput("I")); row40Map.put(110, new TableOneCellOutput("J")); row40Map.put(130, new TableOneCellOutput("K")); row40Map.put(150, new TableOneCellOutput("L", 5)); endOfDiveTable.put(40, row40Map); // Row 50 Map<Integer, TableOneCellOutput> row50Map = new LinkedHashMap<Integer, TableOneCellOutput>(); row50Map.put(10, new TableOneCellOutput("B")); row50Map.put(15, new TableOneCellOutput("C")); row50Map.put(25, new TableOneCellOutput("D")); row50Map.put(30, new TableOneCellOutput("E")); row50Map.put(40, new TableOneCellOutput("F")); row50Map.put(50, new TableOneCellOutput("G")); row50Map.put(60, new TableOneCellOutput("H")); row50Map.put(70, new TableOneCellOutput("I")); row50Map.put(80, new TableOneCellOutput("J")); row50Map.put(100, new TableOneCellOutput("L", 5)); endOfDiveTable.put(50, row50Map); // Row 60 Map<Integer, TableOneCellOutput> row60Map = new LinkedHashMap<Integer, TableOneCellOutput>(); row60Map.put(10, new TableOneCellOutput("B")); row60Map.put(15, new TableOneCellOutput("C")); row60Map.put(20, new TableOneCellOutput("D")); row60Map.put(25, new TableOneCellOutput("E")); row60Map.put(30, new TableOneCellOutput("F")); row60Map.put(40, new TableOneCellOutput("G")); row60Map.put(50, new TableOneCellOutput("H")); row60Map.put(55, new TableOneCellOutput("I")); row60Map.put(60, new TableOneCellOutput("J", 5)); row60Map.put(80, new TableOneCellOutput("L", 7)); endOfDiveTable.put(60, row60Map); // Row 70 Map<Integer, TableOneCellOutput> row70Map = new LinkedHashMap<Integer, TableOneCellOutput>(); row70Map.put(5, new TableOneCellOutput("B")); row70Map.put(10, new TableOneCellOutput("C")); row70Map.put(15, new TableOneCellOutput("D")); row70Map.put(20, new TableOneCellOutput("E")); row70Map.put(30, new TableOneCellOutput("F")); row70Map.put(35, new TableOneCellOutput("G")); row70Map.put(40, new TableOneCellOutput("H")); row70Map.put(45, new TableOneCellOutput("I")); row70Map.put(50, new TableOneCellOutput("J", 5)); row70Map.put(60, new TableOneCellOutput("K", 8)); row70Map.put(70, new TableOneCellOutput("L", 14)); endOfDiveTable.put(70, row70Map); // Row 80 Map<Integer, TableOneCellOutput> row80Map = new LinkedHashMap<Integer, TableOneCellOutput>(); row80Map.put(5, new TableOneCellOutput("B")); row80Map.put(10, new TableOneCellOutput("C")); row80Map.put(15, new TableOneCellOutput("D")); row80Map.put(20, new TableOneCellOutput("E")); row80Map.put(25, new TableOneCellOutput("F")); row80Map.put(30, new TableOneCellOutput("G")); row80Map.put(35, new TableOneCellOutput("H")); row80Map.put(40, new TableOneCellOutput("I", 5)); row80Map.put(50, new TableOneCellOutput("K", 10)); row80Map.put(60, new TableOneCellOutput("L", 17)); endOfDiveTable.put(80, row80Map); // Row 90 Map<Integer, TableOneCellOutput> row90Map = new LinkedHashMap<Integer, TableOneCellOutput>(); row90Map.put(5, new TableOneCellOutput("B")); row90Map.put(10, new TableOneCellOutput("C")); row90Map.put(12, new TableOneCellOutput("D")); row90Map.put(15, new TableOneCellOutput("E")); row90Map.put(20, new TableOneCellOutput("F")); row90Map.put(25, new TableOneCellOutput("G")); row90Map.put(30, new TableOneCellOutput("H", 5)); row90Map.put(40, new TableOneCellOutput("J", 7)); row90Map.put(50, new TableOneCellOutput("L", 18)); endOfDiveTable.put(90, row90Map); // Row 100 Map<Integer, TableOneCellOutput> row100Map = new LinkedHashMap<Integer, TableOneCellOutput>(); row100Map.put(5, new TableOneCellOutput("B")); row100Map.put(7, new TableOneCellOutput("C")); row100Map.put(10, new TableOneCellOutput("D")); row100Map.put(15, new TableOneCellOutput("E")); row100Map.put(20, new TableOneCellOutput("F")); row100Map.put(22, new TableOneCellOutput("G")); row100Map.put(25, new TableOneCellOutput("H", 5)); row100Map.put(40, new TableOneCellOutput("K", 15)); endOfDiveTable.put(100, row100Map); // Row 110 Map<Integer, TableOneCellOutput> row110Map = new LinkedHashMap<Integer, TableOneCellOutput>(); row110Map.put(5, new TableOneCellOutput("C")); row110Map.put(10, new TableOneCellOutput("D")); row110Map.put(13, new TableOneCellOutput("E")); row110Map.put(15, new TableOneCellOutput("F")); row110Map.put(20, new TableOneCellOutput("G", 5)); row110Map.put(30, new TableOneCellOutput("J", 7)); endOfDiveTable.put(110, row110Map); // Row 120 Map<Integer, TableOneCellOutput> row120Map = new LinkedHashMap<Integer, TableOneCellOutput>(); row120Map.put(5, new TableOneCellOutput("C")); row120Map.put(10, new TableOneCellOutput("D")); row120Map.put(12, new TableOneCellOutput("E")); row120Map.put(15, new TableOneCellOutput("F", 5)); row120Map.put(25, new TableOneCellOutput("I", 6)); row120Map.put(30, new TableOneCellOutput("J", 14)); endOfDiveTable.put(120, row120Map); // Row 130 Map<Integer, TableOneCellOutput> row130Map = new LinkedHashMap<Integer, TableOneCellOutput>(); row130Map.put(5, new TableOneCellOutput("C")); row130Map.put(8, new TableOneCellOutput("D")); row130Map.put(10, new TableOneCellOutput("E", 5)); row130Map.put(25, new TableOneCellOutput("J", 10)); endOfDiveTable.put(130, row130Map); // Populate Table 2: surfaceIntervalTimeTable // Column A Map<Integer, String> columnAMap = new LinkedHashMap<Integer, String>(); columnAMap.put(10, "A"); surfaceIntervalTimeTable.put("A", columnAMap); // Column B Map<Integer, String> columnBMap = new LinkedHashMap<Integer, String>(); columnBMap.put(201, "A"); columnBMap.put(10, "B"); surfaceIntervalTimeTable.put("B", columnBMap); // Column C Map<Integer, String> columnCMap = new LinkedHashMap<Integer, String>(); columnCMap.put(290, "A"); columnCMap.put(100, "B"); columnCMap.put(10, "C"); surfaceIntervalTimeTable.put("C", columnCMap); // Column D Map<Integer, String> columnDMap = new LinkedHashMap<Integer, String>(); columnDMap.put(349, "A"); columnDMap.put(159, "B"); columnDMap.put(70, "C"); columnDMap.put(10, "D"); surfaceIntervalTimeTable.put("D", columnDMap); // Column E Map<Integer, String> columnEMap = new LinkedHashMap<Integer, String>(); columnEMap.put(395, "A"); columnEMap.put(205, "B"); columnEMap.put(118, "C"); columnEMap.put(55, "D"); columnEMap.put(10, "E"); surfaceIntervalTimeTable.put("E", columnEMap); // Column F Map<Integer, String> columnFMap = new LinkedHashMap<Integer, String>(); columnFMap.put(426, "A"); columnFMap.put(238, "B"); columnFMap.put(149, "C"); columnFMap.put(90, "D"); columnFMap.put(46, "E"); columnFMap.put(10, "F"); surfaceIntervalTimeTable.put("F", columnFMap); // Column G Map<Integer, String> columnGMap = new LinkedHashMap<Integer, String>(); columnGMap.put(456, "A"); columnGMap.put(266, "B"); columnGMap.put(179, "C"); columnGMap.put(120, "D"); columnGMap.put(76, "E"); columnGMap.put(41, "F"); columnGMap.put(10, "G"); surfaceIntervalTimeTable.put("G", columnGMap); // Column H Map<Integer, String> columnHMap = new LinkedHashMap<Integer, String>(); columnHMap.put(480, "A"); columnHMap.put(290, "B"); columnHMap.put(201, "C"); columnHMap.put(144, "D"); columnHMap.put(102, "E"); columnHMap.put(67, "F"); columnHMap.put(37, "G"); columnHMap.put(10, "H"); surfaceIntervalTimeTable.put("H", columnHMap); // Column I Map<Integer, String> columnIMap = new LinkedHashMap<Integer, String>(); columnIMap.put(502, "A"); columnIMap.put(313, "B"); columnIMap.put(224, "C"); columnIMap.put(165, "D"); columnIMap.put(123, "E"); columnIMap.put(90, "F"); columnIMap.put(60, "G"); columnIMap.put(34, "H"); columnIMap.put(10, "I"); surfaceIntervalTimeTable.put("I", columnIMap); // Column J Map<Integer, String> columnJMap = new LinkedHashMap<Integer, String>(); columnJMap.put(531, "A"); columnJMap.put(341, "B"); columnJMap.put(243, "C"); columnJMap.put(185, "D"); columnJMap.put(141, "E"); columnJMap.put(108, "F"); columnJMap.put(80, "G"); columnJMap.put(55, "H"); columnJMap.put(32, "I"); columnJMap.put(10, "J"); surfaceIntervalTimeTable.put("J", columnJMap); // Column K Map<Integer, String> columnKMap = new LinkedHashMap<Integer, String>(); columnKMap.put(539, "A"); columnKMap.put(349, "B"); columnKMap.put(260, "C"); columnKMap.put(202, "D"); columnKMap.put(159, "E"); columnKMap.put(124, "F"); columnKMap.put(96, "G"); columnKMap.put(72, "H"); columnKMap.put(50, "I"); columnKMap.put(29, "J"); columnKMap.put(10, "K"); surfaceIntervalTimeTable.put("K", columnKMap); // Column L Map<Integer, String> columnLMap = new LinkedHashMap<Integer, String>(); columnLMap.put(553, "A"); columnLMap.put(363, "B"); columnLMap.put(276, "C"); columnLMap.put(217, "D"); columnLMap.put(174, "E"); columnLMap.put(140, "F"); columnLMap.put(110, "G"); columnLMap.put(86, "H"); columnLMap.put(65, "I"); columnLMap.put(46, "J"); columnLMap.put(27, "K"); columnLMap.put(10, "L"); surfaceIntervalTimeTable.put("L", columnLMap); //Populate Table 3: repetitiveDiveTimeTable //Note: I am entering rows in the opposite direction (left to right) as displayed on official NAUI table 3. // Row A Map<Integer, Integer[]> rowAMap = new LinkedHashMap<Integer, Integer[]>(); rowAMap.put(40, new Integer[]{7, 123}); rowAMap.put(50, new Integer[]{6, 74}); rowAMap.put(60, new Integer[]{5, 50}); rowAMap.put(70, new Integer[]{4, 41}); rowAMap.put(80, new Integer[]{4, 31}); rowAMap.put(90, new Integer[]{3, 22}); rowAMap.put(100, new Integer[]{3, 19}); rowAMap.put(110, new Integer[]{3, 12}); rowAMap.put(120, new Integer[]{3, 9}); rowAMap.put(130, new Integer[]{3, 5}); repetitiveDiveTimeTable.put("A", rowAMap); // Row B Map<Integer, Integer[]> rowBMap = new LinkedHashMap<Integer, Integer[]>(); rowBMap.put(40, new Integer[]{17, 113}); rowBMap.put(50, new Integer[]{13, 67}); rowBMap.put(60, new Integer[]{11, 44}); rowBMap.put(70, new Integer[]{9, 36}); rowBMap.put(80, new Integer[]{8, 27}); rowBMap.put(90, new Integer[]{7, 18}); rowBMap.put(100, new Integer[]{7, 15}); rowBMap.put(110, new Integer[]{6, 9}); rowBMap.put(120, new Integer[]{6, 6}); rowBMap.put(130, new Integer[]{6, 0}); repetitiveDiveTimeTable.put("B", rowBMap); // Row C Map<Integer, Integer[]> rowCMap = new LinkedHashMap<Integer, Integer[]>(); rowCMap.put(40, new Integer[]{25, 105}); rowCMap.put(50, new Integer[]{21, 59}); rowCMap.put(60, new Integer[]{17, 38}); rowCMap.put(70, new Integer[]{15, 30}); rowCMap.put(80, new Integer[]{13, 22}); rowCMap.put(90, new Integer[]{11, 14}); rowCMap.put(100, new Integer[]{10, 12}); rowCMap.put(110, new Integer[]{10, 5}); rowCMap.put(120, new Integer[]{9, 0}); rowCMap.put(130, new Integer[]{8, 0}); repetitiveDiveTimeTable.put("C", rowCMap); // Row D Map<Integer, Integer[]> rowDMap = new LinkedHashMap<Integer, Integer[]>(); rowDMap.put(40, new Integer[]{37, 93}); rowDMap.put(50, new Integer[]{29, 51}); rowDMap.put(60, new Integer[]{24, 31}); rowDMap.put(70, new Integer[]{20, 25}); rowDMap.put(80, new Integer[]{18, 17}); rowDMap.put(90, new Integer[]{16, 9}); rowDMap.put(100, new Integer[]{14, 8}); rowDMap.put(110, new Integer[]{13, 0}); rowDMap.put(120, new Integer[]{12, 0}); rowDMap.put(130, new Integer[]{11, 0}); repetitiveDiveTimeTable.put("D", rowDMap); // Row E Map<Integer, Integer[]> rowEMap = new LinkedHashMap<Integer, Integer[]>(); rowEMap.put(40, new Integer[]{49, 81}); rowEMap.put(50, new Integer[]{38, 42}); rowEMap.put(60, new Integer[]{30, 25}); rowEMap.put(70, new Integer[]{26, 19}); rowEMap.put(80, new Integer[]{23, 12}); rowEMap.put(90, new Integer[]{20, 5}); rowEMap.put(100, new Integer[]{18, 4}); rowEMap.put(110, new Integer[]{16, 0}); rowEMap.put(120, new Integer[]{15, 0}); rowEMap.put(130, new Integer[]{13, 0}); repetitiveDiveTimeTable.put("E", rowEMap); // Row F Map<Integer, Integer[]> rowFMap = new LinkedHashMap<Integer, Integer[]>(); rowFMap.put(40, new Integer[]{61, 69}); rowFMap.put(50, new Integer[]{47, 33}); rowFMap.put(60, new Integer[]{36, 19}); rowFMap.put(70, new Integer[]{31, 14}); rowFMap.put(80, new Integer[]{28, 7}); rowFMap.put(90, new Integer[]{24, 0}); rowFMap.put(100, new Integer[]{22, 0}); rowFMap.put(110, new Integer[]{20, 0}); rowFMap.put(120, new Integer[]{18, 0}); rowFMap.put(130, new Integer[]{16, 0}); repetitiveDiveTimeTable.put("F", rowFMap); // Row G Map<Integer, Integer[]> rowGMap = new LinkedHashMap<Integer, Integer[]>(); rowGMap.put(40, new Integer[]{73, 57}); rowGMap.put(50, new Integer[]{56, 24}); rowGMap.put(60, new Integer[]{44, 11}); rowGMap.put(70, new Integer[]{37, 8}); rowGMap.put(80, new Integer[]{32, 0}); rowGMap.put(90, new Integer[]{29, 0}); rowGMap.put(100, new Integer[]{26, 0}); rowGMap.put(110, new Integer[]{24, 0}); rowGMap.put(120, new Integer[]{21, 0}); rowGMap.put(130, new Integer[]{19, 0}); repetitiveDiveTimeTable.put("G", rowGMap); // Row H Map<Integer, Integer[]> rowHMap = new LinkedHashMap<Integer, Integer[]>(); rowHMap.put(40, new Integer[]{87, 43}); rowHMap.put(50, new Integer[]{66, 14}); rowHMap.put(60, new Integer[]{52, 0}); rowHMap.put(70, new Integer[]{43, 0}); rowHMap.put(80, new Integer[]{38, 0}); rowHMap.put(90, new Integer[]{33, 0}); rowHMap.put(100, new Integer[]{30, 0}); rowHMap.put(110, new Integer[]{27, 0}); rowHMap.put(120, new Integer[]{25, 0}); rowHMap.put(130, new Integer[]{22, 0}); repetitiveDiveTimeTable.put("H", rowHMap); // Row I Map<Integer, Integer[]> rowIMap = new LinkedHashMap<Integer, Integer[]>(); rowIMap.put(40, new Integer[]{101, 29}); rowIMap.put(50, new Integer[]{76, 4}); rowIMap.put(60, new Integer[]{61, 0}); rowIMap.put(70, new Integer[]{50, 0}); rowIMap.put(80, new Integer[]{43, 0}); rowIMap.put(90, new Integer[]{38, 0}); rowIMap.put(100, new Integer[]{34, 0}); rowIMap.put(110, new Integer[]{31, 0}); rowIMap.put(120, new Integer[]{28, 0}); rowIMap.put(130, new Integer[]{25, 0}); repetitiveDiveTimeTable.put("I", rowIMap); // Row J Map<Integer, Integer[]> rowJMap = new LinkedHashMap<Integer, Integer[]>(); rowJMap.put(40, new Integer[]{116, 14}); rowJMap.put(50, new Integer[]{87, 4}); rowJMap.put(60, new Integer[]{70, 0}); rowJMap.put(70, new Integer[]{57, 0}); rowJMap.put(80, new Integer[]{48, 0}); rowJMap.put(90, new Integer[]{43, 0}); rowJMap.put(100, new Integer[]{38, 0}); rowJMap.put(110, new Integer[]{null, null}); //Avoid Repetitive Dive over 100 ft. rowJMap.put(120, new Integer[]{null, null}); //Avoid rowJMap.put(130, new Integer[]{null, null}); //Avoid repetitiveDiveTimeTable.put("J", rowJMap); // Row K Map<Integer, Integer[]> rowKMap = new LinkedHashMap<Integer, Integer[]>(); rowKMap.put(40, new Integer[]{138, 0}); rowKMap.put(50, new Integer[]{99, 0}); rowKMap.put(60, new Integer[]{79, 0}); rowKMap.put(70, new Integer[]{64, 0}); rowKMap.put(80, new Integer[]{54, 0}); rowKMap.put(90, new Integer[]{47, 0}); rowKMap.put(100, new Integer[]{null, null}); rowKMap.put(110, new Integer[]{null, null}); //Avoid Repetitive Dive over 100 ft. rowKMap.put(120, new Integer[]{null, null}); //Avoid rowKMap.put(130, new Integer[]{null, null}); //Avoid repetitiveDiveTimeTable.put("K", rowKMap); // Row L Map<Integer, Integer[]> rowLMap = new LinkedHashMap<Integer, Integer[]>(); rowLMap.put(40, new Integer[]{161, 0}); rowLMap.put(50, new Integer[]{111, 0}); rowLMap.put(60, new Integer[]{88, 0}); rowLMap.put(70, new Integer[]{72, 0}); rowLMap.put(80, new Integer[]{61, 0}); rowLMap.put(90, new Integer[]{53, 0}); rowLMap.put(100, new Integer[]{null, null}); rowLMap.put(110, new Integer[]{null, null}); //Avoid Repetitive Dive over 100 ft. rowLMap.put(120, new Integer[]{null, null}); //Avoid rowLMap.put(130, new Integer[]{null, null}); //Avoid repetitiveDiveTimeTable.put("L", rowLMap); } /** * Takes an ArrayList containing the user's dive information (dive depth, dive time, surface interval time), * and outputs data required to generate a proper dive profile. * * @param diveInfo The user's dive data. */ public void calculateDiveTableResults (List<Integer> diveInfo) { String currentPressureGroup = ""; //Changes as we continuously run through loop. for (int i = 0; i < diveInfo.size(); i += 3) { //Note: Incrementing by 3, not 1. Integer diveNumber = ((i / 3) + 1); //Every 3rd element in list indicates a new dive. Integer diveDepth = diveInfo.get(i); //Depth is indicated first. Integer diveTime = diveInfo.get(i + 1); //Then DiveTime. Integer surfaceIntervalTime = diveInfo.get(i + 2); //Then Surface Interval Time. //Will hold all input data and final calculated data for each dive. SingleDiveData diveData = new SingleDiveData(diveDepth, diveTime, surfaceIntervalTime); // System.out.println("Dive #" + diveNumber + ", Depth: " + diveDepth + ", Time: " + diveTime + ", Surface Interval Time: " + surfaceIntervalTime); //For all non-initial dives, we look at repetitive dive table 3 and make adjustments to user input. if (i != 0) { //Table 3 Lookup Integer[] tableThreeResult = repetitiveDiveTimeTableLookup(currentPressureGroup, diveDepth, diveTime); //Check if diveTime is greater than Adjusted Maximum Dive Time. If it is, must report error. if(diveTime > tableThreeResult[1]) { this.errorFound = diveNumber; //Set error location diveData.errorMessage = "Error at Dive #" + diveNumber + ": Dive Time is greater than allowed Adjusted Maximum Dive Time."; } diveTime = diveInfo.get(i + 1) + tableThreeResult[0]; //TotalNitrogenTime = ActualDiveTime + Residual Nitrogen Time. diveData.totalNitrogenTime = diveTime; // System.out.println("\tTotal Nitrogen Time: " + diveTime); } //Table 1 Lookup TableOneCellOutput tableOneResult = tableOneLookup(diveDepth, diveTime); currentPressureGroup = tableOneResult.pressureGroup; //Currently indicates End-Of-Dive PG. diveData.endOfDivePG = currentPressureGroup; Integer decompressionTime = tableOneResult.decompressionTime; diveData.decompressionTime = decompressionTime; // System.out.println("\tEnd-Of-Dive Pressure Group: " + currentPressureGroup); // if (decompressionTime != 0) { // System.out.println("\tDecompression Time Required: " + decompressionTime); // } else { // System.out.println("\tDecompression Time Required: None"); //Table 2 Lookup //Now currentPressureGroup will hold the new Pressure Group post-table2. currentPressureGroup = surfaceIntervalTimeLookup(currentPressureGroup, surfaceIntervalTime); diveData.postSurfaceIntervalPG = currentPressureGroup; // System.out.println("\tPost-Surface-Interval-Time Pressure Group: " + currentPressureGroup); //Add diveData to diveResultsMap this.diveResultsMap.put(diveNumber, diveData); //If error has been found during calculations, exit method prematurely. if (this.errorFound > 0) { return; } } } public TableOneCellOutput tableOneLookup(Integer diveDepth, Integer diveTime) { for (Map.Entry<Integer, Map<Integer, TableOneCellOutput>> entry : endOfDiveTable.entrySet()) { if (entry.getKey() >= diveDepth) { //Note: We round up to the next depth key for safety reasons. //Found key. Now iterate through its nested map. Map<Integer, TableOneCellOutput> nestedMap = entry.getValue(); for (Map.Entry<Integer, TableOneCellOutput> nestedEntry : nestedMap.entrySet()) { if (nestedEntry.getKey() >= diveTime) { //Rounding up to next time key for safety reasons. //Found our target cell. Return it. TableOneCellOutput resultCell = nestedEntry.getValue(); return resultCell; } } } } return null; } public String surfaceIntervalTimeLookup(String pressureGroup, Integer surfaceIntervalTime) { //We have a previously calculated pressure group at this point, so we use it to grab the appropriate //column in the S.I.T. table. Map<Integer, String> columnMap = surfaceIntervalTimeTable.get(pressureGroup); //Now we iterate through map for given surface interval time. //Note: Though the officialNAUI table 2 contains a range of times in each cell, our map only holds the //lower bound time of each cell. This is the time that we will be comparing to. for (Map.Entry<Integer, String> entry : columnMap.entrySet()) { if (entry.getKey() <= surfaceIntervalTime) { //Found target cell. Return new Pressure Group letter. String newPressureGroup = entry.getValue(); return newPressureGroup; } } return null; } public Integer[] repetitiveDiveTimeTableLookup(String pressureGroup, Integer diveDepth, Integer diveTime) { //Use previously calculated Pressure Group (from table 2 output) to grab relevant row mapping in Table 3. Map<Integer, Integer[]> rowMap = repetitiveDiveTimeTable.get(pressureGroup); //Now we iterate through map for given depth. //Note: rowMap is a mapping of dive depth to a size 2 integer array containing: //array[0]: Residual Nitrogen Time //array[1]: Adjusted Max Dive Time for (Map.Entry<Integer, Integer[]> entry : rowMap.entrySet()) { if (entry.getKey() >= diveDepth) { //Note: Rounding up to next nearest depth on the table. //Found target cell. Return new Pressure Group letter. Integer[] targetCell = entry.getValue(); return targetCell; } } return null; } public String toString() { String divesInfo = ""; //Will return at end. if (this.errorFound > 0) { divesInfo += "*WARNING* Error Found at Dive #" + this.errorFound + ": " + this.diveResultsMap.get(this.errorFound).errorMessage + "\n"; } for (Map.Entry<Integer, SingleDiveData> entry : this.diveResultsMap.entrySet()) { Integer diveNumber = entry.getKey(); SingleDiveData diveData = entry.getValue(); divesInfo += "\nDive #" + diveNumber + ", Depth: " + diveData.diveDepth + ", Time: " + diveData.diveTime + ", Surface Interval Time: " + diveData.surfaceIntervalTime; //Show TNT for all non-initial dives. if (diveNumber > 1) { divesInfo += "\n\tTotal Nitrogen Time: " + diveData.totalNitrogenTime; } divesInfo += "\n\tEnd-Of-Dive Pressure Group: " + diveData.endOfDivePG; divesInfo += "\n\tDecompression Time Required: " + diveData.decompressionTime; divesInfo += "\n\tPost-Surface-Interval-Time Pressure Group: " + diveData.postSurfaceIntervalPG; if (diveData.errorMessage == null) { divesInfo += "\n\tErrors: None"; } else { divesInfo += "\n\tError Found: " + diveData.errorMessage; } } return divesInfo; } } /** * Class to hold Table 1 cell data. */ class TableOneCellOutput { String pressureGroup; Integer decompressionTime; public TableOneCellOutput(String PG) { this.pressureGroup = PG; this.decompressionTime = 0; } public TableOneCellOutput(String PG, Integer DT) { this.pressureGroup = PG; this.decompressionTime = DT; } } /** * Class to hold all data of a single dive, including calculated results. */ class SingleDiveData { Integer diveDepth; //From user input Integer diveTime; //From user input Integer surfaceIntervalTime; //From user input Integer totalNitrogenTime; String endOfDivePG; Integer decompressionTime; String postSurfaceIntervalPG; String errorMessage; //Will state the FIRST found error. public SingleDiveData (Integer depth, Integer time, Integer SIT) { this.diveDepth = depth; this.diveTime = time; this.surfaceIntervalTime = SIT; this.totalNitrogenTime = 0; this.decompressionTime = 0; this.errorMessage = null; } }
package ActiveMQ; import java.util.Map.Entry; import java.util.Timer; import java.util.TimerTask; import plugincore.PluginEngine; import shared.MsgEvent; public class ActiveBrokerManager implements Runnable { //private MulticastSocket socket; private Timer timer; public ActiveBrokerManager() { timer = new Timer(); //timer.scheduleAtFixedRate(new BrokerWatchDog(), 500, 300000);//remote timer.scheduleAtFixedRate(new BrokerWatchDog(), 500, 15000);//remote } public void shutdown() { } public void addBroker(String agentPath) { BrokeredAgent ba = PluginEngine.brokeredAgents.get(agentPath); if(ba.brokerStatus == BrokerStatusType.INIT) { //Fire up new thread. //ba.brokerStatus = BrokerStatusType.STARTING; //System.out.println("Adding Broker: " + agentPath + " IP:" + ba.activeAddress); ba.setStarting(); } } public void run() { PluginEngine.ActiveBrokerManagerActive = true; while(PluginEngine.ActiveBrokerManagerActive) { try { MsgEvent cb = PluginEngine.incomingCanidateBrokers.poll(); if(cb != null) { String agentIP = cb.getParam("dst_ip"); if(!PluginEngine.isLocal(agentIP)) //ignore local responses { boolean addBroker = false; String agentPath = cb.getParam("dst_region") + "_" + cb.getParam("dst_agent"); //System.out.println(getClass().getName() + ">>> canidate boker :" + agentPath + " canidate ip:" + agentIP) ; BrokeredAgent ba; if(PluginEngine.brokeredAgents.containsKey(agentPath)) { /* ba = PluginEngine.brokeredAgents.get(agentPath); //add ip to possible list if(!ba.addressMap.containsKey(agentIP)) { ba.addressMap.put(agentIP,BrokerStatusType.INIT); } //reset status if needed if((ba.brokerStatus.equals(BrokerStatusType.FAILED) || (ba.brokerStatus.equals(BrokerStatusType.STOPPED)))) { ba.activeAddress = agentIP; ba.brokerStatus = BrokerStatusType.INIT; addBroker = true; System.out.println("BA EXIST ADDING agentPath: " + agentPath + " remote_ip: " + agentIP); } */ System.out.println("BA EXIST ADDING agentPath: " + agentPath + " remote_ip: " + agentIP); } else { ba = new BrokeredAgent(agentIP,agentPath); PluginEngine.brokeredAgents.put(agentPath, ba); while(!PluginEngine.brokeredAgents.containsKey(agentPath)) { System.out.println("NEW WAITING!!"); Thread.sleep(10000); } addBroker = true; System.out.println("BA NEW ADDING agentPath: " + agentPath + " remote_ip: " + agentIP); } //try and connect if(addBroker) { addBroker(agentPath); } } Thread.sleep(500); //allow HM to catch up } else { Thread.sleep(1000); } } catch (Exception ex) { System.out.println("DiscoveryEngineIPv6 : Run Error " + ex.toString()); } } } class BrokerWatchDog extends TimerTask { public void run() { for (Entry<String, BrokeredAgent> entry : PluginEngine.brokeredAgents.entrySet()) { //System.out.println(entry.getKey() + "/" + entry.getValue()); BrokeredAgent ba = entry.getValue(); if(ba.brokerStatus == BrokerStatusType.FAILED) { //System.out.println("stopping agentPath: " + ba.agentPath); ba.setStop(); System.out.println("Cleared agentPath: " + ba.agentPath); PluginEngine.brokeredAgents.remove(entry.getKey());//remove agent } } } } }
package SW9.model_canvas; import SW9.model_canvas.arrow_heads.ArrowHead; import SW9.model_canvas.arrow_heads.BroadcastChannelSenderArrowHead; import SW9.model_canvas.arrow_heads.ChannelReceiverArrowHead; import SW9.model_canvas.arrow_heads.HandshakeChannelSenderArrowHead; import SW9.model_canvas.edges.Edge; import SW9.model_canvas.edges.Properties; import SW9.model_canvas.locations.Location; import SW9.model_canvas.synchronization.ChannelBox; import SW9.utility.UndoRedoStack; import SW9.utility.helpers.*; import SW9.utility.keyboard.Keybind; import SW9.utility.keyboard.KeyboardTracker; import SW9.utility.mouse.MouseTracker; import javafx.animation.Transition; import javafx.beans.property.DoubleProperty; import javafx.beans.property.SimpleDoubleProperty; import javafx.fxml.FXML; import javafx.scene.Node; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyCodeCombination; import javafx.scene.input.KeyCombination; import javafx.scene.input.MouseButton; import javafx.scene.layout.Pane; import javafx.scene.shape.Circle; import javafx.scene.shape.Line; import javafx.util.Duration; import java.util.ArrayList; public class ModelCanvas extends Pane implements MouseTrackable, IParent { public static final int GRID_SIZE = 25; // Variables describing the state of the canvas private static Location locationOnMouse = null; private static Location hoveredLocation = null; private static Edge edgeBeingDrawn = null; private static ModelContainer hoveredModelContainer = null; private final MouseTracker mouseTracker = new MouseTracker(this); public ModelCanvas() { initialize(); // This is a fix to make the canvas larger when we translate it away from 0,0 final Circle canvasExpanderNode = new Circle(); canvasExpanderNode.radiusProperty().set(0); addChild(canvasExpanderNode); canvasExpanderNode.translateXProperty().bind(this.translateXProperty().multiply(-1)); canvasExpanderNode.translateYProperty().bind(this.translateYProperty().multiply(-1)); // Add a grid to the canvas final Grid grid = new Grid(GRID_SIZE); getChildren().add(grid); DragHelper.makeDraggable(this, mouseEvent -> mouseEvent.getButton().equals(MouseButton.SECONDARY)); } @FXML public void initialize() { KeyboardTracker.registerKeybind(KeyboardTracker.ADD_CHANNEL_BOX, new Keybind(new KeyCodeCombination(KeyCode.B), () -> { final ChannelBox channelBox = new ChannelBox(); UndoRedoStack.push(() -> { // Perform addChild(channelBox); }, () -> { // Undo removeChild(channelBox); }); })); KeyboardTracker.registerKeybind(KeyboardTracker.DELETE_SELECTED, new Keybind(new KeyCodeCombination(KeyCode.DELETE), () -> { ArrayList<Removable> copy = new ArrayList<>(); SelectHelper.getSelectedElements().forEach(copy::add); SelectHelper.clearSelectedElements(); UndoRedoStack.push(() -> { // Perform copy.forEach(Removable::remove); }, () -> { // Undo copy.forEach(Removable::deselect); copy.forEach(Removable::reAdd); }); })); KeyboardTracker.registerKeybind(KeyboardTracker.UNDO, new Keybind(new KeyCodeCombination(KeyCode.Z, KeyCombination.SHORTCUT_DOWN), UndoRedoStack::undo)); KeyboardTracker.registerKeybind(KeyboardTracker.REDO, new Keybind(new KeyCodeCombination(KeyCode.Z, KeyCombination.SHORTCUT_DOWN, KeyCombination.SHIFT_DOWN), UndoRedoStack::redo)); KeyboardTracker.registerKeybind(KeyboardTracker.ADD_NEW_LOCATION, new Keybind(new KeyCodeCombination(KeyCode.L), () -> { if (!mouseHasLocation()) { final Location newLocation = new Location(mouseTracker); locationOnMouse = newLocation; newLocation.setEffect(DropShadowHelper.generateElevationShadow(22)); addChild(newLocation); } })); KeyboardTracker.registerKeybind(KeyboardTracker.CREATE_COMPONENT, new Keybind(new KeyCodeCombination(KeyCode.K), () -> { final ModelComponent mc = new ModelComponent(mouseTracker.xProperty().get(), mouseTracker.yProperty().get(), 400, 600, "Component", mouseTracker); UndoRedoStack.push(() -> addChild(mc), () -> removeChild(mc)); })); // TODO remove me when testing of heads is done KeyboardTracker.registerKeybind(KeyboardTracker.TESTING_BIND, new Keybind(new KeyCodeCombination(KeyCode.T), () -> { // Outgoing arrows final Circle outgoingStart1 = new Circle(100, 100, 0); final Circle outgoingEnd1 = new Circle(200, 100, 0); final Circle outgoingStart2 = new Circle(100, 200, 0); final Circle outgoingEnd2 = new Circle(200, 200, 0); final HandshakeChannelSenderArrowHead handshakeArrowHead = new HandshakeChannelSenderArrowHead(); final BroadcastChannelSenderArrowHead broadCastArrowHead = new BroadcastChannelSenderArrowHead(); handshakeArrowHead.isUrgentProperty().setValue(true); final Line handshakeArrowLine = new Line(); final Line broadCastArrowLine = new Line(); BindingHelper.bind(handshakeArrowLine, outgoingStart1, outgoingEnd1); BindingHelper.bind(broadCastArrowLine, outgoingStart2, outgoingEnd2); BindingHelper.bind(handshakeArrowHead, outgoingStart1, outgoingEnd1); BindingHelper.bind(broadCastArrowHead, outgoingStart2, outgoingEnd2); BindingHelper.bind(handshakeArrowLine, handshakeArrowHead); BindingHelper.bind(broadCastArrowLine, broadCastArrowHead); // Incoming arrows final Circle incomingEnd1 = new Circle(300, 100, 0); final Circle incomingStart1 = new Circle(400, 100, 0); final Line channelReceiverLine = new Line(); final ArrowHead channelReceiverArrowHead = new ChannelReceiverArrowHead(); BindingHelper.bind(channelReceiverLine, incomingStart1, incomingEnd1); BindingHelper.bind(channelReceiverArrowHead, incomingStart1, incomingEnd1); BindingHelper.bind(channelReceiverLine, channelReceiverArrowHead); // Properties Properties properties = new Properties(new SimpleDoubleProperty(100), new SimpleDoubleProperty(300)); UndoRedoStack.push( () -> addChildren(handshakeArrowLine, broadCastArrowLine, handshakeArrowHead, broadCastArrowHead, properties, channelReceiverArrowHead, channelReceiverLine), () -> removeChildren(handshakeArrowLine, broadCastArrowLine, handshakeArrowHead, broadCastArrowHead, properties, channelReceiverArrowHead, channelReceiverLine) ); })); } /** * Gets the Location that currently follows the mouse on the canvas * This functionality is maintained by the Location themselves. * * @return the Locations following the mouse on the canvas */ public static Location getLocationOnMouse() { return locationOnMouse; } /** * Sets a Location to follow the mouse on the canvas * This functionality is maintained by the Location themselves. * * @param location - a Location to follow the mouse */ public static void setLocationOnMouse(final Location location) { locationOnMouse = location; } /** * Checks if a Location is currently following the mouse on the canvas * This functionality is maintained by the Location themselves. * * @return true if a Location is following the mouse, otherwise false */ public static boolean mouseHasLocation() { return locationOnMouse != null; } /** * Gets the Location currently being hovered by the mouse on the canvas * This functionality is maintained by the Location themselves. * * @return the Location be hovered on the canvas */ public static Location getHoveredLocation() { return hoveredLocation; } /** * Sets a Location to currently being hovered by the mouse on the canvas * This functionality is maintained by the Location themselves. * * @param location - a Location that is being hovered */ public static void setHoveredLocation(final Location location) { final Location prevHovered = getHoveredLocation(); if (prevHovered != location) { if (prevHovered != null) { new Transition() { { setCycleDuration(Duration.millis(100)); } protected void interpolate(double fraction) { prevHovered.setEffect(DropShadowHelper.generateElevationShadow(6 - 6 * fraction)); } }.play(); } if (location != null) { new Transition() { { setCycleDuration(Duration.millis(100)); } protected void interpolate(double frac) { location.setEffect(DropShadowHelper.generateElevationShadow(6 * frac)); } }.play(); } hoveredLocation = location; } } /** * Checks if a Location is currently being hovered by the mouse on the canvas * This functionality is maintained by the Location themselves. * * @return true if a Location is being hovered bt the mouse, otherwise false */ public static boolean mouseIsHoveringLocation() { return hoveredLocation != null; } /** * Checks if an Edge is currently being drawn on the canvas * This functionality is maintained by the Edge itself. * * @return true if an Edge is being drawn, otherwise false */ public static boolean edgeIsBeingDrawn() { return edgeBeingDrawn != null; } /** * Gets the Edge that is currently being drawn on the canvas * This functionality is maintained by the Edge itself. * * @return the Edge being drawn on the canvas */ public static Edge getEdgeBeingDrawn() { return edgeBeingDrawn; } /** * Sets the Edge that is currently being drawn on the canvas * This functionality is maintained by the Edge itself. * * @param edgeBeingDrawn - the Edge being drawn */ public static void setEdgeBeingDrawn(Edge edgeBeingDrawn) { ModelCanvas.edgeBeingDrawn = edgeBeingDrawn; } public static ModelContainer getHoveredModelContainer() { return hoveredModelContainer; } public static void setHoveredModelContainer(final ModelContainer modelContainer) { hoveredModelContainer = modelContainer; } public static boolean mouseIsHoveringModelContainer() { return hoveredModelContainer != null; } @Override public MouseTracker getMouseTracker() { return mouseTracker; } @Override public DoubleProperty xProperty() { return layoutXProperty(); } @Override public DoubleProperty yProperty() { return layoutYProperty(); } @Override public void addChild(Node child) { getChildren().add(child); } @Override public void addChildren(Node... children) { getChildren().addAll(children); } @Override public void removeChild(Node child) { getChildren().remove(child); } @Override public void removeChildren(Node... children) { getChildren().removeAll(children); } }
package br.com.dbsoft.util; import java.lang.reflect.Method; import java.math.BigDecimal; import java.sql.Date; import java.sql.Time; import java.sql.Timestamp; public class DBSObject { public static Boolean isEmpty(Object pObj){ if (pObj == null){ return true; } if (pObj instanceof String){ String xObj = pObj.toString(); if (xObj.trim().equals("")){ return true; } } return false; } public static Boolean isNull(Object pObj){ if (pObj == null){ return true; } return false; } public static Boolean isIdValid(Integer pObj) { if (DBSObject.isEmpty(pObj)){ return false; } if (pObj <= 0) { return false; } return true; } @SuppressWarnings("unchecked") public static <T> T getNotNull(T pDado, T pDadoDefault){ if (DBSObject.isEmpty(pDado)){ if (DBSObject.isEmpty(pDadoDefault)){ return (T) ""; //Retorna vazio } else { return pDadoDefault; //Retorna valor default informado } } else{ return pDado; } } public static <T> T getNotEmpty(T pDado, T pDadoDefault){ if (DBSObject.isEmpty(pDado)){ return pDadoDefault; //Retorna valor default informado } else{ return pDado; } } /** * Converte o valor recebido para o tipo de class informado * @param pValue * @param pClass * @return */ @SuppressWarnings("unchecked") public static <T> T toClass(T pValue, Class<?> pClass){ if (pClass==null){ return pValue; } if (pClass.isAssignableFrom(Boolean.class)){ return (T) DBSBoolean.toBoolean(pValue); } if (pValue==null){ return null; } if (pClass.isAssignableFrom(Integer.class)){ pValue = (T) DBSNumber.toInteger(pValue); }else if (pClass.isAssignableFrom(BigDecimal.class)){ pValue = (T) DBSNumber.toBigDecimal(pValue); }else if (pClass.isAssignableFrom(Double.class)){ pValue = (T) DBSNumber.toDouble(pValue); }else if (pClass.isAssignableFrom(String.class)){ pValue = (T) pValue.toString(); }else if (pClass.isAssignableFrom(Date.class)){ pValue = (T) DBSDate.toDate(pValue); }else if (pClass.isAssignableFrom(Timestamp.class)){ pValue = (T) DBSDate.toTimestamp(pValue); }else if (pClass.isAssignableFrom(Time.class)){ pValue = (T) DBSDate.toTime(pValue); } return pValue; } protected static Class<?> getCallerReturnType(int pParentIndex){ try { StackTraceElement xElement = Thread.currentThread().getStackTrace()[pParentIndex]; Class<?> xClass = Class.forName(xElement.getClassName()); Method xMethod = xClass.getDeclaredMethod(xElement.getMethodName()); return xMethod.getReturnType(); } catch (ClassNotFoundException | NoSuchMethodException | SecurityException e) { return null; } } }
package browserview; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.openqa.selenium.By; import org.openqa.selenium.Dimension; import org.openqa.selenium.Point; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebDriverException; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeOptions; import ui.UI; import util.GitHubURL; import util.PlatformSpecific; import util.events.testevents.JumpToCommentEvent; import util.events.testevents.SendKeysToBrowserEvent; import com.sun.jna.platform.win32.User32; import com.sun.jna.platform.win32.WinDef.HWND; import com.sun.jna.platform.win32.WinUser; /** * An abstraction for the functions of the Selenium web driver. * It depends minimally on UI for width adjustments. */ public class BrowserComponent { private static final Logger logger = LogManager.getLogger(BrowserComponent.class.getName()); private static final boolean USE_MOBILE_USER_AGENT = false; private boolean isTestChromeDriver; // Chrome, Android 4.2.2, Samsung Galaxy S4 private static final String MOBILE_USER_AGENT = "Mozilla/5.0 (Linux; Android 4.2.2; GT-I9505 Build/JDQ39)" + "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.59 Mobile Safari/537.36"; private static final String CHROME_DRIVER_LOCATION = "browserview/"; private static final String CHROME_DRIVER_BINARY_NAME = determineChromeDriverBinaryName(); private String pageContentOnLoad = ""; private static final int SWP_NOSIZE = 0x0001; private static final int SWP_NOMOVE = 0x0002; private static final int SWP_NOACTIVATE = 0x0010; private static HWND browserWindowHandle; private static User32 user32; private final UI ui; private ChromeDriverEx driver = null; // We want browser commands to be run on a separate thread, but not to // interfere with each other. This executor is limited to a single instance, // so it ensures that browser commands are queued and executed in sequence. // The alternatives would be to: // - allow race conditions // - interrupt the blocking WebDriver::get method // The first is not desirable and the second does not seem to be possible // at the moment. private Executor executor; public BrowserComponent(UI ui, boolean isTestChromeDriver) { this.ui = ui; executor = Executors.newSingleThreadExecutor(); this.isTestChromeDriver = isTestChromeDriver; setupJNA(); setupChromeDriverExecutable(); } /** * Called on application startup. Blocks until the driver is created. * Guaranteed to only happen once. */ public void initialise() { assert driver == null; executor.execute(() -> { driver = createChromeDriver(); logger.info("Successfully initialised browser component and ChromeDriver"); }); login(); } /** * Called when application quits. Guaranteed to only happen once. */ public void onAppQuit() { quit(); removeChromeDriverIfNecessary(); } /** * Quits the browser component. */ private void quit() { logger.info("Quitting browser component"); // The application may quit before the browser is initialised. // In that case, do nothing. if (driver != null) { try { driver.quit(); } catch (WebDriverException e) { // Chrome was closed; do nothing } } } /** * Creates, initialises, and returns a ChromeDriver. * @return */ private ChromeDriverEx createChromeDriver() { ChromeOptions options = new ChromeOptions(); if (USE_MOBILE_USER_AGENT) { options.addArguments(String.format("user-agent=\"%s\"", MOBILE_USER_AGENT)); } ChromeDriverEx driver = new ChromeDriverEx(options, isTestChromeDriver); WebDriver.Options manage = driver.manage(); if (!isTestChromeDriver) { manage.window().setPosition(new Point((int) ui.getCollapsedX(), 0)); manage.window().setSize(new Dimension((int) ui.getAvailableDimensions().getWidth(), (int) ui.getAvailableDimensions().getHeight())); initialiseJNA(); } return driver; } private void removeChromeDriverIfNecessary() { if (ui.getCommandLineArgs().containsKey(UI.ARG_UPDATED_TO)) { boolean success = new File(CHROME_DRIVER_BINARY_NAME).delete(); if (!success) { logger.warn("Failed to delete chromedriver"); } } } /** * Executes Javascript in the currently-active driver window. * Run on the UI thread (will block until execution is complete, * i.e. change implementation if long-running scripts must be run). * @param script */ private void executeJavaScript(String script) { driver.executeScript(script); logger.info("Executed JavaScript " + script.substring(0, Math.min(script.length(), 10))); } /** * Navigates to the New Label page on GitHub. * Run on a separate thread. */ public void newLabel() { logger.info("Navigating to New Label page"); runBrowserOperation(() -> driver.get(GitHubURL.getPathForNewLabel(ui.logic.getDefaultRepo()), false)); bringToTop(); } /** * Navigates to the New Milestone page on GitHub. * Run on a separate thread. */ public void newMilestone() { logger.info("Navigating to New Milestone page"); runBrowserOperation(() -> driver.get(GitHubURL.getPathForNewMilestone(ui.logic.getDefaultRepo()), false)); bringToTop(); } /** * Navigates to the New Issue page on GitHub. * Run on a separate thread. */ public void newIssue() { logger.info("Navigating to New Issue page"); runBrowserOperation(() -> driver.get(GitHubURL.getPathForNewIssue(ui.logic.getDefaultRepo()), false)); bringToTop(); } /** * Navigates to the HubTurbo documentation page. * Run on a separate thread. */ public void showDocs() { logger.info("Showing documentation page"); runBrowserOperation(() -> driver.get(GitHubURL.DOCS_PAGE, false)); } /** * Navigates to the GitHub changelog page. * Run on a separate thread. */ // public void showChangelog(String version) { // logger.info("Showing changelog for version " + version); // runBrowserOperation(() -> driver.get(GitHubURL.getChangelogForVersion(version))); /** * Navigates to the GitHub page for the given issue in the currently-active * driver window. * Run on a separate thread. */ public void showIssue(String repoId, int id, boolean isPullRequest, boolean isForceRefresh) { if (isPullRequest) { logger.info("Showing pull request runBrowserOperation(() -> driver.get(GitHubURL.getPathForPullRequest(repoId, id), isForceRefresh)); } else { logger.info("Showing issue runBrowserOperation(() -> driver.get(GitHubURL.getPathForIssue(repoId, id), isForceRefresh)); } } public void jumpToComment(){ if (isTestChromeDriver) { UI.events.triggerEvent(new JumpToCommentEvent()); } try { WebElement comment = driver.findElementById("new_comment_field"); comment.click(); bringToTop(); } catch (Exception e) { logger.warn("Unable to reach jump to comments. "); } } private boolean isBrowserActive(){ if (driver == null) return false; try { // Throws an exception if unable to switch to original HT tab // which then triggers a browser reset when called from runBrowserOperation WebDriver.TargetLocator switchTo = driver.switchTo(); String windowHandle = driver.getWindowHandle(); if (!isTestChromeDriver) switchTo.window(windowHandle); // When the HT tab is closed (but the window is still alive), // a lot of the operations on the driver (such as getCurrentURL) // will hang (without throwing an exception, the thread will just freeze the UI forever), // so we cannot use getCurrentURL/getTitle to check if the original HT tab // is still open. The above line does not hang the driver but still throws // an exception, thus letting us detect that the HT tab is not active any more. return true; } catch (WebDriverException e) { logger.warn("Unable to reach bview. "); return false; } } // A helper function for reseting browser. private void resetBrowser(){ logger.info("Relaunching chrome."); quit(); // if the driver hangs driver = createChromeDriver(); login(); } /** * A helper function for running browser operations. * Takes care of running it on a separate thread, and normalises error-handling across * all types of code. */ private void runBrowserOperation (Runnable operation) { executor.execute(() -> { if (isBrowserActive()) { try { operation.run(); pageContentOnLoad = getCurrentPageSource(); } catch (WebDriverException e) { switch (BrowserComponentError.fromErrorMessage(e.getMessage())) { case NoSuchWindow: resetBrowser(); runBrowserOperation(operation); // Recurse and repeat break; case NoSuchElement: logger.info("Warning: no such element! " + e.getMessage()); break; default: break; } } } else { logger.info("Chrome window not responding."); resetBrowser(); runBrowserOperation(operation); } }); } /** * Logs in the currently-active driver window using the credentials * supplied by the user on login to the app. * Run on a separate thread. */ public void login() { logger.info("Logging in on GitHub..."); focus(ui.getMainWindowHandle()); runBrowserOperation(() -> { driver.get(GitHubURL.LOGIN_PAGE, false); try { WebElement searchBox = driver.findElement(By.name("login")); searchBox.sendKeys(ui.logic.loginController.credentials.username); searchBox = driver.findElement(By.name("password")); searchBox.sendKeys(ui.logic.loginController.credentials.password); searchBox.submit(); } catch (Exception e) { // Already logged in; do nothing logger.info("Unable to login, may already be logged in. "); } }); } /** * One-time JNA setup. */ private static void setupJNA() { if (PlatformSpecific.isOnWindows()) user32 = User32.INSTANCE; } /** * JNA initialisation. Should happen whenever the Chrome window is recreated. */ private void initialiseJNA() { if (PlatformSpecific.isOnWindows()) { browserWindowHandle = user32.FindWindow(null, "data:, - Google Chrome"); } } public static String determineChromeDriverBinaryName() { if (PlatformSpecific.isOnMac()) { logger.info("Using chrome driver binary: chromedriver_2-16"); return "chromedriver_2-16"; } else if (PlatformSpecific.isOnWindows()) { logger.info("Using chrome driver binary: chromedriver_2-16.exe"); return "chromedriver_2-16.exe"; } else if (PlatformSpecific.isOn32BitsLinux()) { logger.info("Using chrome driver binary: chromedriver_linux_2-16"); return "chromedriver_linux_2-16"; } else if (PlatformSpecific.isOn64BitsLinux()) { logger.info("Using chrome driver binary: chromedriver_linux_x86_64_2-16"); return "chromedriver_linux_x86_64_2-16"; } else { logger.error("Unable to determine platform for chrome driver"); logger.info("Using chrome driver binary: chromedriver_linux_2-16"); return "chromedriver_linux_2-16"; } } /** * Ensures that the chromedriver executable is in the project root before * initialisation. Since executables are packaged for all platforms, this also * picks the right version to use. */ private static void setupChromeDriverExecutable() { File f = new File(CHROME_DRIVER_BINARY_NAME); if (!f.exists()) { InputStream in = BrowserComponent.class.getClassLoader() .getResourceAsStream(CHROME_DRIVER_LOCATION + CHROME_DRIVER_BINARY_NAME); assert in != null : "Could not find " + CHROME_DRIVER_BINARY_NAME + " at " + CHROME_DRIVER_LOCATION + "; this path must be updated if the executables are moved"; OutputStream out; try { out = new FileOutputStream(CHROME_DRIVER_BINARY_NAME); IOUtils.copy(in, out); out.close(); f.setExecutable(true); } catch (IOException e) { logger.error("Could not load Chrome driver binary! " + e.getLocalizedMessage(), e); } logger.info("Could not find " + CHROME_DRIVER_BINARY_NAME + "; extracted it from jar"); } else { logger.info("Located " + CHROME_DRIVER_BINARY_NAME); } System.setProperty("webdriver.chrome.driver", CHROME_DRIVER_BINARY_NAME); } private void bringToTop(){ if (PlatformSpecific.isOnWindows()) { user32.ShowWindow(browserWindowHandle, WinUser.SW_RESTORE); user32.SetForegroundWindow(browserWindowHandle); } } public void focus(HWND mainWindowHandle){ if (PlatformSpecific.isOnWindows()) { // Restores browser window if it is minimized / maximized user32.ShowWindow(browserWindowHandle, WinUser.SW_SHOWNOACTIVATE); // SWP_NOMOVE and SWP_NOSIZE prevents the 0,0,0,0 parameters from taking effect. user32.SetWindowPos(browserWindowHandle, mainWindowHandle, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); user32.SetForegroundWindow(mainWindowHandle); } } private String getCurrentPageSource() { return StringEscapeUtils.escapeHtml4( (String) driver.executeScript("return document.documentElement.outerHTML")); } public boolean hasBviewChanged() { if (isTestChromeDriver) return true; if (isBrowserActive()) { if (getCurrentPageSource().equals(pageContentOnLoad)) return false; pageContentOnLoad = getCurrentPageSource(); return true; } return false; } public void scrollToTop() { String script = "window.scrollTo(0, 0)"; executeJavaScript(script); } public void scrollToBottom() { String script = "window.scrollTo(0, document.body.scrollHeight)"; executeJavaScript(script); } public void scrollPage(boolean isDownScroll) { String script; if (isDownScroll) script = "window.scrollBy(0,100)"; else script = "window.scrollBy(0, -100)"; executeJavaScript(script); } private void sendKeysToBrowser(String keyCode) { if (isTestChromeDriver) { UI.events.triggerEvent(new SendKeysToBrowserEvent(keyCode)); } WebElement body; try { body = driver.findElementByTagName("body"); body.sendKeys(keyCode); } catch (Exception e) { logger.error("No such element"); } } public void manageAssignees(String keyCode) { sendKeysToBrowser(keyCode.toLowerCase()); bringToTop(); } public void manageMilestones(String keyCode) { sendKeysToBrowser(keyCode.toLowerCase()); bringToTop(); } public void showIssues() { logger.info("Navigating to Issues page"); runBrowserOperation(() -> driver.get(GitHubURL.getPathForAllIssues(ui.logic.getDefaultRepo()), false)); } public void showPullRequests() { logger.info("Navigating to Pull requests page"); runBrowserOperation(() -> driver.get(GitHubURL.getPathForPullRequests(ui.logic.getDefaultRepo()), false)); } public void showKeyboardShortcuts() { logger.info("Navigating to Keyboard Shortcuts"); runBrowserOperation(() -> driver.get(GitHubURL.KEYBOARD_SHORTCUTS_PAGE, false)); } public void showMilestones() { logger.info("Navigating to Milestones page"); runBrowserOperation(() -> driver.get(GitHubURL.getPathForMilestones(ui.logic.getDefaultRepo()), false)); } public void showContributors() { logger.info("Navigating to Contributors page"); runBrowserOperation(() -> driver.get(GitHubURL.getPathForContributors(ui.logic.getDefaultRepo()), false)); } public boolean isCurrentUrlIssue() { return driver != null && GitHubURL.isUrlIssue(driver.getCurrentUrl()); } public String getCurrentUrl() { return driver.getCurrentUrl(); } }
package tachyon.master; import java.io.IOException; import java.nio.ByteBuffer; import java.util.List; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import junit.framework.Assert; import org.apache.commons.codec.binary.Base64; import org.junit.Test; /** * Unit Test for EditLogOperation */ public class EditLogOperationTest { private static final String CREATE_DEPENDENCY_TYPE = "{\"type\":\"CREATE_DEPENDENCY\"," + "\"parameters\":{\"parents\":[1,2,3],\"commandPrefix\":\"fake command\"," + "\"dependencyId\":1,\"frameworkVersion\":\"0.3\",\"data\":[\"AAAAAAAAAAAAAA==\"]," + "\"children\":[4,5,6,7]," + "\"comment\":\"Comment Test\",\"creationTimeMs\":1409349750338," + "\"dependencyType\":\"Narrow\",\"framework\":\"Tachyon Examples\"}}"; private static final ObjectMapper OBJECT_MAPPER = JsonObject.createObjectMapper(); // Tests for CREATE_DEPENDENCY operation @Test public void createDependencyTest() throws IOException { EditLogOperation editLogOperation = OBJECT_MAPPER.readValue(CREATE_DEPENDENCY_TYPE.getBytes(), EditLogOperation.class); // get all parameters for "CREATE_DEPENDENCY" List<Integer> parents = editLogOperation.get("parents", new TypeReference<List<Integer>>() {}); Assert.assertEquals(3, parents.size()); List<Integer> children = editLogOperation.get("children", new TypeReference<List<Integer>>() {}); Assert.assertEquals(4, children.size()); String commandPrefix = editLogOperation.getString("commandPrefix"); Assert.assertEquals("fake command", commandPrefix); List<ByteBuffer> data = editLogOperation.getByteBufferList("data"); Assert.assertEquals(1, data.size()); String decodedBase64 = new String(data.get(0).array(), "UTF-8"); Assert.assertEquals(new String (Base64.decodeBase64("AAAAAAAAAAAAAA==")), decodedBase64); String comment = editLogOperation.getString("comment"); Assert.assertEquals("Comment Test", comment); String framework = editLogOperation.getString("framework"); Assert.assertEquals("Tachyon Examples", framework); String frameworkVersion = editLogOperation.getString("frameworkVersion"); Assert.assertEquals("0.3", frameworkVersion); DependencyType dependencyType = editLogOperation.get("dependencyType", DependencyType.class); Assert.assertEquals(DependencyType.Narrow, dependencyType); Integer depId = editLogOperation.getInt("dependencyId"); Assert.assertEquals(1, depId.intValue()); Long creationTimeMs = editLogOperation.getLong("creationTimeMs"); Assert.assertEquals(1409349750338L, creationTimeMs.longValue()); } }
package uk.org.ulcompsoc.ld32.systems; import java.util.ArrayList; import com.badlogic.ashley.core.Engine; import uk.org.ulcompsoc.ld32.LD32; import uk.org.ulcompsoc.ld32.components.Player; import uk.org.ulcompsoc.ld32.components.Tower; import uk.org.ulcompsoc.ld32.components.Wallet; import uk.org.ulcompsoc.ld32.util.Mappers; import uk.org.ulcompsoc.ld32.util.TextureManager; import uk.org.ulcompsoc.ld32.util.TextureName; import com.badlogic.ashley.core.Entity; import com.badlogic.ashley.core.EntitySystem; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.math.Vector3; public class GUIRenderSystem extends EntitySystem { private final Batch batch; private final TextureManager textureManager; private OrthographicCamera camera; private Engine engine = null; private boolean processing = false; // different textures private TextureRegion frame = null; private TextureRegion redBallIcon = null; private TextureRegion blueBallIcon = null; private TextureRegion greenBallIcon = null; private TextureRegion zero = null; private TextureRegion one = null; private TextureRegion two = null; private TextureRegion three = null; private TextureRegion four = null; private TextureRegion five = null; private TextureRegion six = null; private TextureRegion seven = null; private TextureRegion eight = null; private TextureRegion nine = null; private final Entity playerEntity; public static Entity selectedTowerEntity = null; // Default coordinates for drawing elements in predefined positions private final Vector3 DFLT_POSITION_OF_THE_FRAME = new Vector3(0.0f, 0.0f, 0.0f); private final Vector3 DFLT_POSITION_OF_THE_RED_BALL = new Vector3(120.0f, 150.0f, 0.0f); private final Vector3 DFLT_POSITION_OF_THE_GREEN_BALL = new Vector3(120.0f, 250.0f, 0.0f); private final Vector3 DFLT_POSITION_OF_THE_BLUE_BALL = new Vector3(120.0f, 350.f, 0.0f); private final Vector3 DFLT_RED_1_DIGIT_POSITION = new Vector3(120.0f, 95.0f, 0.0f); private final Vector3 DFLT_RED_2_DIGIT_POSITION = new Vector3(155.0f, 95.0f, 0.0f); private final Vector3 DFLT_GREEN_1_DIGIT_POSITION = new Vector3(120.0f, 195.0f, 0.0f); private final Vector3 DFLT_GREEN_2_DIGIT_POSITION = new Vector3(155.0f, 195.0f, 0.0f); private final Vector3 DFLT_BLUE_1_DIGIT_POSITION = new Vector3(120.0f, 295.0f, 0.0f); private final Vector3 DFLT_BLUE_2_DIGIT_POSITION = new Vector3(155.0f, 295.0f, 0.0f); private final Vector3 DFLT_TOWER_STAT_RED = null; private final Vector3 DFLT_TOWER_STAT_BLUE = null; private final Vector3 DFLT_TOWER_STAT_GREEN = null; private Vector3 temp; @SuppressWarnings("unchecked") public GUIRenderSystem(int priority, final Batch batch, final OrthographicCamera cam, final Entity playerEntity) { super(priority); this.batch = batch; this.textureManager = LD32.textureManager; this.camera = cam; this.playerEntity = playerEntity; this.frame = new TextureRegion(textureManager.nameMap.get(TextureName.FRAME_1)); this.redBallIcon = new TextureRegion(textureManager.nameMap.get(TextureName.BALL_R)); this.blueBallIcon = new TextureRegion(textureManager.nameMap.get(TextureName.BALL_B)); this.greenBallIcon = new TextureRegion(textureManager.nameMap.get(TextureName.BALL_G)); this.zero = new TextureRegion(textureManager.nameMap.get(TextureName.ZERO)); this.one = new TextureRegion(textureManager.nameMap.get(TextureName.ONE)); this.two = new TextureRegion(textureManager.nameMap.get(TextureName.TWO)); this.three = new TextureRegion(textureManager.nameMap.get(TextureName.THREE)); this.four = new TextureRegion(textureManager.nameMap.get(TextureName.FOUR)); this.five = new TextureRegion(textureManager.nameMap.get(TextureName.FIVE)); this.six = new TextureRegion(textureManager.nameMap.get(TextureName.SIX)); this.seven = new TextureRegion(textureManager.nameMap.get(TextureName.SEVEN)); this.eight = new TextureRegion(textureManager.nameMap.get(TextureName.EIGHT)); this.nine = new TextureRegion(textureManager.nameMap.get(TextureName.NINE)); } @Override public void addedToEngine(Engine engine) { this.engine = engine; processing = true; } @Override public void removedFromEngine(Engine engine) { this.engine = null; processing = false; } @Override public void update(float deltaTime) { Wallet wallet = Mappers.walletMapper.get(playerEntity); // int screenWidth = Gdx.graphics.getWidth(); // int screenHeight = Gdx.graphics.getHeight(); camera.update(); temp = camera.unproject(DFLT_POSITION_OF_THE_FRAME.cpy()); batch.setProjectionMatrix(camera.combined); int redcount = wallet.red; int bluecount = wallet.blue; int greencount = wallet.green; final float scale = 0.68f; final float w = frame.getRegionWidth() * scale; final float h = frame.getRegionHeight() * scale; batch.begin(); // batch.draw(frame, temp.x, temp.y-h , screenWidth*0.1f, h); batch.draw(frame, temp.x, temp.y - h, w, h); temp = camera.unproject(DFLT_POSITION_OF_THE_RED_BALL.cpy()); batch.draw(redBallIcon, temp.x, temp.y); temp = camera.unproject(DFLT_POSITION_OF_THE_BLUE_BALL.cpy()); batch.draw(blueBallIcon, temp.x, temp.y); temp = camera.unproject(DFLT_POSITION_OF_THE_GREEN_BALL.cpy()); batch.draw(greenBallIcon, temp.x, temp.y); this.handleACounter(redcount, batch, DFLT_RED_1_DIGIT_POSITION.cpy(), DFLT_RED_2_DIGIT_POSITION.cpy()); this.handleACounter(bluecount, batch, DFLT_BLUE_1_DIGIT_POSITION.cpy(), DFLT_BLUE_2_DIGIT_POSITION.cpy()); this.handleACounter(greencount, batch, DFLT_GREEN_1_DIGIT_POSITION.cpy(), DFLT_GREEN_2_DIGIT_POSITION.cpy()); // batch.draw(textureManager., x, y, originX, originY, width, height, // scaleX, scaleY, rotation); if (selectedTowerEntity != null) { Tower tower = Mappers.towerMapper.get(selectedTowerEntity); if (tower != null) { //String dropRate = "Drop Rate "+tower.dropRate; //String r ="Attack Speed "+ tower.fireDelay+"s"; //handleACounter(tower.red.getStage(), batch, new Vector3(110.0f, 350.0f, 0.0f), new Vector3(130.0f, // 350.0f, 0.0f)); //textureManager.makeWord(this.engine, dropRate, 130, 350); } } /** * Score */ handleScore(batch); batch.end(); } protected void handleACounter(int counter, Batch batch, final Vector3 vector1, final Vector3 vector2) { float scalefactor = 0.3f; float newWidth = zero.getRegionWidth() * scalefactor; float newHeight = zero.getRegionHeight() * scalefactor; String toBreakDown; if (counter > 9) { if (counter > 99) { toBreakDown = "99"; } else { toBreakDown = counter + ""; } temp = camera.unproject(vector1); batch.draw(this.getNumber(Integer.parseInt(toBreakDown.substring(0, 1))), temp.x, (temp.y - newWidth), newWidth, newHeight); temp = camera.unproject(vector2); batch.draw(this.getNumber(Integer.parseInt(toBreakDown.substring(1))), temp.x, (temp.y - newWidth), newWidth, newHeight); } else { temp = camera.unproject(vector2); batch.draw(this.getNumber(counter), temp.x, (temp.y - newWidth), newWidth, newHeight); } } protected void handleScore(Batch batch) { float scalefactor = 0.1f; float newWidth = zero.getRegionWidth() * scalefactor; float newHeight = zero.getRegionHeight() * scalefactor; int score = Player.score; ArrayList<Integer> characters = new ArrayList<Integer>(); while (score > 0) { characters.add(score % 10); score /= 10; } Vector3 start = camera.unproject(new Vector3(Gdx.graphics.getWidth() /2 - newWidth * characters.size(), Gdx.graphics.getHeight() / 10, 0.0f)); float SPACER_MULTIPLIER = newWidth; float space = 0.0f; for (int i = characters.size() - 1; i >= 0; i batch.draw(this.getNumber(characters.get(i)), start.x + space, (start.y), newWidth, newHeight); space += SPACER_MULTIPLIER; } } private TextureRegion getNumber(int number) { switch (number) { case 0: return this.zero; case 1: return this.one; case 2: return this.two; case 3: return this.three; case 4: return this.four; case 5: return this.five; case 6: return this.six; case 7: return this.seven; case 8: return this.eight; case 9: return this.nine; default: return null; } } }
package catastrophe.web; import java.util.List; import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.GET; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.Context; import javax.ws.rs.core.GenericType; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import catastrophe.cats.Score; import catastrophe.discovery.ServiceFinder; @Path("cat") public class RestCatStuff { private static final String CAT_PATH = "/rest/cats"; private static final String USERS_PATH = "/rest/users"; private static final String SCORING_PATH = "/rest/scoring"; Client client = ClientBuilder.newClient(); @PUT @Path("score") @Produces(MediaType.APPLICATION_JSON) public Score score(@QueryParam("encodedImage") String encodedImage, @Context HttpServletRequest request) { // Get user from session String userName = (String) request.getSession().getAttribute("cat.user"); System.out.println(userName + " put in a guess of " + encodedImage); String host = new ServiceFinder().getHostAndPort(CAT_PATH); if (host != null) { String scoreHost = new ServiceFinder().getHostAndPort(SCORING_PATH); String scorePath = SCORING_PATH + "/score/"; System.out.println("Requesting " + scoreHost + scorePath); WebTarget scoreTarget = client.target("http://" + scoreHost).path(scorePath).queryParam("encodedImage", encodedImage); Score score = scoreTarget.request(MediaType.APPLICATION_JSON).get(Score.class); System.out.println("Going to update " + userName + " with a score of " + score + "."); String usersHost = new ServiceFinder().getHostAndPort(USERS_PATH); String updateScorePath = USERS_PATH + "/updateScore/"; System.out.println("Requesting " + usersHost + updateScorePath); WebTarget authTarget = client.target("http://" + usersHost).path(updateScorePath) .queryParam("userName", userName).queryParam("score", score.getScore()) .queryParam("image", encodedImage); Response response = authTarget.request(MediaType.APPLICATION_JSON).post(null); System.out.println("Score update response is " + response.getStatus()); return score; } return null; } @SuppressWarnings("rawtypes") @GET @Path("scores") @Produces(MediaType.APPLICATION_JSON) public List getLeaderboard() { String host = new ServiceFinder().getHostAndPort(USERS_PATH); if (host != null) { String authPath = USERS_PATH + "/leaderboard"; System.out.println("Requesting " + authPath); WebTarget target = client.target("http://" + host).path(authPath); List response = target.request(MediaType.APPLICATION_JSON).get(new GenericType<List>(List.class)); return response; } else { System.out.println("No provider for service " + USERS_PATH); return null; } } @SuppressWarnings("rawtypes") @GET @Path("cats") @Produces(MediaType.APPLICATION_JSON) public Set getCats() { String host = new ServiceFinder().getHostAndPort(CAT_PATH); if (host != null) { WebTarget target = client.target("http://" + host).path(CAT_PATH + "/cats"); Set response = target.request(MediaType.APPLICATION_JSON).get(new GenericType<Set>(Set.class)); return response; } else { System.out.println("No provider for service " + CAT_PATH); return null; } } }
package co.rewen.statex; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteStatement; import android.net.Uri; import android.support.v4.content.LocalBroadcastManager; import com.facebook.common.logging.FLog; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.Callback; import com.facebook.react.bridge.GuardedAsyncTask; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.WritableArray; import com.facebook.react.bridge.WritableMap; import com.facebook.react.common.ReactConstants; import com.facebook.react.common.SetBuilder; import com.facebook.react.modules.common.ModuleDataCleaner; import java.util.ArrayList; import java.util.HashSet; import static co.rewen.statex.StateXDatabaseSupplier.KEY_COLUMN; import static co.rewen.statex.StateXDatabaseSupplier.TABLE_STATE; import static co.rewen.statex.StateXDatabaseSupplier.VALUE_COLUMN; public final class StateXModule extends ReactContextBaseJavaModule implements ModuleDataCleaner.Cleanable { // SQL variable number limit, defined by SQLITE_LIMIT_VARIABLE_NUMBER: private static final int MAX_SQL_KEYS = 999; private StateXDatabaseSupplier mStateXDatabaseSupplier; private boolean mShuttingDown = false; public StateXModule(ReactApplicationContext reactContext) { super(reactContext); mStateXDatabaseSupplier = new StateXDatabaseSupplier(reactContext); } @Override public String getName() { return "StateX"; } @Override public void initialize() { super.initialize(); mShuttingDown = false; } @Override public void onCatalystInstanceDestroy() { mShuttingDown = true; } @Override public void clearSensitiveData() { // Clear local storage. If fails, crash, since the app is potentially in a bad state and could // cause a privacy violation. We're still not recovering from this well, but at least the error // will be reported to the server. clear( new Callback() { @Override public void invoke(Object... args) { if (args.length == 0) { FLog.d(ReactConstants.TAG, "Cleaned StateX."); return; } // Clearing the database has failed, delete it instead. if (mStateXDatabaseSupplier.deleteDatabase()) { FLog.d(ReactConstants.TAG, "Deleted Local Database StateX."); return; } // Everything failed, crash the app throw new RuntimeException("Clearing and deleting database failed: " + args[0]); } }); } /** * Given an array of keys, this returns a map of (key, value) pairs for the keys found, and * (key, null) for the keys that haven't been found. */ @ReactMethod public void multiGet(final ReadableArray keys, final Callback callback) { if (keys == null) { callback.invoke(AsyncStorageErrorUtil.getInvalidKeyError(null), null); return; } new GuardedAsyncTask<Void, Void>(getReactApplicationContext()) { @Override protected void doInBackgroundGuarded(Void... params) { if (!ensureDatabase()) { callback.invoke(AsyncStorageErrorUtil.getDBError(null), null); return; } String[] columns = {KEY_COLUMN, VALUE_COLUMN}; HashSet<String> keysRemaining = SetBuilder.newHashSet(); WritableArray data = Arguments.createArray(); for (int keyStart = 0; keyStart < keys.size(); keyStart += MAX_SQL_KEYS) { int keyCount = Math.min(keys.size() - keyStart, MAX_SQL_KEYS); Cursor cursor = mStateXDatabaseSupplier.get().query( TABLE_STATE, columns, AsyncLocalStorageUtil.buildKeySelection(keyCount), AsyncLocalStorageUtil.buildKeySelectionArgs(keys, keyStart, keyCount), null, null, null); keysRemaining.clear(); try { if (cursor.getCount() != keys.size()) { // some keys have not been found - insert them with null into the final array for (int keyIndex = keyStart; keyIndex < keyStart + keyCount; keyIndex++) { keysRemaining.add(keys.getString(keyIndex)); } } if (cursor.moveToFirst()) { do { WritableArray row = Arguments.createArray(); row.pushString(cursor.getString(0)); row.pushString(cursor.getString(1)); data.pushArray(row); keysRemaining.remove(cursor.getString(0)); } while (cursor.moveToNext()); } } catch (Exception e) { FLog.w(ReactConstants.TAG, e.getMessage(), e); callback.invoke(AsyncStorageErrorUtil.getError(null, e.getMessage()), null); return; } finally { cursor.close(); } for (String key : keysRemaining) { WritableArray row = Arguments.createArray(); row.pushString(key); row.pushNull(); data.pushArray(row); } keysRemaining.clear(); } callback.invoke(null, data); } }.execute(); } /** * Inserts multiple (key, value) pairs. If one or more of the pairs cannot be inserted, this will * return StateXFailure, but all other pairs will have been inserted. * The insertion will replace conflicting (key, value) pairs. */ @ReactMethod public void multiSet(final ReadableArray keyValueArray, final Callback callback) { if (keyValueArray.size() == 0) { callback.invoke(AsyncStorageErrorUtil.getInvalidKeyError(null)); return; } new GuardedAsyncTask<Void, Void>(getReactApplicationContext()) { @Override protected void doInBackgroundGuarded(Void... params) { if (!ensureDatabase()) { callback.invoke(AsyncStorageErrorUtil.getDBError(null)); return; } String sql = "INSERT OR REPLACE INTO " + TABLE_STATE + " VALUES (?, ?);"; SQLiteStatement statement = mStateXDatabaseSupplier.get().compileStatement(sql); WritableMap error = null; ArrayList<String> keys = new ArrayList<>(); try { mStateXDatabaseSupplier.get().beginTransaction(); for (int idx = 0; idx < keyValueArray.size(); idx++) { if (keyValueArray.getArray(idx).size() != 2) { error = AsyncStorageErrorUtil.getInvalidValueError(null); break; } String key = keyValueArray.getArray(idx).getString(0); if (key == null) { error = AsyncStorageErrorUtil.getInvalidKeyError(null); break; } String value = keyValueArray.getArray(idx).getString(1); if (value == null) { error = AsyncStorageErrorUtil.getInvalidValueError(null); break; } keys.add(key); statement.clearBindings(); statement.bindString(1, key); statement.bindString(2, value); statement.execute(); } mStateXDatabaseSupplier.get().setTransactionSuccessful(); } catch (Exception e) { FLog.w(ReactConstants.TAG, e.getMessage(), e); error = AsyncStorageErrorUtil.getError(null, e.getMessage()); } finally { try { mStateXDatabaseSupplier.get().endTransaction(); } catch (Exception e) { FLog.w(ReactConstants.TAG, e.getMessage(), e); if (error == null) { error = AsyncStorageErrorUtil.getError(null, e.getMessage()); } } } if (error != null) { callback.invoke(error); } else { callback.invoke(); notifyStateChanged(keys); } } }.execute(); } /** * Removes all rows of the keys given. */ @ReactMethod public void multiRemove(final ReadableArray keys, final Callback callback) { if (keys.size() == 0) { callback.invoke(AsyncStorageErrorUtil.getInvalidKeyError(null)); return; } new GuardedAsyncTask<Void, Void>(getReactApplicationContext()) { @Override protected void doInBackgroundGuarded(Void... params) { if (!ensureDatabase()) { callback.invoke(AsyncStorageErrorUtil.getDBError(null)); return; } WritableMap error = null; try { mStateXDatabaseSupplier.get().beginTransaction(); for (int keyStart = 0; keyStart < keys.size(); keyStart += MAX_SQL_KEYS) { int keyCount = Math.min(keys.size() - keyStart, MAX_SQL_KEYS); mStateXDatabaseSupplier.get().delete( TABLE_STATE, AsyncLocalStorageUtil.buildKeySelection(keyCount), AsyncLocalStorageUtil.buildKeySelectionArgs(keys, keyStart, keyCount)); } mStateXDatabaseSupplier.get().setTransactionSuccessful(); } catch (Exception e) { FLog.w(ReactConstants.TAG, e.getMessage(), e); error = AsyncStorageErrorUtil.getError(null, e.getMessage()); } finally { try { mStateXDatabaseSupplier.get().endTransaction(); } catch (Exception e) { FLog.w(ReactConstants.TAG, e.getMessage(), e); if (error == null) { error = AsyncStorageErrorUtil.getError(null, e.getMessage()); } } } if (error != null) { callback.invoke(error); } else { callback.invoke(); notifyStateChanged(StateX.toStringArray(keys)); } } }.execute(); } /** * Given an array of (key, value) pairs, this will merge the given values with the stored values * of the given keys, if they exist. */ @ReactMethod public void multiMerge(final ReadableArray keyValueArray, final Callback callback) { new GuardedAsyncTask<Void, Void>(getReactApplicationContext()) { @Override protected void doInBackgroundGuarded(Void... params) { if (!ensureDatabase()) { callback.invoke(AsyncStorageErrorUtil.getDBError(null)); return; } WritableMap error = null; ArrayList<String> keys = new ArrayList<>(); try { mStateXDatabaseSupplier.get().beginTransaction(); for (int idx = 0; idx < keyValueArray.size(); idx++) { if (keyValueArray.getArray(idx).size() != 2) { error = AsyncStorageErrorUtil.getInvalidValueError(null); return; } String key = keyValueArray.getArray(idx).getString(0); if (key == null) { error = AsyncStorageErrorUtil.getInvalidKeyError(null); return; } else { keys.add(key); } if (keyValueArray.getArray(idx).getString(1) == null) { error = AsyncStorageErrorUtil.getInvalidValueError(null); return; } if (!AsyncLocalStorageUtil.mergeImpl( mStateXDatabaseSupplier.get(), key, keyValueArray.getArray(idx).getString(1))) { error = AsyncStorageErrorUtil.getDBError(null); return; } } mStateXDatabaseSupplier.get().setTransactionSuccessful(); } catch (Exception e) { FLog.w(ReactConstants.TAG, e.getMessage(), e); error = AsyncStorageErrorUtil.getError(null, e.getMessage()); } finally { try { mStateXDatabaseSupplier.get().endTransaction(); } catch (Exception e) { FLog.w(ReactConstants.TAG, e.getMessage(), e); if (error == null) { error = AsyncStorageErrorUtil.getError(null, e.getMessage()); } } } if (error != null) { callback.invoke(error); } else { callback.invoke(); notifyStateChanged(keys); } } }.execute(); } /** * Clears the database. */ @ReactMethod public void clear(final Callback callback) { new GuardedAsyncTask<Void, Void>(getReactApplicationContext()) { @Override protected void doInBackgroundGuarded(Void... params) { if (!mStateXDatabaseSupplier.ensureDatabase()) { callback.invoke(AsyncStorageErrorUtil.getDBError(null)); return; } try { mStateXDatabaseSupplier.get().delete(TABLE_STATE, null, null); callback.invoke(); } catch (Exception e) { FLog.w(ReactConstants.TAG, e.getMessage(), e); callback.invoke(AsyncStorageErrorUtil.getError(null, e.getMessage())); } } }.execute(); } /** * Returns an array with all keys from the database. */ @ReactMethod public void getAllKeys(final Callback callback) { new GuardedAsyncTask<Void, Void>(getReactApplicationContext()) { @Override protected void doInBackgroundGuarded(Void... params) { if (!ensureDatabase()) { callback.invoke(AsyncStorageErrorUtil.getDBError(null), null); return; } WritableArray data = Arguments.createArray(); String[] columns = {KEY_COLUMN}; Cursor cursor = mStateXDatabaseSupplier.get() .query(TABLE_STATE, columns, null, null, null, null, null); try { if (cursor.moveToFirst()) { do { data.pushString(cursor.getString(0)); } while (cursor.moveToNext()); } } catch (Exception e) { FLog.w(ReactConstants.TAG, e.getMessage(), e); callback.invoke(AsyncStorageErrorUtil.getError(null, e.getMessage()), null); return; } finally { cursor.close(); } callback.invoke(null, data); } }.execute(); } /** * Verify the database is open for reads and writes. */ private boolean ensureDatabase() { return !mShuttingDown && mStateXDatabaseSupplier.ensureDatabase(); } private void notifyStateChanged(ArrayList<String> keys) { /*Intent intent = new Intent(StateX.ACTION_STATE_CHANGED); intent.putStringArrayListExtra(StateX.EXTRA_KEYS, keys);*/ LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance( getReactApplicationContext()); for (String key : keys) { Intent intent = new Intent(StateX.ACTION_STATE_CHANGED); Uri uri = StateX.uriForKey(key); intent.setData(uri); broadcastManager.sendBroadcast(intent); } } }
package com.akiban.qp.rowtype; import com.akiban.ais.model.*; import java.util.*; // UserTable RowTypes are indexed by the UserTable's RowDef's ordinal. Derived RowTypes get higher values. public class Schema extends DerivedTypesSchema { public UserTableRowType userTableRowType(UserTable table) { return (UserTableRowType) rowTypes.get(table.getTableId()); } public IndexRowType indexRowType(Index index) { // TODO: Group index schema is always ""; need another way to // check for group _table_ index. if (false) assert ais.getTable(index.getIndexName().getSchemaName(), index.getIndexName().getTableName()).isUserTable() : index; return index.isTableIndex() ? userTableRowType((UserTable) index.leafMostTable()).indexRowType(index) : groupIndexRowType((GroupIndex) index); } public Set<UserTableRowType> userTableTypes() { Set<UserTableRowType> userTableTypes = new HashSet<UserTableRowType>(); for (AisRowType rowType : rowTypes.values()) { if (rowType instanceof UserTableRowType) { if (!rowType.userTable().isAISTable()) { userTableTypes.add((UserTableRowType) rowType); } } } return userTableTypes; } public Set<RowType> allTableTypes() { Set<RowType> userTableTypes = new HashSet<RowType>(); for (RowType rowType : rowTypes.values()) { if (rowType instanceof UserTableRowType) { userTableTypes.add(rowType); } } return userTableTypes; } public List<IndexRowType> groupIndexRowTypes() { return groupIndexRowTypes; } public Schema(AkibanInformationSchema ais) { this.ais = ais; // Create RowTypes for AIS UserTables for (UserTable userTable : ais.getUserTables().values()) { UserTableRowType userTableRowType = new UserTableRowType(this, userTable); int tableTypeId = userTableRowType.typeId(); rowTypes.put(tableTypeId, userTableRowType); typeIdToLeast(userTableRowType.typeId()); } // Create RowTypes for AIS TableIndexes for (UserTable userTable : ais.getUserTables().values()) { UserTableRowType userTableRowType = userTableRowType(userTable); for (TableIndex index : userTable.getIndexesIncludingInternal()) { IndexRowType indexRowType = IndexRowType.createIndexRowType(this, userTableRowType, index); userTableRowType.addIndexRowType(indexRowType); rowTypes.put(indexRowType.typeId(), indexRowType); } } // Create RowTypes for AIS GroupIndexes for (Group group : ais.getGroups().values()) { for (GroupIndex groupIndex : group.getIndexes()) { IndexRowType indexRowType = IndexRowType.createIndexRowType(this, userTableRowType(groupIndex.leafMostTable()), groupIndex); rowTypes.put(indexRowType.typeId(), indexRowType); groupIndexRowTypes.add(indexRowType); } } } public AkibanInformationSchema ais() { return ais; } // For use by this package // For use by this class private IndexRowType groupIndexRowType(GroupIndex groupIndex) { for (IndexRowType groupIndexRowType : groupIndexRowTypes) { if (groupIndexRowType.index() == groupIndex) { return groupIndexRowType; } } return null; } // Object state private final AkibanInformationSchema ais; private final Map<Integer, AisRowType> rowTypes = new HashMap<Integer, AisRowType>(); private final List<IndexRowType> groupIndexRowTypes = new ArrayList<IndexRowType>(); }
package com.auto.test.utils; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.text.SimpleDateFormat; import java.util.Date; public class DateUtil { public static void main(String[] args) { System.out.println(getFormatDateTime(getNetworkTime())); System.out.println(getFormatDateTime(getSystemTime())); setSystemDateTime(null); } /** * (date) * @param date */ public static void setSystemDateTime(Date date){ date = (date == null) ? getNetworkTime() : date; String os = System.getProperty("os.name"); if(os.toLowerCase().contains("windows")){ String dateCom[] = {"cmd", "/c", "date", getFormatDateWin(date)}; exeCommand(dateCom); String timeCom[] = {"cmd", "/c", "time", getFormatTime(date)}; exeCommand(timeCom); }else if(os.toLowerCase().contains("linux")){ String dateCom[] = {"date", "-s", getFormatDateLinux(date)}; exeCommand(dateCom); String timeCom[] = {"date", "-s", getFormatTime(date)}; exeCommand(timeCom); } } /** * * @return */ public static Date getSystemTime(){ return new Date(); } /** * * @return */ public static Date getNetworkTime(){ try{ URL url = new URL("http: URLConnection urlConn = url.openConnection(); urlConn.connect(); long time = urlConn.getDate(); return new Date(time); }catch(MalformedURLException e){ e.printStackTrace(); }catch(IOException e){ e.printStackTrace(); } return null; } private static void exeCommand(String[] command){ Process process = null; try { process = Runtime.getRuntime().exec(command); process.waitFor(); } catch (Exception e) { e.printStackTrace(); } finally { if(process != null){ process.destroy(); } } } public static String date2String(Date date, String format){ return new SimpleDateFormat(format).format(date); } public static String getFormatDateTime(Date date){ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return sdf.format(date); } public static String getFormatDateWin(Date date){ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); return sdf.format(date); } public static String getFormatDateLinux(Date date){ SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); return sdf.format(date); } public static String getFormatTime(Date date){ SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); return sdf.format(date); } }
package com.blobcity.db; import com.blobcity.db.search.SearchParam; import com.blobcity.db.annotations.Entity; import com.blobcity.db.config.Credentials; import com.blobcity.db.annotations.Primary; import com.blobcity.db.exceptions.DbOperationException; import com.blobcity.db.exceptions.InternalAdapterException; import com.blobcity.db.exceptions.InternalDbException; import com.blobcity.db.search.Query; import com.blobcity.db.search.StringUtil; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * This class provides the connection and query execution framework for performing operations on the BlobCity data store. This class must be extended by any * Model that represents a BlobCity Entity. * * @author Sanket Sarang * @author Karishma * @author Karun AB <karun.ab@blobcity.net> * @version 1.0 * @since 1.0 */ public abstract class CloudStorage { private String table = null; private String db = null; public CloudStorage() { for (Annotation annotation : this.getClass().getAnnotations()) { if (annotation instanceof Entity) { final Entity blobCityEntity = (Entity) annotation; table = blobCityEntity.table(); if (StringUtil.isEmpty(blobCityEntity.db())) { db = blobCityEntity.db(); } if (StringUtil.isEmpty(table)) { table = this.getClass().getSimpleName(); } break; } } if (table == null) { table = this.getClass().getSimpleName(); } TableStore.getInstance().registerClass(table, this.getClass()); } // Public static methods public static <T extends CloudStorage> T newInstance(Class<T> clazz) { try { return clazz.newInstance(); } catch (InstantiationException ex) { throw new InternalAdapterException("An error has occurred in the adapter. Check stack trace for more details.", ex); } catch (IllegalAccessException ex) { throw new InternalAdapterException("An error has occurred in the adapter. Check stack trace for more details.", ex); } } public static <T extends CloudStorage> T newInstance(Class<T> clazz, Object pk) { try { T obj = clazz.newInstance(); obj.setPk(pk); return obj; } catch (InstantiationException ex) { throw new InternalAdapterException("An error has occurred in the adapter. Check stack trace for more details.", ex); } catch (IllegalAccessException ex) { throw new InternalAdapterException("An error has occurred in the adapter. Check stack trace for more details.", ex); } } public static <T extends CloudStorage> T newLoadedInstance(Class<T> clazz, Object pk) { try { T obj = clazz.newInstance(); obj.setPk(pk); if (obj.load()) { return obj; } return null; } catch (InstantiationException ex) { throw new InternalAdapterException("An error has occurred in the adapter. Check stack trace for more details.", ex); } catch (IllegalAccessException ex) { throw new InternalAdapterException("An error has occurred in the adapter. Check stack trace for more details.", ex); } } public static <T extends CloudStorage> List<Object> selectAll(Class<T> clazz) { return selectAll(clazz, Object.class); } public static <T extends CloudStorage, P extends Object> List<P> selectAll(final Class<T> clazz, final Class<P> returnTypeClazz) { JSONObject responseJson = postStaticRequest(Credentials.getInstance(), clazz, QueryType.SELECT_ALL); JSONArray jsonArray; List<P> list; try { if (responseJson.getInt(QueryConstants.ACK) == 1) { jsonArray = responseJson.getJSONArray(QueryConstants.KEYS); list = new ArrayList<P>(); for (int i = 0; i < jsonArray.length(); i++) { list.add(dataTypeTransform((P) jsonArray.getString(i), returnTypeClazz)); } return list; } throw new DbOperationException(responseJson.getString(QueryConstants.CODE), responseJson.optString(QueryConstants.CAUSE)); } catch (JSONException ex) { throw new InternalDbException("Error in API JSON response", ex); } } public static <T extends CloudStorage> boolean contains(final Object key) { return contains(Credentials.getInstance(), key); } public static <T extends CloudStorage> boolean contains(final Credentials credentials, final Object key) { JSONObject responseJson = postStaticRequest(credentials, QueryType.CONTAINS, key); try { if ("1".equals(responseJson.getString(QueryConstants.ACK))) { return responseJson.getBoolean("contains"); } throw new DbOperationException(responseJson.getString(QueryConstants.CODE), responseJson.optString(QueryConstants.CAUSE)); } catch (JSONException ex) { throw new InternalDbException("Error in API JSON response", ex); } } public static <T extends CloudStorage> void remove(final Object pk) { remove(Credentials.getInstance(), pk); } public static <T extends CloudStorage> void remove(final Credentials credentials, final Object pk) { JSONObject responseJson = postStaticRequest(credentials, QueryType.REMOVE, pk); try { if ("0".equals(responseJson.getString(QueryConstants.ACK))) { throw new DbOperationException(responseJson.getString(QueryConstants.CODE), responseJson.optString(QueryConstants.CAUSE)); } } catch (JSONException ex) { throw new InternalDbException("Error in API JSON response", ex); } } public static <T extends CloudStorage> List<T> search(final Query<T> query) { return search(Credentials.getInstance(), query); } public static <T extends CloudStorage> List<T> search(final Credentials credentials, final Query<T> query) { if (query.getFromTables() == null && query.getFromTables().isEmpty()) { throw new InternalAdapterException("No table name set. Table name is a mandatory field queries."); } final String queryStr = query.asSql(); final String responseString = QueryExecuter.executeSql(DbQueryRequest.create(credentials, queryStr)); final JSONObject responseJson; try { responseJson = new JSONObject(responseString); } catch (JSONException ex) { throw new InternalDbException("Error in processing request/response JSON", ex); } try { final Class<T> clazz = query.getFromTables().get(0); if ("1".equals(responseJson.getString(QueryConstants.ACK))) { final JSONArray resultJsonArray = responseJson.getJSONArray(QueryConstants.PAYLOAD); final int resultCount = resultJsonArray.length(); final List<T> responseList = new ArrayList<T>(); final String tableName = CloudStorage.getTableName(clazz); TableStore.getInstance().registerClass(tableName, clazz); final Map<String, Field> structureMap = TableStore.getInstance().getStructure(tableName); for (int i = 0; i < resultCount; i++) { final T instance = CloudStorage.newInstance(clazz); final JSONObject instanceData = resultJsonArray.getJSONObject(i); final Iterator<String> columnNameIterator = instanceData.keys(); while (columnNameIterator.hasNext()) { final String columnName = columnNameIterator.next(); final Field field = structureMap.get(columnName); final boolean oldAccessibilityValue = field.isAccessible(); field.setAccessible(true); try { field.set(instance, getCastedValue(field, instanceData.get(columnName), clazz)); } catch (JSONException ex) { throw new InternalDbException("Error in processing JSON. Class: " + clazz + " Request: " + instanceData.toString(), ex); } catch (IllegalArgumentException ex) { throw new InternalAdapterException("An error has occurred in the adapter. Check stack trace for more details.", ex); } catch (IllegalAccessException ex) { throw new InternalAdapterException("An error has occurred in the adapter. Check stack trace for more details.", ex); } finally { field.setAccessible(oldAccessibilityValue); } } responseList.add(instance); } return responseList; } throw new DbOperationException(responseJson.getString(QueryConstants.CODE), responseJson.optString(QueryConstants.CAUSE)); } catch (JSONException ex) { throw new InternalDbException("Error in API JSON response", ex); } } /** * Allows quick search queries on a single column. This method internally uses {@link #search(com.blobcity.db.search.Query) } * * @see #search(com.blobcity.db.search.Query) * @param <T> Any class reference which extends {@link CloudStorage} * @param clazz class reference who's data is to be searched * @param columnName column to be searched * @param values values to be used to filter data in column * @return {@link List} of {@code T} that matches {@code searchParams} */ public static <T extends CloudStorage> List<T> select(final Class<T> clazz, final String columnName, final Object... values) { return search(Query.table(clazz).where(SearchParam.create(columnName).in(values))); } public static <T extends CloudStorage> List<T> filter(Class<T> clazz, String filterName) { throw new UnsupportedOperationException("Not supported yet."); } /** * Statically provides the table name for any instance/child of {@link CloudStorage} that is internally used by the adapter for querying. Note, this method * is not used by the adapter internally but the logic here, should be kept in sync with the rest of the class to ensure table names are evaluated * appropriately. This method can be used for logging purposes where the table name for a class is required. * * @param <T> Any class reference which extends {@link CloudStorage} * @param clazz class reference who's table name is required * @return Name of the table */ public static <T extends CloudStorage> String getTableName(final Class<T> clazz) { final Entity entity = (Entity) clazz.getAnnotation(Entity.class); return entity != null && !StringUtil.isEmpty(entity.table()) ? entity.table() : clazz.getSimpleName(); } /** * Statically provides the db name for any instance/child of {@link CloudStorage} that is internally used by the adapter for querying. Note, this method is * used by the adapter internally for SQL queries and the logic here should be kept in sync with the rest of the class to ensure db names are evaluated * appropriately. This method can be used for logging purposes where the db name for a class is required. * * @param <T> Any class reference which extends {@link CloudStorage} * @param clazz class reference who's db name is required * @return Name of the DB */ public static <T extends CloudStorage> String getDbName(final Class<T> clazz) { final Entity entity = (Entity) clazz.getAnnotation(Entity.class); return entity != null && !StringUtil.isEmpty(entity.db()) ? entity.db() : Credentials.getInstance().getDb(); } public static <T extends CloudStorage> Object invokeProc(final String storedProcedureName, final String... params) { return invokeProc(Credentials.getInstance(), storedProcedureName, params); } // TODO: Complete method implementation This method is clearly not complete. public static <T extends CloudStorage> Object invokeProc(final Credentials credentials, final String storedProcedureName, final String... params) { final JSONObject responseJson = postStaticProcRequest(credentials, QueryType.STORED_PROC, storedProcedureName, params); try { /* If ack:0 then check for error code and report accordingly */ if ("0".equals(responseJson.getString(QueryConstants.ACK))) { final String cause = responseJson.optString(QueryConstants.CAUSE); final String code = responseJson.optString(QueryConstants.CODE); throw new DbOperationException(code, cause); } final Object payloadObj = responseJson.get(QueryConstants.PAYLOAD); if (payloadObj instanceof CloudStorage) { return "1 obj"; } else if (payloadObj instanceof JSONArray) { return ((JSONArray) payloadObj).length() + " objs"; } return payloadObj; } catch (JSONException ex) { throw new InternalDbException("Error in API JSON response", ex); } } // Public instance methods public boolean load() { return load(Credentials.getInstance()); } public void save() { save(Credentials.getInstance()); } public boolean insert() { return insert(Credentials.getInstance()); } public void remove() { remove(Credentials.getInstance()); } /** * Gets a JSON representation of the object. The column names are same as those loaded in {@link TableStore} * * @return {@link JSONObject} representing the entity class in its current state */ public JSONObject asJson() { try { return toJson(); } catch (IllegalArgumentException ex) { throw new InternalAdapterException("An error has occurred in the adapter. Check stack trace for more details.", ex); } catch (IllegalAccessException ex) { throw new InternalAdapterException("An error has occurred in the adapter. Check stack trace for more details.", ex); } } // Protected instance methods protected void setPk(Object pk) { final Field primaryKeyField = TableStore.getInstance().getPkField(table); final boolean accessible = primaryKeyField.isAccessible(); try { if (!accessible) { primaryKeyField.setAccessible(true); } primaryKeyField.set(this, pk); } catch (IllegalArgumentException ex) { throw new InternalAdapterException("An error has occurred in the adapter. Check stack trace for more details.", ex); } catch (IllegalAccessException ex) { throw new InternalAdapterException("An error has occurred in the adapter. Check stack trace for more details.", ex); } finally { if (!accessible) { primaryKeyField.setAccessible(false); } } } // Private static methods private static <T extends CloudStorage> JSONObject postStaticProcRequest(final Credentials credentials, final QueryType queryType, final String name, final String[] params) { final Map<String, Object> queryParamMap = new HashMap<String, Object>(); queryParamMap.put(QueryConstants.QUERY, queryType.getQueryCode()); final Map<String, Object> paramsMap = new HashMap<String, Object>(); paramsMap.put("name", name); paramsMap.put("params", new JSONArray(params != null ? Arrays.asList(params) : null)); queryParamMap.put(QueryConstants.PAYLOAD, new JSONObject(paramsMap)); final String responseString = QueryExecuter.executeBql(DbQueryRequest.create(credentials, new JSONObject(queryParamMap).toString())); try { final JSONObject responseJson = new JSONObject(responseString); return responseJson; } catch (JSONException ex) { throw new InternalDbException("Error in processing request/response JSON", ex); } } /** * Transforms data type of a column dynamically leveraging Java Type Erasure. Currently supports all types that can be used as primary keys in tables. * * @param <P> Requested data format class parameter * @param value value to be transformed * @param returnTypeClazz Class object in who's image the {@code value} has to be transformed * @return transformed data object to an appropriate type */ private static <P extends Object> P dataTypeTransform(final P value, final Class<P> returnTypeClazz) { if (returnTypeClazz == Integer.class) { return (P) Integer.valueOf(value.toString()); } if (returnTypeClazz == Float.class) { return (P) Float.valueOf(value.toString()); } if (returnTypeClazz == Long.class) { return (P) Long.valueOf(value.toString()); } if (returnTypeClazz == Double.class) { return (P) Double.valueOf(value.toString()); } // String return value; } /** * Provides a standard service to cast input types from JSON's format ({@link Integer}, {@link String}, {@link JSONArray} etc.) to Java's internal data * types. * * @param field field in current {@link Object} that needs to be updated * @param value value to be set for the field * @param parentClazz {@link Class} value of the parent object for which the casted field is being requested. This field is only required for proper error * logging in case of exceptions * @return appropriately casted value */ private static Object getCastedValue(final Field field, final Object value, final Class<?> parentClazz) { final Class<?> type = field.getType(); if (type == String.class) { // Pre-exit most common use cases if (value.getClass() == JSONObject.NULL.getClass()) { return null; } return value; } if (type.isEnum()) { return "".equals(value.toString()) ? null : Enum.valueOf((Class<? extends Enum>) type, value.toString()); } if (type == Double.TYPE || type == Double.class) { return new Double(value.toString()); } if (type == Float.TYPE || type == Float.class) { return new Float(value.toString()); } if (type == Character.TYPE || type == Character.class) { return value.toString().charAt(0); } if (type == Boolean.TYPE || type == Boolean.class) { return Boolean.valueOf(value.toString()); } if (type == BigDecimal.class) { return new BigDecimal(value.toString()); } if (type == java.util.Date.class) { return new java.util.Date(Long.valueOf(value.toString())); } if (type == java.sql.Date.class) { return new java.sql.Date(Long.valueOf(value.toString())); } // Note: This code is unnecessary but is kept here to show that these values are supported and if tomorrow, // the return type of the DB changes to String instead of an int/long in JSON, this code shold be uncommented // if (type == Integer.TYPE || type == Integer.class) { // should be unnecessary // return new Integer(value.toString()); // if (type == Long.TYPE || type == Long.class) { // should be unnecessary // return new Long(value.toString()); if (type == List.class) { // doesn't always return inside this block, BEWARE! if (value instanceof JSONArray) { final JSONArray arr = (JSONArray) value; final int length = arr.length(); final List<Object> list = new ArrayList(length); for (int i = 0; i < length; i++) { list.add(arr.opt(i)); } return list; } else if ((value instanceof String && "".equals(value)) || value.getClass() == JSONObject.NULL.getClass()) { return new ArrayList(); } Logger.getLogger(CloudStorage.class.getName()).log(Level.WARNING, "Class of type \"{0}\" has field with name \"{1}\" and data type \"{2}\" for value to be set was \"{3}\" has a type of {4}. This will probably cause an exception.", new Object[]{parentClazz, field.getName(), type, value, value.getClass()}); } // The if for List check does not always return a value. Be sure before putting any code below here // String & any other weird type return value; } private static <T extends CloudStorage> JSONObject postStaticRequest(final Credentials credentials, final Class<T> clazz, final QueryType queryType) { final Entity entity = (Entity) clazz.getAnnotation(Entity.class); final Map<String, Object> requestMap = new HashMap<String, Object>(); final String tableName = entity != null && entity.table() != null && !"".equals(entity.table()) ? entity.table() : clazz.getSimpleName(); final boolean entityContainsDbName = entity != null && entity.db() != null && !"".equals(entity.db()); final String db = entityContainsDbName ? entity.db() : credentials.getDb(); // No NPEs here because entityContainsDbName handles that final Credentials dbSpecificCredentials = entityContainsDbName ? Credentials.create(credentials, null, null, null, db) : credentials; requestMap.put(QueryConstants.TABLE, tableName); requestMap.put(QueryConstants.QUERY, queryType.getQueryCode()); final String queryStr = new JSONObject(requestMap).toString(); try { final String responseString = QueryExecuter.executeBql(DbQueryRequest.create(dbSpecificCredentials, queryStr)); final JSONObject responseJson = new JSONObject(responseString); return responseJson; } catch (JSONException ex) { throw new InternalDbException("Error in processing request/response JSON", ex); } } private static <T extends CloudStorage> JSONObject postStaticRequest(final Credentials credentials, final QueryType queryType, final Object pk) { try { final Map<String, Object> queryMap = new HashMap<String, Object>(); queryMap.put(QueryConstants.QUERY, queryType.getQueryCode()); queryMap.put(QueryConstants.PRIMARY_KEY, pk); final String queryStr = new JSONObject(queryMap).toString(); final String responseString = QueryExecuter.executeBql(DbQueryRequest.create(credentials, queryStr)); final JSONObject responseJson = new JSONObject(responseString); return responseJson; } catch (JSONException ex) { throw new InternalDbException("Error in processing request/response JSON", ex); } } // Private instance methods private boolean load(final Credentials credentials) { JSONObject responseJson; JSONObject payloadJson; responseJson = postRequest(credentials, QueryType.LOAD); try { /* If ack:0 then check for error code and report accordingly */ if ("0".equals(responseJson.getString(QueryConstants.ACK))) { if ("DB200".equals(responseJson.getString(QueryConstants.CODE))) { return false; } else { reportIfError(responseJson); } } payloadJson = responseJson.getJSONObject(QueryConstants.PAYLOAD); fromJson(payloadJson); return true; } catch (JSONException ex) { throw new InternalDbException("Error in API JSON response", ex); } } private void save(final Credentials credentials) { JSONObject responseJson = postRequest(credentials, QueryType.SAVE); reportIfError(responseJson); } private boolean insert(final Credentials credentials) { JSONObject responseJson = postRequest(credentials, QueryType.INSERT); try { if ("1".equals(responseJson.getString(QueryConstants.ACK))) { final JSONObject payloadJson = responseJson.getJSONObject(QueryConstants.PAYLOAD); fromJson(payloadJson); return true; } else if ("0".equals(responseJson.getString(QueryConstants.ACK))) { if ("DB201".equals(responseJson.getString(QueryConstants.CODE))) { return false; } /* * considering conditions before this and the code in {@link #reportIfError(JSONObject)}, this call will always result in an exception. */ reportIfError(responseJson); } throw new InternalAdapterException("Unknown acknowledgement code from the database. Expected: [0, 1]. Actual: " + responseJson.getString(QueryConstants.ACK)); } catch (Exception ex) { reportIfError(responseJson); throw new InternalAdapterException("Exception occurred in the adapter.", ex); } } private void remove(final Credentials credentials) { final JSONObject responseJson = postRequest(credentials, QueryType.REMOVE); try { /* If ack:0 then check for error code and report accordingly */ if ("0".equals(responseJson.getString(QueryConstants.ACK)) && !"DB200".equals(responseJson.getString(QueryConstants.CODE))) { reportIfError(responseJson); } } catch (JSONException ex) { throw new InternalDbException("Error in API JSON response", ex); } } /** * Instantiates current object with data from the provided {@link JSONObject}. * * Every column mentioned in the {@link CloudStorage} instance (as maintained by {@link TableStore}) will be loaded with data. If any of these column name * IDs do not exist in the provided {@link JSONObject}, an {@link InternalDbException} will be thrown. If there are any issues whilst reflecting the data * into the instance, an {@link InternalAdapterException} will be thrown. * * If any data already exists the calling object in any field mapped as a column, the data will be overwritten and lost. * * @param jsonObject input {@link JSONObject} from which the data for the current instance are to be loaded. */ private void fromJson(final JSONObject jsonObject) { final Map<String, Field> structureMap = TableStore.getInstance().getStructure(table); for (final String columnName : structureMap.keySet()) { final Field field = structureMap.get(columnName); try { setFieldValue(field, jsonObject.get(columnName)); } catch (JSONException ex) { throw new InternalDbException("Error in processing JSON. Class: " + this.getClass() + " Request: " + jsonObject.toString(), ex); } catch (IllegalArgumentException ex) { throw new InternalAdapterException("An error has occurred in the adapter. Check stack trace for more details.", ex); } catch (IllegalAccessException ex) { throw new InternalAdapterException("An error has occurred in the adapter. Check stack trace for more details.", ex); } } } private JSONObject postRequest(final Credentials credentials, QueryType queryType) { JSONObject responseJson; try { final Map<String, Object> queryParamMap = new HashMap<String, Object>(); queryParamMap.put(QueryConstants.TABLE, table); queryParamMap.put(QueryConstants.QUERY, queryType.getQueryCode()); final Credentials dbSpecificCredentials = db != null ? Credentials.create(credentials, null, null, null, db) : credentials; switch (queryType) { case LOAD: case REMOVE: queryParamMap.put(QueryConstants.PRIMARY_KEY, getPrimaryKeyValue()); break; case INSERT: case SAVE: queryParamMap.put(QueryConstants.PAYLOAD, toJson()); break; default: throw new InternalDbException("Attempting to executed unknown or unidentifed query"); } final String queryStr = new JSONObject(queryParamMap).toString(); final String responseString = QueryExecuter.executeBql(DbQueryRequest.create(dbSpecificCredentials, queryStr)); responseJson = new JSONObject(responseString); return responseJson; } catch (JSONException ex) { throw new InternalDbException("Error in processing request/response JSON", ex); } catch (IllegalArgumentException ex) { throw new InternalAdapterException("An error has occurred in the adapter. Check stack trace for more details.", ex); } catch (IllegalAccessException ex) { throw new InternalAdapterException("An error has occurred in the adapter. Check stack trace for more details.", ex); } } private JSONObject toJson() throws IllegalArgumentException, IllegalAccessException { final Map<String, Field> structureMap = TableStore.getInstance().getStructure(table); final Map<String, Object> dataMap = new HashMap<String, Object>(); for (String columnName : structureMap.keySet()) { final Field field = structureMap.get(columnName); final boolean accessible = field.isAccessible(); field.setAccessible(true); try { if (field.getType().isEnum()) { dataMap.put(columnName, field.get(this) != null ? field.get(this).toString() : null); continue; } else if (field.getType() == java.util.Date.class) { dataMap.put(columnName, field.get(this) != null ? ((java.util.Date) field.get(this)).getTime() : null); continue; } else if (field.getType() == java.sql.Date.class) { dataMap.put(columnName, field.get(this) != null ? ((java.sql.Date) field.get(this)).getTime() : null); continue; } dataMap.put(columnName, field.get(this)); } catch (IllegalAccessException iae) { throw iae; } finally { field.setAccessible(accessible); } } return new JSONObject(dataMap); } private void reportIfError(JSONObject jsonObject) { try { if (!"1".equals(jsonObject.getString(QueryConstants.ACK))) { final String code = jsonObject.optString(QueryConstants.CODE); final String cause = jsonObject.optString(QueryConstants.CAUSE); throw new DbOperationException(code, cause); } } catch (JSONException ex) { throw new InternalDbException("Error in API JSON response", ex); } } private Object getPrimaryKeyValue() throws IllegalArgumentException, IllegalAccessException { Map<String, Field> structureMap = TableStore.getInstance().getStructure(table); for (String columnName : structureMap.keySet()) { Field field = structureMap.get(columnName); if (field.getAnnotation(Primary.class) != null) { final boolean accessible = field.isAccessible(); field.setAccessible(true); try { final Object value = field.get(this); return value; } catch (IllegalAccessException iae) { throw iae; } finally { field.setAccessible(accessible); } } } return null; } private void setFieldValue(final Field field, final Object value) throws IllegalAccessException { final boolean oldAccessibilityValue = field.isAccessible(); field.setAccessible(true); try { field.set(this, getCastedValue(field, value, this.getClass())); } catch (IllegalAccessException iae) { throw iae; } finally { field.setAccessible(oldAccessibilityValue); } } }
package com.gameminers.visage; import java.io.File; import java.util.Arrays; import java.util.logging.ConsoleHandler; import java.util.logging.Formatter; import java.util.logging.Level; import java.util.logging.Logger; import org.fusesource.jansi.AnsiConsole; import joptsimple.OptionParser; import joptsimple.OptionSet; import joptsimple.OptionSpec; import com.gameminers.visage.benchmark.VisageBenchmark; import com.gameminers.visage.master.VisageMaster; import com.gameminers.visage.slave.VisageSlave; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; public class Visage { public static final String VERSION = "2.0.0"; public static final Formatter logFormat = new VisageFormatter(); public static final Logger log = Logger.getLogger("com.gameminers.visage"); public static boolean ansi; public static void main(String[] args) throws Exception { AnsiConsole.systemInstall(); Thread.currentThread().setName("Main thread"); ConsoleHandler con = new ConsoleHandler(); con.setFormatter(logFormat); log.setUseParentHandlers(false); log.addHandler(con); if (Boolean.parseBoolean(System.getProperty("com.gameminers.visage.trace"))) { log.setLevel(Level.ALL); con.setLevel(Level.ALL); } else if (Boolean.parseBoolean(System.getProperty("com.gameminers.visage.debug"))) { log.setLevel(Level.FINER); con.setLevel(Level.FINER); } else { log.setLevel(Level.FINE); con.setLevel(Level.FINE); } OptionParser parser = new OptionParser(); parser.acceptsAll(Arrays.asList("master", "m"), "Start Visage as a master"); parser.acceptsAll(Arrays.asList("slave", "s"), "Start Visage as a slave"); parser.acceptsAll(Arrays.asList("benchmark", "b"), "Run a benchmark on the current machine"); OptionSpec<File> fileSwitch; fileSwitch = parser.acceptsAll(Arrays.asList("config", "c"), "Load the given config file instead of the default conf/[mode].conf").withRequiredArg().ofType(File.class); OptionSet set = parser.parse(args); File confFile = fileSwitch.value(set); if (set.has("master")) { if (confFile == null) { confFile = new File("conf/master.conf"); } Config conf = ConfigFactory.parseFile(confFile); ansi = conf.getBoolean("ansi"); log.info("Starting Visage v"+VERSION+" as a master"); new VisageMaster(conf).start(); } else if (set.has("benchmark")) { ansi = true; log.info("Running a benchmark..."); new VisageBenchmark().start(); } else { if (confFile == null) { confFile = new File("conf/slave.conf"); } Config conf = ConfigFactory.parseFile(confFile); ansi = conf.getBoolean("ansi"); log.info("Starting Visage v"+VERSION+" as a slave"); new VisageSlave(conf).start(); } } }
package com.gooddata.processor; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import com.gooddata.connector.AbstractConnector; import com.gooddata.connector.CsvConnector; import com.gooddata.connector.GaConnector; import com.gooddata.exceptions.InvalidArgumentException; import com.gooddata.google.analytics.GaQuery; import com.gooddata.integration.ftp.GdcFTPApiWrapper; import com.gooddata.integration.model.DLI; import com.gooddata.integration.model.DLIPart; import com.gooddata.integration.rest.GdcRESTApiWrapper; import com.gooddata.integration.rest.configuration.NamePasswordConfiguration; import com.gooddata.integration.rest.exceptions.GdcLoginException; import com.gooddata.util.FileUtil; /** * The GoodData Data Integration CLI processor. * * @author jiri.zaloudek * @author Zdenek Svoboda <zd@gooddata.org> * @version 1.0 */ public class GdcDI { private final String ftpHost; private final String host; private final String userName; private final String password; private GdcRESTApiWrapper _restApi = null; private GdcFTPApiWrapper _ftpApi = null; private String projectId = null; private AbstractConnector connector = null; private GdcDI(final String host, final String userName, final String password) throws GdcLoginException { String ftpHost = null; // Create the FTP host automatically String[] hcs = host.split("\\."); if(hcs != null && hcs.length > 0) { for(String hc : hcs) { if(ftpHost != null && ftpHost.length()>0) ftpHost += "." + hc; else ftpHost = hc + "-upload"; } } else { throw new IllegalArgumentException("Invalid format of the GoodData REST API host: " + host); } this.host = host; this.ftpHost = ftpHost; this.userName = userName; this.password = password; } private void setProject(String projectId) { this.projectId = projectId; } public void execute(final String commandsStr) throws Exception { List<Command> cmds = new ArrayList<Command>(); cmds.addAll(parseCmd(commandsStr)); for(Command command : cmds) { processCommand(command); } } private GdcRESTApiWrapper getRestApi() throws GdcLoginException { if (_restApi == null) { if (userName == null || password == null) { throw new IllegalArgumentException( "Please specify both GoodData username (-u or --username) and password (-p or --password) command-line options"); } final NamePasswordConfiguration httpConfiguration = new NamePasswordConfiguration( "https", host, userName, password); _restApi = new GdcRESTApiWrapper(httpConfiguration); _restApi.login(); } return _restApi; } private GdcFTPApiWrapper getFtpApi() { if (_ftpApi == null) { System.out.println("Using the GoodData FTP host '" + ftpHost + "'."); NamePasswordConfiguration ftpConfiguration = new NamePasswordConfiguration("ftp", ftpHost, userName, password); _ftpApi = new GdcFTPApiWrapper(ftpConfiguration); } return _ftpApi; } /** * The main CLI processor * @param args command line argument * @throws Exception any issue */ public static void main(String[] args) throws Exception { String userName = null; String password = null; String host = "secure.gooddata.com"; Options o = new Options(); o.addOption("u", "username", true, "GoodData username"); o.addOption("p", "password", true, "GoodData password"); o.addOption("h", "host", true, "GoodData host"); o.addOption("i", "project", true, "GoodData project identifier (a string like nszfbgkr75otujmc4smtl6rf5pnmz9yl)"); o.addOption("e", "execute", true, "Commands and params to execute before the commands in provided files"); CommandLineParser parser = new GnuParser(); CommandLine line = parser.parse(o, args); try { if(line.hasOption("host")) { host = line.getOptionValue("host"); } else { System.out.println("Using the default GoodData REST API host '" + host + "'."); } GdcDI gdcDi = new GdcDI(host, userName, password); if (line.hasOption("project")) { gdcDi.setProject(line.getOptionValue("project")); } if (line.hasOption("execute")) { gdcDi.execute(line.getOptionValue("execute")); } if (line.getArgs().length == 0 && !line.hasOption("execute")) { printErrorHelpandExit("No command has been given, quitting", o); } for (final String arg : line.getArgs()) { gdcDi.execute(FileUtil.readStringFromFile(arg)); } } catch (final IllegalArgumentException e) { printErrorHelpandExit(e.getMessage(), o); } } /** * Parses the commands * @param cmd commands string * @return array of commands * @throws InvalidArgumentException in case there is an invalid command */ protected static List<Command> parseCmd(String cmd) throws InvalidArgumentException { if(cmd != null && cmd.length()>0) { List<Command> cmds = new ArrayList<Command>(); String[] commands = cmd.split(";"); for( String component : commands) { component = component.trim(); if(component != null && component.length() > 0 && !component.startsWith(" Pattern p = Pattern.compile(".*?\\(.*?\\)"); Matcher m = p.matcher(component); if(!m.matches()) throw new InvalidArgumentException("Invalid command: "+component); p = Pattern.compile(".*?\\("); m = p.matcher(component); String command = ""; if(m.find()) { command = m.group(); command = command.substring(0, command.length() - 1); } else { throw new InvalidArgumentException("Can't extract command from: "+component); } p = Pattern.compile("\\(.*?\\)"); m = p.matcher(component); Properties args = new Properties(); if(m.find()) { String as = m.group(); as = as.substring(1,as.length()-1); try { args.load(new StringReader(as.replace(",","\n"))); } catch (IOException e) { throw new InvalidArgumentException(e.getMessage()); } } else { throw new InvalidArgumentException("Can't extract command from: "+component); } cmds.add(new Command(command, args)); } } return cmds; } throw new InvalidArgumentException("Can't parse command."); } /** * Returns the help for commands * @return help text */ protected static String commandsHelp() throws Exception { try { final InputStream is = GdcDI.class.getResourceAsStream("/com/gooddata/processor/COMMANDS.txt"); if (is == null) throw new IOException(); return FileUtil.readStringFromStream(is); } catch (IOException e) { throw new Exception("Could not read com/gooddata/processor/COMMANDS.txt"); } } /** * Prints an err message, help and exits with status code 1 * @param err the err message * @param o options */ protected static void printErrorHelpandExit(String err, Options o) throws Exception { HelpFormatter formatter = new HelpFormatter(); System.out.println("ERROR: " + err); System.out.println(commandsHelp()); System.exit(1); } /** * Executes the command * @param command to execute * @throws Exception general error */ private void processCommand(Command command) throws Exception { if(command.getCommand().equalsIgnoreCase("CreateProject")) { String name = (String)command.getParameters().get("name"); String desc = (String)command.getParameters().get("desc"); if(name != null && name.length() > 0) { if(desc != null && desc.length() > 0) projectId = getRestApi().createProject(name, desc); else projectId = getRestApi().createProject(name, name); System.out.println("Project id = '"+projectId+"' created."); } else throw new IllegalArgumentException("CreateProject: Command requires the 'name' parameter."); } if(command.getCommand().equalsIgnoreCase("OpenProject")) { String id = (String)command.getParameters().get("id"); if(id != null && id.length() > 0) { projectId = id; } else { throw new IllegalArgumentException("OpenProject: Command requires the 'id' parameter."); } } if(command.getCommand().equalsIgnoreCase("GenerateCsvConfigTemplate")) { String configFile = (String)command.getParameters().get("configFile"); String csvHeaderFile = (String)command.getParameters().get("csvHeaderFile"); if(configFile != null && configFile.length() > 0) { File cf = new File(configFile); if(csvHeaderFile != null && csvHeaderFile.length() > 0) { File csvf = new File(csvHeaderFile); if(csvf.exists()) { CsvConnector.saveConfigTemplate(configFile, csvHeaderFile); } else throw new IllegalArgumentException( "GenerateCsvConfigTemplate: File '" + csvHeaderFile + "' doesn't exists."); } else throw new IllegalArgumentException( "GenerateCsvConfigTemplate: Command requires the 'csvHeaderFile' parameter."); } else throw new IllegalArgumentException("GenerateCsvConfigTemplate: Command requires the 'configFile' parameter."); } if(command.getCommand().equalsIgnoreCase("LoadCsv")) { String configFile = (String)command.getParameters().get("configFile"); String csvDataFile = (String)command.getParameters().get("csvDataFile"); if(configFile != null && configFile.length() > 0) { File conf = new File(configFile); if(conf.exists()) { if(csvDataFile != null && csvDataFile.length() > 0) { File csvf = new File(csvDataFile); if(csvf.exists()) { if(projectId != null) { connector = CsvConnector.createConnector(projectId, configFile, csvDataFile); } else throw new IllegalArgumentException( "LoadCsv: No active project found. Use command 'CreateProject'" + " or 'OpenProject' first."); } else throw new IllegalArgumentException( "LoadCsv: File '" + csvDataFile + "' doesn't exists."); } else throw new IllegalArgumentException( "LoadCsv: Command requires the 'csvHeaderFile' parameter."); } else throw new IllegalArgumentException( "LoadCsv: File '" + configFile + "' doesn't exists."); } else throw new IllegalArgumentException( "LoadCsv: Command requires the 'configFile' parameter."); } if(command.getCommand().equalsIgnoreCase("GenerateGoogleAnalyticsConfigTemplate")) { String configFile = (String)command.getParameters().get("configFile"); String name = (String)command.getParameters().get("name"); String dimensions = (String)command.getParameters().get("dimensions"); String metrics = (String)command.getParameters().get("metrics"); if(configFile != null && configFile.length() > 0) { File cf = new File(configFile); if(dimensions != null && dimensions.length() > 0) { if(metrics != null && metrics.length() > 0) { if(name != null && name.length() > 0) { GaQuery gq = null; try { gq = new GaQuery(); } catch (MalformedURLException e) { throw new IllegalArgumentException(e.getMessage()); } gq.setDimensions(dimensions); gq.setMetrics(metrics); GaConnector.saveConfigTemplate(name, configFile, gq); } else throw new IllegalArgumentException( "GenerateGoogleAnalyticsConfigTemplate: Please specify a name using the name parameter."); } else throw new IllegalArgumentException( "GenerateGoogleAnalyticsConfigTemplate: Please specify a metrics using the metrics parameter."); } else throw new IllegalArgumentException( "GenerateGoogleAnalyticsConfigTemplate: Please specify a dimensions using the dimensions parameter."); } else throw new IllegalArgumentException( "GenerateGoogleAnalyticsConfigTemplate: Please specify a config file using the configFile parameter."); } if(command.getCommand().equalsIgnoreCase("LoadGoogleAnalytics")) { String configFile = (String)command.getParameters().get("configFile"); String usr = (String)command.getParameters().get("username"); String psw = (String)command.getParameters().get("password"); String id = (String)command.getParameters().get("profileId"); String dimensions = (String)command.getParameters().get("dimensions"); String metrics = (String)command.getParameters().get("metrics"); String startDate = (String)command.getParameters().get("startDate"); String endDate = (String)command.getParameters().get("endDate"); String filters = (String)command.getParameters().get("filters"); if(configFile != null && configFile.length() > 0) { File conf = new File(configFile); if(conf.exists()) { if(projectId != null) { if(usr != null && usr.length() > 0) { if(psw != null && psw.length() > 0) { if(id != null && id.length() > 0) { GaQuery gq = null; try { gq = new GaQuery(); } catch (MalformedURLException e) { throw new IllegalArgumentException(e.getMessage()); } if(dimensions != null && dimensions.length() > 0) gq.setDimensions(dimensions.replace("|",",")); else throw new IllegalArgumentException( "LoadGoogleAnalytics: Please specify a dimensions using the dimensions parameter."); if(metrics != null && metrics.length() > 0) gq.setMetrics(metrics.replace("|",",")); else throw new IllegalArgumentException( "LoadGoogleAnalytics: Please specify a metrics using the metrics parameter."); if(startDate != null && startDate.length() > 0) gq.setStartDate(startDate); if(endDate != null && endDate.length() > 0) gq.setEndDate(endDate); if(filters != null && filters.length() > 0) gq.setFilters(filters); connector = GaConnector.createConnector(projectId, configFile, usr, psw, id, gq); } else throw new IllegalArgumentException( "LoadGoogleAnalytics: Please specify a Google Profile ID using the profileId parameter."); } else throw new IllegalArgumentException( "LoadGoogleAnalytics: Please specify a Google username using the username parameter."); } else throw new IllegalArgumentException( "LoadGoogleAnalytics: Please specify a Google password using the password parameter."); } else throw new IllegalArgumentException( "LoadGoogleAnalytics: No active project found. Use command 'CreateProject'" + " or 'OpenProject' first."); } else throw new IllegalArgumentException( "LoadGoogleAnalytics: File '" + configFile + "' doesn't exists."); } else throw new IllegalArgumentException( "LoadGoogleAnalytics: Command requires the 'configFile' parameter."); } if(command.getCommand().equalsIgnoreCase("GenerateMaql")) { String maqlFile = (String)command.getParameters().get("maqlFile"); if(maqlFile != null && maqlFile.length() > 0) { if(connector != null) { String maql = connector.generateMaql(); FileUtil.writeStringToFile(maql, maqlFile); } else throw new IllegalArgumentException("GenerateMaql: No data source loaded. Use a 'LoadXXX' to load a data source."); } else throw new IllegalArgumentException("GenerateMaql: Command requires the 'maqlFile' parameter."); } if(command.getCommand().equalsIgnoreCase("ExecuteMaql")) { String maqlFile = (String)command.getParameters().get("maqlFile"); if(maqlFile != null && maqlFile.length() > 0) { File mf = new File(maqlFile); if(mf.exists()) { if(projectId != null) { String maql = FileUtil.readStringFromFile(maqlFile); getRestApi().executeMAQL(projectId, maql); } else throw new IllegalArgumentException( "ExecuteMaql: No active project found. Use command 'CreateProject'" + " or 'OpenProject' first."); } else throw new IllegalArgumentException( "ExecuteMaql: File '" + maqlFile + "' doesn't exists."); } else throw new IllegalArgumentException("ExecuteMaql: Command requires the 'maqlFile' parameter."); } if(command.getCommand().equalsIgnoreCase("ListSnapshots")) { if(connector != null) { System.out.println(connector.listSnapshots()); } else throw new IllegalArgumentException("ListSnapshots: No data source loaded. Use a 'LoadXXX' to load a data source."); } if(command.getCommand().equalsIgnoreCase("DropSnapshots")) { if(connector != null) { connector.dropSnapshots(); } else throw new IllegalArgumentException("DropSnapshots: No data source loaded. Use a 'LoadXXX' to load a data source."); } if(command.getCommand().equalsIgnoreCase("TransferData")) { if(connector != null) { if(!connector.isInitialized()) connector.initialize(); // retrieve the DLI DLI dli = getRestApi().getDLIById("dataset." + connector.getName().toLowerCase(), projectId); List<DLIPart> parts= getRestApi().getDLIParts("dataset." + connector.getName().toLowerCase(), projectId); // target directories and ZIP names String incremental = (String)command.getParameters().get("incremental"); if(incremental != null && incremental.length() > 0 && incremental.equalsIgnoreCase("true")) { for(DLIPart part : parts) { if(part.getFileName().startsWith("f_")) { part.setLoadMode(DLIPart.LM_INCREMENTAL); } } } File tmpDir = FileUtil.createTempDir(); File tmpZipDir = FileUtil.createTempDir(); String archiveName = tmpDir.getName(); String archivePath = tmpZipDir.getAbsolutePath() + System.getProperty("file.separator") + archiveName + ".zip"; // loads the CSV data to the embedded Derby SQL connector.extract(); // normalize the data in the Derby connector.transform(); // load data from the Derby to the local GoodData data integration package connector.deploy(dli, parts, tmpDir.getAbsolutePath(), archivePath); // transfer the data package to the GoodData server getFtpApi().transferDir(archivePath); // kick the GooDData server to load the data package to the project getRestApi().startLoading(projectId, archiveName); } else throw new IllegalArgumentException("TransferData: No data source loaded. Use a 'LoadXXX' to load a data source."); } if(command.getCommand().equalsIgnoreCase("TransferSnapshots")) { String firstSnapshot = (String)command.getParameters().get("firstSnapshot"); String lastSnapshot = (String)command.getParameters().get("lastSnapshot"); if(firstSnapshot != null && firstSnapshot.length() > 0) { if(lastSnapshot != null && lastSnapshot.length() > 0) { int fs = 0,ls = 0; try { fs = Integer.parseInt(firstSnapshot); } catch (NumberFormatException e) { throw new IllegalArgumentException("TransferSnapshots: The 'firstSnapshot' (" + firstSnapshot + ") parameter is not a number."); } try { ls = Integer.parseInt(lastSnapshot); } catch (NumberFormatException e) { throw new IllegalArgumentException("TransferSnapshots: The 'lastSnapshot' (" + lastSnapshot + ") parameter is not a number."); } int cnt = ls - fs; if(cnt >= 0) { int[] snapshots = new int[cnt]; for(int i = 0; i < cnt; i++) { snapshots[i] = fs + i; } if(connector != null) { if(!connector.isInitialized()) connector.initialize(); // retrieve the DLI DLI dli = getRestApi().getDLIById("dataset." + connector.getName().toLowerCase(), projectId); List<DLIPart> parts= getRestApi().getDLIParts("dataset." + connector.getName().toLowerCase(), projectId); String incremental = (String)command.getParameters().get("incremental"); if(incremental != null && incremental.length() > 0 && incremental.equalsIgnoreCase("true")) { for(DLIPart part : parts) { if(part.getFileName().startsWith("f_")) { part.setLoadMode(DLIPart.LM_INCREMENTAL); } } } // target directories and ZIP names File tmpDir = FileUtil.createTempDir(); File tmpZipDir = FileUtil.createTempDir(); String archiveName = tmpDir.getName(); String archivePath = tmpZipDir.getAbsolutePath() + System.getProperty("file.separator") + archiveName + ".zip"; // loads the CSV data to the embedded Derby SQL connector.extract(); // normalize the data in the Derby connector.transform(); // load data from the Derby to the local GoodData data integration package connector.deploySnapshot(dli, parts, tmpDir.getAbsolutePath(), archivePath, snapshots); // transfer the data package to the GoodData server getFtpApi().transferDir(archivePath); // kick the GooDData server to load the data package to the project getRestApi().startLoading(projectId, archiveName); } else throw new IllegalArgumentException("TransferSnapshots: No data source loaded." + "Use a 'LoadXXX' to load a data source."); } else throw new IllegalArgumentException("TransferSnapshots: The 'lastSnapshot' (" + lastSnapshot + ") parameter must be higher than the 'firstSnapshot' (" + firstSnapshot + ") parameter."); } else throw new IllegalArgumentException("TransferSnapshots: Command requires the 'lastSnapshot' parameter."); } else throw new IllegalArgumentException("TransferSnapshots: Command requires the 'firstSnapshot' parameter."); } if(command.getCommand().equalsIgnoreCase("TransferLastSnapshot")) { if(connector != null) { if(!connector.isInitialized()) connector.initialize(); // retrieve the DLI DLI dli = getRestApi().getDLIById("dataset." + connector.getName().toLowerCase(), projectId); List<DLIPart> parts= getRestApi().getDLIParts("dataset." + connector.getName().toLowerCase(), projectId); String incremental = (String)command.getParameters().get("incremental"); if(incremental != null && incremental.length() > 0 && incremental.equalsIgnoreCase("true")) { for(DLIPart part : parts) { if(part.getFileName().startsWith("f_")) { part.setLoadMode(DLIPart.LM_INCREMENTAL); } } } // target directories and ZIP names File tmpDir = FileUtil.createTempDir(); File tmpZipDir = FileUtil.createTempDir(); String archiveName = tmpDir.getName(); String archivePath = tmpZipDir.getAbsolutePath() + System.getProperty("file.separator") + archiveName + ".zip"; // loads the CSV data to the embedded Derby SQL connector.extract(); // normalize the data in the Derby connector.transform(); // load data from the Derby to the local GoodData data integration package connector.deploySnapshot(dli, parts, tmpDir.getAbsolutePath(), archivePath, new int[] {connector.getLastSnapshotId()}); // transfer the data package to the GoodData server getFtpApi().transferDir(archivePath); // kick the GooDData server to load the data package to the project getRestApi().startLoading(projectId, archiveName); } else throw new IllegalArgumentException("TransferLastSnapshot: No data source loaded." + "Use a 'LoadXXX' to load a data source."); } } }
package com.google.code.jscep; import java.io.IOException; import java.math.BigInteger; import java.net.Proxy; import java.net.URL; import java.security.GeneralSecurityException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.cert.CRL; import java.security.cert.CertStore; import java.security.cert.CertStoreException; import java.security.cert.Certificate; import java.security.cert.CertificateEncodingException; import java.security.cert.X509CRL; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.logging.Logger; import javax.security.auth.x500.X500Principal; import org.bouncycastle.cms.CMSException; import com.google.code.jscep.operations.GetCRL; import com.google.code.jscep.operations.GetCert; import com.google.code.jscep.operations.PkiOperation; import com.google.code.jscep.request.GetCACaps; import com.google.code.jscep.request.GetCACert; import com.google.code.jscep.request.GetNextCACert; import com.google.code.jscep.response.Capability; import com.google.code.jscep.transaction.Transaction; import com.google.code.jscep.transaction.TransactionFactory; import com.google.code.jscep.transport.Transport; import com.google.code.jscep.util.LoggingUtil; /** * SCEP Client */ public class Client { private static Logger LOGGER = LoggingUtil.getLogger(Client.class); private URL url; // Required private byte[] caDigest; // Required private String digestAlgorithm; // Optional private Proxy proxy; // Optional private String caIdentifier; // Optional private KeyPair keyPair; // Optional private X509Certificate identity; // Optional public Client(ClientConfiguration config) throws IllegalStateException, IOException, ScepException, CMSException, GeneralSecurityException { url = config.getUrl(); proxy = config.getProxy(); caDigest = config.getCaDigest(); caIdentifier = config.getCaIdentifier(); keyPair = config.getKeyPair(); identity = config.getIdentity(); digestAlgorithm = config.getDigestAlgorithm(); X500Principal subject = config.getSubject(); X509Certificate ca = config.getCaCertificate(); // See http://tools.ietf.org/html/draft-nourse-scep-19#section-5.1 if (isValid(url) == false) { throw new IllegalStateException("Invalid URL"); } // See http://tools.ietf.org/html/draft-nourse-scep-19#section-2.1.2.1 if (ca == null && caDigest == null) { throw new IllegalStateException("Need CA OR CA Digest."); } if (ca != null && caDigest != null) { throw new IllegalStateException("Need CA OR CA Digest."); } // Must have only one way of obtaining an identity. if (identity == null && subject == null) { throw new IllegalStateException("Need Identity OR Subject"); } if (identity != null && subject != null) { throw new IllegalStateException("Need Identity OR Subject"); } // Set Defaults if (digestAlgorithm == null) { digestAlgorithm = "MD5"; } if (proxy == null) { proxy = Proxy.NO_PROXY; } if (keyPair == null) { keyPair = createKeyPair(); } if (isValid(keyPair) == false) { throw new IllegalStateException("Invalid KeyPair"); } if (identity == null) { identity = createCertificate(subject); } // If we're replacing a certificate, we must have the same key pair. if (identity.getPublicKey().equals(keyPair.getPublic()) == false) { throw new IllegalStateException("Public Key Mismatch"); } List<String> algorithms = new LinkedList<String>(); algorithms.add("MD5"); algorithms.add("SHA-1"); algorithms.add("SHA-256"); algorithms.add("SHA-512"); if (algorithms.contains(digestAlgorithm) == false) { throw new IllegalStateException(digestAlgorithm + " is not a valid digest algorithm"); } if (ca != null) { MessageDigest digest = MessageDigest.getInstance(digestAlgorithm); caDigest = digest.digest(ca.getTBSCertificate()); } else { ca = retrieveCA(); } // Check renewal if (subject == null) { if (isSelfSigned(identity) == false) { if (identity.getIssuerX500Principal().equals(ca.getSubjectX500Principal())) { LOGGER.fine("Certificate is signed by CA, so this is a renewal."); } else { LOGGER.fine("Certificate is signed by another CA, bit this is still a renewal."); } try { LOGGER.fine("Checking if the CA supports certificate renewal..."); if (getCapabilities().contains(Capability.RENEWAL) == false) { throw new IllegalStateException("Your CA does not support renewal"); } } catch (IOException e) { throw new IllegalStateException("Your CA does not support renewal"); } } else { LOGGER.fine("Certificate is self-signed. This is not a renewal."); } } } private boolean isSelfSigned(X509Certificate cert) { return cert.getIssuerX500Principal().equals(cert.getSubjectX500Principal()); } private boolean isValid(KeyPair keyPair) { PrivateKey pri = keyPair.getPrivate(); PublicKey pub = keyPair.getPublic(); return pri.getAlgorithm().equals("RSA") && pub.getAlgorithm().equals("RSA"); } private boolean isValid(URL url) { if (url == null) { return false; } if (url.getProtocol().matches("^https?$") == false) { return false; } if (url.getPath().endsWith("pkiclient.exe") == false) { return false; } if (url.getRef() != null) { return false; } if (url.getQuery() != null) { return false; } return true; } private KeyPair createKeyPair() { LOGGER.fine("Creating RSA Key Pair"); try { return KeyPairGenerator.getInstance("RSA").genKeyPair(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } private X509Certificate createCertificate(X500Principal subject) { LOGGER.fine("Creating Self-Signed Certificate for " + subject); try { return X509CertificateFactory.createCertificate(subject, keyPair); } catch (Exception e) { throw new RuntimeException(e); } } private String getBestMessageDigest() throws IOException { Set<Capability> caps = getCapabilities(); if (caps.contains(Capability.SHA_512)) { return "SHA-512"; } else if (caps.contains(Capability.SHA_256)) { return "SHA-256"; } else if (caps.contains(Capability.SHA_1)) { return "SHA-1"; } else { return "MD5"; } } private Transaction createTransaction() throws IOException { return TransactionFactory.createTransaction(createTransport(), retrieveSigningCertificate(), identity, keyPair, getBestMessageDigest()); } private Transport createTransport() throws IOException { LOGGER.entering(getClass().getName(), "createTransport"); final Transport t; if (getCapabilities().contains(Capability.POST_PKI_OPERATION)) { t = Transport.createTransport(Transport.Method.POST, url, proxy); } else { t = Transport.createTransport(Transport.Method.GET, url, proxy); } LOGGER.exiting(getClass().getName(), "createTransport", t); return t; } /** * Retrieve the generated {@link KeyPair}. * * @return the key pair. */ public KeyPair getKeyPair() { return keyPair; } private Set<Capability> getCapabilities() throws IOException { GetCACaps req = new GetCACaps(caIdentifier); Transport trans = Transport.createTransport(Transport.Method.GET, url, proxy); return trans.sendMessage(req); } private List<X509Certificate> getCaCertificate() throws IOException { GetCACert req = new GetCACert(caIdentifier); Transport trans = Transport.createTransport(Transport.Method.GET, url, proxy); return trans.sendMessage(req); } public List<X509Certificate> getNextCA() throws IOException { X509Certificate ca = retrieveCA(); Transport trans = Transport.createTransport(Transport.Method.GET, url, proxy); GetNextCACert req = new GetNextCACert(ca, caIdentifier); return trans.sendMessage(req); } private X509Certificate retrieveCA() throws IOException { final List<X509Certificate> certs = getCaCertificate(); // Validate MessageDigest md; try { md = MessageDigest.getInstance(digestAlgorithm); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } byte[] certBytes; try { certBytes = certs.get(0).getEncoded(); } catch (CertificateEncodingException e) { throw new IOException(e); } if (Arrays.equals(caDigest, md.digest(certBytes)) == false) { throw new IOException("CA Fingerprint Error"); } return certs.get(0); } private X509Certificate retrieveSigningCertificate() throws IOException { List<X509Certificate> certs = getCaCertificate(); // Validate MessageDigest md; try { md = MessageDigest.getInstance(digestAlgorithm); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } byte[] certBytes; try { certBytes = certs.get(0).getEncoded(); } catch (CertificateEncodingException e) { throw new IOException(e); } if (Arrays.equals(caDigest, md.digest(certBytes)) == false) { throw new IOException("CA Fingerprint Error"); } if (certs.size() > 1) { return certs.get(1); } else { return certs.get(0); } } /** * Retrieves the certificate revocation list for the current CA. * * @return the certificate revocation list. * @throws IOException if any I/O error occurs. * @throws ScepException if any SCEP error occurs. * @throws GeneralSecurityException if any security error occurs. * @throws CMSException */ public List<X509CRL> getCrl() throws IOException { X509Certificate ca = retrieveCA(); if (supportsDistributionPoints()) { return null; } else { // PKI Operation PkiOperation req = new GetCRL(ca.getIssuerX500Principal(), ca.getSerialNumber()); CertStore store; try { store = createTransaction().performOperation(req); } catch (RequestPendingException e) { throw new RuntimeException(e); } catch (EnrollmentFailureException e) { throw new RuntimeException(e); } try { return getCRLs(store.getCRLs(null)); } catch (CertStoreException e) { throw new IOException(e); } } } private boolean supportsDistributionPoints() { // TODO Implement CDP return false; } /** * Enrolls an identity into a PKI domain. * * @param password the enrollment password. * @return the enrolled certificate. * @throws IOException if any I/O error occurs. */ public EnrollmentResult enroll(char[] password) throws IOException { final X509Certificate signer = retrieveSigningCertificate(); return new InitialEnrollmentTask(createTransport(), signer, keyPair, identity, password, getBestMessageDigest()).call(); } /** * Retrieves the certificate corresponding to the given serial number. * * @param serial the serial number of the certificate. * @return the certificate. * @throws IOException if any I/O error occurs. * @throws ScepException * @throws GeneralSecurityException * @throws CMSException */ public X509Certificate getCert(BigInteger serial) throws IOException { final X509Certificate ca = retrieveCA(); // PKI Operation PkiOperation req = new GetCert(ca.getIssuerX500Principal(), serial); CertStore store; try { store = createTransaction().performOperation(req); } catch (RequestPendingException e) { throw new RuntimeException(e); } catch (EnrollmentFailureException e) { throw new RuntimeException(e); } try { return getCertificates(store.getCertificates(null)).get(0); } catch (CertStoreException e) { throw new RuntimeException(e); } } private List<X509Certificate> getCertificates(Collection<? extends Certificate> certs) { List<X509Certificate> x509 = new ArrayList<X509Certificate>(); for (Certificate cert : certs) { x509.add((X509Certificate) cert); } return x509; } private List<X509CRL> getCRLs(Collection<? extends CRL> crls) { List<X509CRL> x509 = new ArrayList<X509CRL>(); for (CRL crl : crls) { x509.add((X509CRL) crl); } return x509; } }
package org.commcare; import android.Manifest; import android.annotation.SuppressLint; import android.app.Activity; import android.app.Application; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.IBinder; import android.os.Looper; import android.os.Message; import android.preference.PreferenceManager; import android.provider.Settings.Secure; import android.support.v4.app.NotificationCompat; import android.support.v4.content.ContextCompat; import android.support.v4.util.Pair; import android.telephony.TelephonyManager; import android.text.format.DateUtils; import android.util.Log; import android.widget.Toast; import com.google.android.gms.analytics.GoogleAnalytics; import com.google.android.gms.analytics.Tracker; import net.sqlcipher.database.SQLiteDatabase; import net.sqlcipher.database.SQLiteException; import org.acra.annotation.ReportsCrashes; import org.commcare.activities.DispatchActivity; import org.commcare.activities.LoginActivity; import org.commcare.activities.MessageActivity; import org.commcare.activities.UnrecoverableErrorActivity; import org.commcare.android.logging.ForceCloseLogEntry; import org.commcare.android.logging.ForceCloseLogger; import org.commcare.core.network.ModernHttpRequester; import org.commcare.dalvik.BuildConfig; import org.commcare.dalvik.R; import org.commcare.engine.references.ArchiveFileRoot; import org.commcare.engine.references.AssetFileRoot; import org.commcare.engine.references.JavaHttpRoot; import org.commcare.engine.resource.ResourceInstallUtils; import org.commcare.android.javarosa.AndroidLogEntry; import org.commcare.logging.AndroidLogger; import org.commcare.logging.PreInitLogger; import org.commcare.logging.XPathErrorEntry; import org.commcare.logging.XPathErrorLogger; import org.commcare.logging.analytics.GoogleAnalyticsUtils; import org.commcare.logging.analytics.TimedStatsTracker; import org.commcare.models.AndroidClassHasher; import org.commcare.models.AndroidSessionWrapper; import org.commcare.models.database.AndroidDbHelper; import org.commcare.models.database.HybridFileBackedSqlHelpers; import org.commcare.models.database.HybridFileBackedSqlStorage; import org.commcare.models.database.MigrationException; import org.commcare.models.database.AndroidPrototypeFactorySetup; import org.commcare.models.database.SqlStorage; import org.commcare.models.database.app.DatabaseAppOpenHelper; import org.commcare.android.database.app.models.UserKeyRecord; import org.commcare.models.database.global.DatabaseGlobalOpenHelper; import org.commcare.android.database.global.models.ApplicationRecord; import org.commcare.models.database.user.DatabaseUserOpenHelper; import org.commcare.models.framework.Table; import org.commcare.models.legacy.LegacyInstallUtils; import org.commcare.network.AndroidModernHttpRequester; import org.commcare.network.DataPullRequester; import org.commcare.network.DataPullResponseFactory; import org.commcare.network.HttpUtils; import org.commcare.preferences.CommCarePreferences; import org.commcare.preferences.CommCareServerPreferences; import org.commcare.preferences.DevSessionRestorer; import org.commcare.provider.ProviderUtils; import org.commcare.services.CommCareSessionService; import org.commcare.session.CommCareSession; import org.commcare.suite.model.Profile; import org.commcare.tasks.DataSubmissionListener; import org.commcare.tasks.LogSubmissionTask; import org.commcare.tasks.PurgeStaleArchivedFormsTask; import org.commcare.tasks.UpdateTask; import org.commcare.tasks.templates.ManagedAsyncTask; import org.commcare.utils.ACRAUtil; import org.commcare.utils.AndroidCacheDirSetup; import org.commcare.utils.AndroidCommCarePlatform; import org.commcare.utils.CommCareExceptionHandler; import org.commcare.utils.FileUtil; import org.commcare.utils.GlobalConstants; import org.commcare.utils.MultipleAppsUtil; import org.commcare.utils.ODKPropertyManager; import org.commcare.utils.SessionActivityRegistration; import org.commcare.utils.SessionStateUninitException; import org.commcare.utils.SessionUnavailableException; import org.commcare.views.notifications.NotificationClearReceiver; import org.commcare.views.notifications.NotificationMessage; import org.javarosa.core.model.User; import org.javarosa.core.model.instance.FormInstance; import org.javarosa.core.reference.ReferenceManager; import org.javarosa.core.reference.RootTranslator; import org.javarosa.core.services.Logger; import org.javarosa.core.services.PropertyManager; import org.javarosa.core.services.locale.Localization; import org.javarosa.core.services.storage.EntityFilter; import org.javarosa.core.services.storage.Persistable; import org.javarosa.core.util.PropertyUtils; import org.javarosa.core.util.externalizable.PrototypeFactory; import java.io.File; import java.lang.ref.WeakReference; import java.net.URL; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import java.util.Vector; import javax.crypto.SecretKey; /** * @author ctsims */ @ReportsCrashes( formUri = "https://your/cloudant/report", formUriBasicAuthLogin = "your_username", formUriBasicAuthPassword = "your_password", reportType = org.acra.sender.HttpSender.Type.JSON, httpMethod = org.acra.sender.HttpSender.Method.PUT) public class CommCareApplication extends Application { private static final String TAG = CommCareApplication.class.getSimpleName(); // Tracking ids for Google Analytics private static final String LIVE_TRACKING_ID = BuildConfig.ANALYTICS_TRACKING_ID_LIVE; private static final String DEV_TRACKING_ID = BuildConfig.ANALYTICS_TRACKING_ID_DEV; private static final int STATE_UNINSTALLED = 0; private static final int STATE_READY = 2; public static final int STATE_CORRUPTED = 4; public static final int STATE_MIGRATION_FAILED = 16; public static final int STATE_MIGRATION_QUESTIONABLE = 32; private static final String ACTION_PURGE_NOTIFICATIONS = "CommCareApplication_purge"; private int dbState; private static CommCareApplication app; private CommCareApp currentApp; // stores current state of application: the session, form private AndroidSessionWrapper sessionWrapper; private final Object globalDbHandleLock = new Object(); private SQLiteDatabase globalDatabase; private ArchiveFileRoot mArchiveFileRoot; // A bound service is created out of the CommCareSessionService to ensure it stays in memory. private CommCareSessionService mBoundService; private ServiceConnection mConnection; private final Object serviceLock = new Object(); private boolean sessionServiceIsBound = false; // Important so we don't use the service before the db is initialized. private boolean sessionServiceIsBinding = false; // Milliseconds to wait for bind private static final int MAX_BIND_TIMEOUT = 5000; private int mCurrentServiceBindTimeout = MAX_BIND_TIMEOUT; /** * Handler to receive notifications and show them the user using toast. */ private final PopupHandler toaster = new PopupHandler(this); private GoogleAnalytics analyticsInstance; private Tracker analyticsTracker; private String messageForUserOnDispatch; private String titleForUserMessage; // Indicates that a build refresh action has been triggered, but not yet completed private boolean latestBuildRefreshPending; private boolean invalidateCacheOnRestore; @Override public void onCreate() { super.onCreate(); // Sets the static strategy for the deserialization code to be based on an optimized // md5 hasher. Major speed improvements. AndroidClassHasher.registerAndroidClassHashStrategy(); CommCareApplication.app = this; //TODO: Make this robust PreInitLogger pil = new PreInitLogger(); Logger.registerLogger(pil); // Workaround because android is written by 7 year-olds (re-uses http connection pool // improperly, so the second https request in a short time period will flop) System.setProperty("http.keepAlive", "false"); Thread.setDefaultUncaughtExceptionHandler(new CommCareExceptionHandler(Thread.getDefaultUncaughtExceptionHandler(), this)); PropertyManager.setPropertyManager(new ODKPropertyManager()); SQLiteDatabase.loadLibs(this); setRoots(); prepareTemporaryStorage(); // Init global storage (Just application records, logs, etc) dbState = initGlobalDb(); // This is where we go through and check for updates between major transitions. // Soon we should start doing this differently, and actually go to an activity // first which tells the user what's going on. // The rule about this transition is that if the user had logs pending, we still want // them in order, so we aren't going to dump our logs from the Pre-init logger until // after this transition occurs. try { LegacyInstallUtils.checkForLegacyInstall(this, this.getGlobalStorage(ApplicationRecord.class)); } finally { // No matter what happens, set up our new logger, we want those logs! setupLoggerStorage(false); pil.dumpToNewLogger(); } intializeDefaultLocalizerData(); if (dbState != STATE_MIGRATION_FAILED && dbState != STATE_MIGRATION_QUESTIONABLE) { checkForIncompletelyUninstalledApps(); initializeAnAppOnStartup(); } ACRAUtil.initACRA(this); if (!GoogleAnalyticsUtils.versionIncompatible()) { analyticsInstance = GoogleAnalytics.getInstance(this); GoogleAnalyticsUtils.reportAndroidApiLevelAtStartup(); } } public void triggerHandledAppExit(Context c, String message, String title) { triggerHandledAppExit(c, message, title, true); } public void triggerHandledAppExit(Context c, String message, String title, boolean useExtraMessage) { Intent i = new Intent(c, UnrecoverableErrorActivity.class); i.putExtra(UnrecoverableErrorActivity.EXTRA_ERROR_TITLE, title); i.putExtra(UnrecoverableErrorActivity.EXTRA_ERROR_MESSAGE, message); i.putExtra(UnrecoverableErrorActivity.EXTRA_USE_MESSAGE, useExtraMessage); // start a new stack and forget where we were (so we don't restart the app from there) i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET | Intent.FLAG_ACTIVITY_CLEAR_TOP); c.startActivity(i); } public static void restartCommCare(Activity originActivity, boolean systemExit) { restartCommCare(originActivity, DispatchActivity.class, systemExit); } public static void restartCommCare(Activity originActivity, Class c, boolean systemExit) { Intent intent = new Intent(originActivity, c); // Make sure that the new stack starts with the given class, and clear everything between. intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); originActivity.moveTaskToBack(true); originActivity.startActivity(intent); originActivity.finish(); if (systemExit) { System.exit(0); } } public void startUserSession(byte[] symmetricKey, UserKeyRecord record, boolean restoreSession) { synchronized (serviceLock) { // if we already have a connection established to // CommCareSessionService, close it and open a new one SessionActivityRegistration.unregisterSessionExpiration(); if (this.sessionServiceIsBound) { releaseUserResourcesAndServices(); } bindUserSessionService(symmetricKey, record, restoreSession); } } /** * Closes down the user service, resources, and background tasks. Used for * manual user log-outs. */ public void closeUserSession() { synchronized (serviceLock) { // Cancel any running tasks before closing down the user database. ManagedAsyncTask.cancelTasks(); releaseUserResourcesAndServices(); // Switch loggers back over to using global storage, now that we don't have a session setupLoggerStorage(false); } } /** * Closes down the user service, resources, and background tasks, * broadcasting an intent to redirect the user to the login screen. Used * for session-expiration related user logouts. */ public void expireUserSession() { synchronized (serviceLock) { closeUserSession(); SessionActivityRegistration.registerSessionExpiration(); sendBroadcast(new Intent(SessionActivityRegistration.USER_SESSION_EXPIRED)); } } public void releaseUserResourcesAndServices() { String userBeingLoggedOut = CommCareApplication._().getCurrentUserId(); try { CommCareApplication._().getSession().closeServiceResources(); } catch (SessionUnavailableException e) { Log.w(TAG, "User's session services have unexpectedly already " + "been closed down. Proceeding to close the session."); } unbindUserSessionService(); TimedStatsTracker.registerEndSession(userBeingLoggedOut); } public SecretKey createNewSymmetricKey() { return getSession().createNewSymmetricKey(); } synchronized public Tracker getDefaultTracker() { if (analyticsTracker == null) { if (BuildConfig.DEBUG) { analyticsTracker = analyticsInstance.newTracker(DEV_TRACKING_ID); } else { analyticsTracker = analyticsInstance.newTracker(LIVE_TRACKING_ID); } analyticsTracker.enableAutoActivityTracking(true); } String userId = getCurrentUserId(); if (!"".equals(userId)) { analyticsTracker.set("&uid", userId); } else { analyticsTracker.set("&uid", null); } return analyticsTracker; } public int[] getCommCareVersion() { return this.getResources().getIntArray(R.array.commcare_version); } public AndroidCommCarePlatform getCommCarePlatform() { if (this.currentApp == null) { throw new RuntimeException("No App installed!!!"); } else { return this.currentApp.getCommCarePlatform(); } } public CommCareApp getCurrentApp() { return this.currentApp; } /** * Get the current CommCare session that's being executed */ public CommCareSession getCurrentSession() { return getCurrentSessionWrapper().getSession(); } public AndroidSessionWrapper getCurrentSessionWrapper() { if (sessionWrapper == null) { throw new SessionStateUninitException("CommCare user session isn't available"); } return sessionWrapper; } public int getDatabaseState() { return dbState; } public void initializeGlobalResources(CommCareApp app) { if (dbState != STATE_UNINSTALLED) { initializeAppResources(app); } } public String getPhoneId() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_DENIED) { return "000000000000000"; } TelephonyManager manager = (TelephonyManager)this.getSystemService(TELEPHONY_SERVICE); String imei = manager.getDeviceId(); if (imei == null) { imei = Secure.getString(getContentResolver(), Secure.ANDROID_ID); } return imei; } public void intializeDefaultLocalizerData() { Localization.init(true); Localization.registerLanguageReference("default", "jr://asset/locales/android_translatable_strings.txt"); Localization.registerLanguageReference("default", "jr://asset/locales/android_startup_strings.txt"); Localization.setDefaultLocale("default"); // For now. Possibly handle this better in the future Localization.setLocale("default"); } private void setRoots() { JavaHttpRoot http = new JavaHttpRoot(); AssetFileRoot afr = new AssetFileRoot(this); ArchiveFileRoot arfr = new ArchiveFileRoot(); mArchiveFileRoot = arfr; ReferenceManager._().addReferenceFactory(http); ReferenceManager._().addReferenceFactory(afr); ReferenceManager._().addReferenceFactory(arfr); ReferenceManager._().addRootTranslator(new RootTranslator("jr://media/", GlobalConstants.MEDIA_REF)); } /** * Check if any existing apps were left in a partially deleted state, and finish * uninstalling them if so. */ private void checkForIncompletelyUninstalledApps() { for (ApplicationRecord record : getGlobalStorage(ApplicationRecord.class)) { if (record.getStatus() == ApplicationRecord.STATUS_DELETE_REQUESTED) { try { uninstall(record); } catch (RuntimeException e) { Logger.log(AndroidLogger.TYPE_ERROR_STORAGE, "Unable to uninstall an app " + "during startup that was previously left partially-deleted"); } } } } /** * Performs the appropriate initialization of an application when this CommCareApplication is * first launched */ private void initializeAnAppOnStartup() { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); String lastAppId = prefs.getString(LoginActivity.KEY_LAST_APP, ""); if (!"".equals(lastAppId)) { ApplicationRecord lastApp = MultipleAppsUtil.getAppById(lastAppId); if (lastApp == null || !lastApp.isUsable()) { initFirstUsableAppRecord(); } else { initializeAppResources(new CommCareApp(lastApp)); } } else { initFirstUsableAppRecord(); } } /** * Initializes the first "usable" application from the list of globally installed app records, * if there is one */ public void initFirstUsableAppRecord() { for (ApplicationRecord record : MultipleAppsUtil.getUsableAppRecords()) { initializeAppResources(new CommCareApp(record)); break; } } /** * Initialize all of the given app's resources, and set the state of its resources accordingly * * @param app the CC app to initialize */ public void initializeAppResources(CommCareApp app) { int resourceState; try { currentApp = app; if (currentApp.initializeApplication()) { resourceState = STATE_READY; this.sessionWrapper = new AndroidSessionWrapper(this.getCommCarePlatform()); } else { resourceState = STATE_CORRUPTED; } } catch (Exception e) { Log.i("FAILURE", "Problem with loading"); Log.i("FAILURE", "E: " + e.getMessage()); e.printStackTrace(); ForceCloseLogger.reportExceptionInBg(e); resourceState = STATE_CORRUPTED; } app.setAppResourceState(resourceState); } /** * @return all ApplicationRecords in storage, regardless of their status, in alphabetical order */ public ArrayList<ApplicationRecord> getInstalledAppRecords() { ArrayList<ApplicationRecord> records = new ArrayList<>(); for (ApplicationRecord r : getGlobalStorage(ApplicationRecord.class)) { records.add(r); } Collections.sort(records, new Comparator<ApplicationRecord>() { @Override public int compare(ApplicationRecord lhs, ApplicationRecord rhs) { return lhs.getDisplayName().compareTo(rhs.getDisplayName()); } }); return records; } /** * @param uniqueId - the uniqueId of the ApplicationRecord being sought * @return the ApplicationRecord corresponding to the given id, if it exists. Otherwise, * return null */ public ApplicationRecord getAppById(String uniqueId) { for (ApplicationRecord r : getInstalledAppRecords()) { if (r.getUniqueId().equals(uniqueId)) { return r; } } return null; } /** * @return if the given ApplicationRecord is the currently seated one */ public boolean isSeated(ApplicationRecord record) { return currentApp != null && currentApp.getUniqueId().equals(record.getUniqueId()); } /** * If the given record is the currently seated app, unseat it */ public void unseat(ApplicationRecord record) { if (isSeated(record)) { this.currentApp.teardownSandbox(); this.currentApp = null; } } /** * Completes a full uninstall of the CC app that the given ApplicationRecord represents. * This method should be idempotent and should be capable of completing an uninstall * regardless of previous failures */ public void uninstall(ApplicationRecord record) { CommCareApp app = new CommCareApp(record); // 1) If the app we are uninstalling is the currently-seated app, tear down its sandbox if (isSeated(record)) { getCurrentApp().teardownSandbox(); unseat(record); } // 2) Set record's status to delete requested, so we know if we have left it in a bad // state later record.setStatus(ApplicationRecord.STATUS_DELETE_REQUESTED); getGlobalStorage(ApplicationRecord.class).write(record); // 3) Delete the directory containing all of this app's resources if (!FileUtil.deleteFileOrDir(app.storageRoot())) { Logger.log(AndroidLogger.TYPE_RESOURCES, "App storage root was unable to be " + "deleted during app uninstall. Aborting uninstall process for now."); return; } // 4) Delete all the user databases associated with this app SqlStorage<UserKeyRecord> userDatabase = app.getStorage(UserKeyRecord.class); for (UserKeyRecord user : userDatabase) { File f = getDatabasePath(DatabaseUserOpenHelper.getDbName(user.getUuid())); if (!FileUtil.deleteFileOrDir(f)) { Logger.log(AndroidLogger.TYPE_RESOURCES, "A user database was unable to be " + "deleted during app uninstall. Aborting uninstall process for now."); // If we failed to delete a file, it is likely because there is an open pointer // to that db still in use, so stop the uninstall for now, and rely on it to // complete the next time the app starts up return; } } // 5) Delete the forms database for this app File formsDb = getDatabasePath(ProviderUtils.getProviderDbName( ProviderUtils.ProviderType.FORMS, app.getAppRecord().getApplicationId())); if (!FileUtil.deleteFileOrDir(formsDb)) { Logger.log(AndroidLogger.TYPE_RESOURCES, "The app's forms database was unable to be " + "deleted during app uninstall. Aborting uninstall process for now."); return; } // 6) Delete the instances database for this app File instancesDb = getDatabasePath(ProviderUtils.getProviderDbName( ProviderUtils.ProviderType.INSTANCES, app.getAppRecord().getApplicationId())); if (!FileUtil.deleteFileOrDir(instancesDb)) { Logger.log(AndroidLogger.TYPE_RESOURCES, "The app's instances database was unable to" + " be deleted during app uninstall. Aborting uninstall process for now."); return; } // 7) Delete the app database File f = getDatabasePath(DatabaseAppOpenHelper.getDbName(app.getAppRecord().getApplicationId())); if (!FileUtil.deleteFileOrDir(f)) { Logger.log(AndroidLogger.TYPE_RESOURCES, "The app database was unable to be deleted" + "during app uninstall. Aborting uninstall process for now."); return; } // 8) Delete the ApplicationRecord getGlobalStorage(ApplicationRecord.class).remove(record.getID()); } private int initGlobalDb() { SQLiteDatabase database; try { database = new DatabaseGlobalOpenHelper(this).getWritableDatabase("null"); database.close(); return STATE_READY; } catch (SQLiteException e) { // Only thrown if DB isn't there return STATE_UNINSTALLED; } catch (MigrationException e) { if (e.isDefiniteFailure()) { return STATE_MIGRATION_FAILED; } else { return STATE_MIGRATION_QUESTIONABLE; } } } public SQLiteDatabase getUserDbHandle() { return this.getSession().getUserDbHandle(); } public <T extends Persistable> SqlStorage<T> getGlobalStorage(Class<T> c) { return getGlobalStorage(c.getAnnotation(Table.class).value(), c); } public <T extends Persistable> SqlStorage<T> getGlobalStorage(String table, Class<T> c) { return new SqlStorage<>(table, c, new AndroidDbHelper(this.getApplicationContext()) { @Override public SQLiteDatabase getHandle() { synchronized (globalDbHandleLock) { if (globalDatabase == null || !globalDatabase.isOpen()) { globalDatabase = new DatabaseGlobalOpenHelper(this.c).getWritableDatabase("null"); } return globalDatabase; } } }); } public <T extends Persistable> SqlStorage<T> getAppStorage(Class<T> c) { return getAppStorage(c.getAnnotation(Table.class).value(), c); } public <T extends Persistable> SqlStorage<T> getAppStorage(String name, Class<T> c) { return currentApp.getStorage(name, c); } public <T extends Persistable> HybridFileBackedSqlStorage<T> getFileBackedAppStorage(String name, Class<T> c) { return currentApp.getFileBackedStorage(name, c); } public <T extends Persistable> SqlStorage<T> getUserStorage(Class<T> c) { return getUserStorage(c.getAnnotation(Table.class).value(), c); } public <T extends Persistable> SqlStorage<T> getUserStorage(String storage, Class<T> c) { return new SqlStorage<>(storage, c, buildUserDbHandle()); } public <T extends Persistable> HybridFileBackedSqlStorage<T> getFileBackedUserStorage(String storage, Class<T> c) { return new HybridFileBackedSqlStorage<>(storage, c, buildUserDbHandle(), getUserKeyRecordId(), CommCareApplication._().getCurrentApp()); } public String getUserKeyRecordId() { return getSession().getUserKeyRecordUUID(); } protected AndroidDbHelper buildUserDbHandle() { return new AndroidDbHelper(this.getApplicationContext()) { @Override public SQLiteDatabase getHandle() { SQLiteDatabase database = getUserDbHandle(); if (database == null) { throw new SessionUnavailableException("The user database has been closed!"); } return database; } }; } public <T extends Persistable> SqlStorage<T> getRawStorage(String storage, Class<T> c, final SQLiteDatabase handle) { return new SqlStorage<>(storage, c, new AndroidDbHelper(this.getApplicationContext()) { @Override public SQLiteDatabase getHandle() { return handle; } }); } public static CommCareApplication _() { return app; } /** * Assumes that there is an active session when it is called, and wipes out all local user * data (users, referrals, etc) for the user with an active session, but leaves application * resources in place. * * It makes no attempt to make sure this is a safe operation when called, so * it shouldn't be used lightly. */ public void clearUserData() { wipeSandboxForUser(this.getSession().getLoggedInUser().getUsername()); CommCareApplication._().getCurrentApp().getAppPreferences().edit() .putString(CommCarePreferences.LAST_LOGGED_IN_USER, null).commit(); CommCareApplication._().closeUserSession(); } public void wipeSandboxForUser(final String username) { // manually clear file-backed fixture storage to ensure files are removed CommCareApplication._().getFileBackedUserStorage("fixture", FormInstance.class).removeAll(); // wipe the user's db final Set<String> dbIdsToRemove = new HashSet<>(); CommCareApplication._().getAppStorage(UserKeyRecord.class).removeAll(new EntityFilter<UserKeyRecord>() { @Override public boolean matches(UserKeyRecord ukr) { if (ukr.getUsername().equalsIgnoreCase(username.toLowerCase())) { dbIdsToRemove.add(ukr.getUuid()); return true; } return false; } }); for (String id : dbIdsToRemove) { CommCareApplication._().getDatabasePath(DatabaseUserOpenHelper.getDbName(id)).delete(); } } public String getCurrentUserId() { try { return this.getSession().getLoggedInUser().getUniqueId(); } catch (SessionUnavailableException e) { return ""; } } public void prepareTemporaryStorage() { String tempRoot = this.getAndroidFsTemp(); FileUtil.deleteFileOrDir(tempRoot); boolean success = FileUtil.createFolder(tempRoot); if (!success) { Logger.log(AndroidLogger.TYPE_ERROR_STORAGE, "Couldn't create temp folder"); } } public String getCurrentVersionString() { PackageManager pm = this.getPackageManager(); PackageInfo pi; try { pi = pm.getPackageInfo(getPackageName(), 0); } catch (NameNotFoundException e) { e.printStackTrace(); return "ERROR! Incorrect package version requested"; } int[] versions = this.getCommCareVersion(); String ccv = ""; for (int vn : versions) { if (!"".equals(ccv)) { ccv += "."; } ccv += vn; } Profile p = this.currentApp == null ? null : this.getCommCarePlatform().getCurrentProfile(); String profileVersion = ""; if (p != null) { profileVersion = String.valueOf(p.getVersion()); } String buildDate = BuildConfig.BUILD_DATE; String buildNumber = BuildConfig.BUILD_NUMBER; return Localization.get(getString(R.string.app_version_string), new String[]{pi.versionName, String.valueOf(pi.versionCode), ccv, buildNumber, buildDate, profileVersion}); } /** * Allows something within the current service binding to update the app to let it * know that the bind may take longer than the current timeout can allow */ public void setCustomServiceBindTimeout(int timeout) { synchronized (serviceLock) { this.mCurrentServiceBindTimeout = timeout; } } private void bindUserSessionService(final byte[] key, final UserKeyRecord record, final boolean restoreSession) { mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName className, IBinder service) { // This is called when the connection with the service has been // established, giving us the service object we can use to // interact with the service. Because we have bound to a explicit // service that we know is running in our own process, we can // cast its IBinder to a concrete class and directly access it. User user = null; synchronized (serviceLock) { mCurrentServiceBindTimeout = MAX_BIND_TIMEOUT; mBoundService = ((CommCareSessionService.LocalBinder)service).getService(); // Don't let anyone touch this until it's logged in // Open user database mBoundService.prepareStorage(key, record); if (record != null) { //Ok, so we have a login that was successful, but do we have a user model in the DB? //We need to check before we're logged in, so we get the handle raw, here for (User u : getRawStorage("USER", User.class, mBoundService.getUserDbHandle())) { if (record.getUsername().equals(u.getUsername())) { user = u; } } } // Switch all loggers over to using user storage while there is a session setupLoggerStorage(true); sessionServiceIsBound = true; // Don't signal bind completion until the db is initialized. sessionServiceIsBinding = false; if (user != null) { mBoundService.startSession(user, record); if (restoreSession) { CommCareApplication.this.sessionWrapper = DevSessionRestorer.restoreSessionFromPrefs(getCommCarePlatform()); } else { CommCareApplication.this.sessionWrapper = new AndroidSessionWrapper(CommCareApplication.this.getCommCarePlatform()); } if (shouldAutoUpdate()) { startAutoUpdate(); } syncPending = getPendingSyncStatus(); doReportMaintenance(false); // Register that this user was the last to successfully log in if it's a real user if (!User.TYPE_DEMO.equals(user.getUserType())) { getCurrentApp().getAppPreferences().edit().putString(CommCarePreferences.LAST_LOGGED_IN_USER, record.getUsername()).commit(); // clear any files orphaned by file-backed db transaction failures HybridFileBackedSqlHelpers.removeOrphanedFiles(mBoundService.getUserDbHandle()); PurgeStaleArchivedFormsTask.launchPurgeTask(); } } TimedStatsTracker.registerStartSession(); } } @Override public void onServiceDisconnected(ComponentName className) { // This is called when the connection with the service has been // unexpectedly disconnected -- that is, its process crashed. // Because it is running in our same process, we should never // see this happen. mBoundService = null; } }; // Establish a connection with the service. We use an explicit // class name because we want a specific service implementation that // we know will be running in our own process (and thus won't be // supporting component replacement by other applications). startService(new Intent(this, CommCareSessionService.class)); bindService(new Intent(this, CommCareSessionService.class), mConnection, Context.BIND_AUTO_CREATE); sessionServiceIsBinding = true; } @SuppressLint("NewApi") private void doReportMaintenance(boolean force) { // Create a new submission task no matter what. If nothing is pending, it'll see if there // are unsent reports and try to send them. Otherwise, it'll create the report SharedPreferences settings = CommCareApplication._().getCurrentApp().getAppPreferences(); String url = settings.getString(CommCareServerPreferences.PREFS_SUBMISSION_URL_KEY, null); if (url == null) { Logger.log(AndroidLogger.TYPE_ERROR_ASSERTION, "PostURL isn't set. This should never happen"); return; } DataSubmissionListener dataListener; dataListener = CommCareApplication.this.getSession().startDataSubmissionListener(R.string.submission_logs_title); LogSubmissionTask task = new LogSubmissionTask( force || isPending(settings.getLong(CommCarePreferences.LOG_LAST_DAILY_SUBMIT, 0), DateUtils.DAY_IN_MILLIS), dataListener, url); // Execute on a true multithreaded chain, since this is an asynchronous process if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } else { task.execute(); } } /** * @return True if we aren't a demo user and the time to check for an * update has elapsed or we logged out while an auto-update was downlaoding * or queued for retry. */ private boolean shouldAutoUpdate() { return (!areAutomatedActionsInvalid() && (ResourceInstallUtils.shouldAutoUpdateResume(getCurrentApp()) || isUpdatePending())); } private void startAutoUpdate() { Logger.log(AndroidLogger.TYPE_MAINTENANCE, "Auto-Update Triggered"); String ref = ResourceInstallUtils.getDefaultProfileRef(); try { UpdateTask updateTask = UpdateTask.getNewInstance(); updateTask.startPinnedNotification(this); updateTask.setAsAutoUpdate(); updateTask.executeParallel(ref); } catch (IllegalStateException e) { Log.w(TAG, "Trying trigger auto-update when it is already running. " + "Should only happen if the user triggered a manual update before this fired."); } } public boolean isUpdatePending() { SharedPreferences preferences = getCurrentApp().getAppPreferences(); // Establish whether or not an AutoUpdate is Pending String autoUpdateFreq = preferences.getString(CommCarePreferences.AUTO_UPDATE_FREQUENCY, CommCarePreferences.FREQUENCY_NEVER); // See if auto update is even turned on if (!autoUpdateFreq.equals(CommCarePreferences.FREQUENCY_NEVER)) { long lastUpdateCheck = preferences.getLong(CommCarePreferences.LAST_UPDATE_ATTEMPT, 0); return isTimeForAutoUpdateCheck(lastUpdateCheck, autoUpdateFreq); } return false; } public boolean isTimeForAutoUpdateCheck(long lastUpdateCheck, String autoUpdateFreq) { int checkEveryNDays; if (CommCarePreferences.FREQUENCY_DAILY.equals(autoUpdateFreq)) { checkEveryNDays = 1; } else { checkEveryNDays = 7; } long duration = DateUtils.DAY_IN_MILLIS * checkEveryNDays; return isPending(lastUpdateCheck, duration); } /** * Used to check if an update, sync, or log submission is pending, based upon the last time * it occurred and the expected period between occurrences */ private boolean isPending(long last, long period) { long now = new Date().getTime(); // 1) Straightforward - Time is greater than last + duration long diff = now - last; if (diff > period) { return true; } // 2) For daily stuff, we want it to be the case that if the last time you synced was the day prior, // you still sync, so people can get into the cycle of doing it once in the morning, which // is more valuable than syncing mid-day. if (isDifferentDayInPast(now, last, period)) { return true; } // 3) Major time change - (Phone might have had its calendar day manipulated). // for now we'll simply say that if last was more than a day in the future (timezone blur) // we should also trigger return (now < (last - DateUtils.DAY_IN_MILLIS)); } private boolean isDifferentDayInPast(long now, long last, long period) { Calendar lastRestoreCalendar = Calendar.getInstance(); lastRestoreCalendar.setTimeInMillis(last); return period == DateUtils.DAY_IN_MILLIS && lastRestoreCalendar.get(Calendar.DAY_OF_WEEK) != Calendar.getInstance().get(Calendar.DAY_OF_WEEK) && now > last; } /** * Whether automated stuff like auto-updates/syncing are valid and should * be triggered. */ private boolean areAutomatedActionsInvalid() { try { return User.TYPE_DEMO.equals(getSession().getLoggedInUser().getUserType()); } catch (SessionUnavailableException sue) { return true; } } private void unbindUserSessionService() { synchronized (serviceLock) { if (sessionServiceIsBound) { if (sessionWrapper != null) { sessionWrapper.reset(); } sessionServiceIsBound = false; // Detach our existing connection. unbindService(mConnection); stopService(new Intent(this, CommCareSessionService.class)); } } } public CommCareSessionService getSession() { long started = System.currentTimeMillis(); while (sessionServiceIsBinding) { if (Looper.getMainLooper().getThread() == Thread.currentThread()) { throw new SessionUnavailableException( "Trying to access session on UI thread while session is binding"); } if (System.currentTimeMillis() - started > mCurrentServiceBindTimeout) { // Something bad happened Log.e(TAG, "WARNING: Timed out while binding to session service, " + "this may cause serious problems."); unbindUserSessionService(); throw new SessionUnavailableException("Timeout binding to session service"); } } if (sessionServiceIsBound) { synchronized (serviceLock) { return mBoundService; } } else { throw new SessionUnavailableException(); } } public UserKeyRecord getRecordForCurrentUser() { return getSession().getUserKeyRecord(); } public static final int MESSAGE_NOTIFICATION = R.string.notification_message_title; private final ArrayList<NotificationMessage> pendingMessages = new ArrayList<>(); public void reportNotificationMessage(NotificationMessage message) { reportNotificationMessage(message, false); } public void reportNotificationMessage(final NotificationMessage message, boolean showToast) { synchronized (pendingMessages) { // Make sure there is no matching message pending for (NotificationMessage msg : pendingMessages) { if (msg.equals(message)) { // If so, bail. return; } } if (showToast) { Bundle b = new Bundle(); b.putParcelable("message", message); Message m = Message.obtain(toaster); m.setData(b); toaster.sendMessage(m); } // Otherwise, add it to the queue, and update the notification pendingMessages.add(message); updateMessageNotification(); } } private void updateMessageNotification() { NotificationManager mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); synchronized (pendingMessages) { if (pendingMessages.size() == 0) { mNM.cancel(MESSAGE_NOTIFICATION); return; } String title = pendingMessages.get(0).getTitle(); // The PendingIntent to launch our activity if the user selects this notification Intent i = new Intent(this, MessageActivity.class); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, i, 0); String additional = pendingMessages.size() > 1 ? Localization.get("notifications.prompt.more", new String[]{String.valueOf(pendingMessages.size() - 1)}) : ""; Notification messageNotification = new NotificationCompat.Builder(this) .setContentTitle(title) .setContentText(Localization.get("notifications.prompt.details", new String[]{additional})) .setSmallIcon(R.drawable.notification) .setNumber(pendingMessages.size()) .setContentIntent(contentIntent) .setDeleteIntent(PendingIntent.getBroadcast(this, 0, new Intent(this, NotificationClearReceiver.class), 0)) .setOngoing(true) .setWhen(System.currentTimeMillis()) .build(); mNM.notify(MESSAGE_NOTIFICATION, messageNotification); } } public ArrayList<NotificationMessage> purgeNotifications() { synchronized (pendingMessages) { this.sendBroadcast(new Intent(ACTION_PURGE_NOTIFICATIONS)); ArrayList<NotificationMessage> cloned = (ArrayList<NotificationMessage>)pendingMessages.clone(); clearNotifications(null); return cloned; } } public void clearNotifications(String category) { synchronized (pendingMessages) { NotificationManager mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); Vector<NotificationMessage> toRemove = new Vector<>(); for (NotificationMessage message : pendingMessages) { if (category == null || category.equals(message.getCategory())) { toRemove.add(message); } } for (NotificationMessage message : toRemove) { pendingMessages.remove(message); } if (pendingMessages.size() == 0) { mNM.cancel(MESSAGE_NOTIFICATION); } else { updateMessageNotification(); } } } private boolean syncPending = false; /** * @return True if there is a sync action pending. */ private boolean getPendingSyncStatus() { SharedPreferences prefs = CommCareApplication._().getCurrentApp().getAppPreferences(); long period = -1; // Old flag, use a day by default if ("true".equals(prefs.getString("cc-auto-update", "false"))) { period = DateUtils.DAY_IN_MILLIS; } // new flag, read what it is. String periodic = prefs.getString(CommCarePreferences.AUTO_SYNC_FREQUENCY, CommCarePreferences.FREQUENCY_NEVER); if (!periodic.equals(CommCarePreferences.FREQUENCY_NEVER)) { period = DateUtils.DAY_IN_MILLIS * (periodic.equals(CommCarePreferences.FREQUENCY_DAILY) ? 1 : 7); } // If we didn't find a period, bail if (period == -1) { return false; } long lastRestore = prefs.getLong(CommCarePreferences.LAST_SYNC_ATTEMPT, 0); return (isPending(lastRestore, period)); } public synchronized boolean isSyncPending(boolean clearFlag) { if (areAutomatedActionsInvalid()) { return false; } // We only set this to true occasionally, but in theory it could be set to false // from other factors, so turn it off if it is. if (!getPendingSyncStatus()) { syncPending = false; } if (!syncPending) { return false; } if (clearFlag) { syncPending = false; } return true; } public boolean isStorageAvailable() { try { File storageRoot = new File(getAndroidFsRoot()); return storageRoot.exists(); } catch (Exception e) { return false; } } /** * Notify the application that something has occurred which has been * logged, and which should cause log submission to occur as soon as * possible. */ public void notifyLogsPending() { doReportMaintenance(true); } public String getAndroidFsRoot() { return Environment.getExternalStorageDirectory().toString() + "/Android/data/" + getPackageName() + "/files/"; } public String getAndroidFsTemp() { return Environment.getExternalStorageDirectory().toString() + "/Android/data/" + getPackageName() + "/temp/"; } /** * @return a path to a file location that can be used to store a file * temporarily and will be cleaned up as part of CommCare's application * lifecycle */ public String getTempFilePath() { return getAndroidFsTemp() + PropertyUtils.genUUID(); } public ArchiveFileRoot getArchiveFileRoot() { return mArchiveFileRoot; } /** * Message handler that pops-up notifications to the user via toast. */ private static class PopupHandler extends Handler { /** * Reference to the context used to show pop-ups (the parent class). * Reference is weak to avoid memory leaks. */ private final WeakReference<CommCareApplication> mActivity; /** * @param activity Is the context used to pop-up the toast message. */ public PopupHandler(CommCareApplication activity) { mActivity = new WeakReference<>(activity); } /** * Pops up the message to the user by way of toast * * @param m Has a 'message' parcel storing pop-up message text */ @Override public void handleMessage(Message m) { NotificationMessage message = m.getData().getParcelable("message"); CommCareApplication activity = mActivity.get(); if (activity != null && message != null) { Toast.makeText(activity, Localization.get("notification.for.details.wrapper", new String[]{message.getTitle()}), Toast.LENGTH_LONG).show(); } } } /** * Used for manually linking to a session service during tests */ public void setTestingService(CommCareSessionService service) { sessionServiceIsBound = true; mBoundService = service; mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName className, IBinder service) { } @Override public void onServiceDisconnected(ComponentName className) { } }; } public void storeMessageForUserOnDispatch(String title, String message) { this.titleForUserMessage = title; this.messageForUserOnDispatch = message; } public String[] getPendingUserMessage() { if (messageForUserOnDispatch != null) { return new String[]{messageForUserOnDispatch, titleForUserMessage}; } return null; } public void clearPendingUserMessage() { messageForUserOnDispatch = null; titleForUserMessage = null; } private void setupLoggerStorage(boolean userStorageAvailable) { if (userStorageAvailable) { Logger.registerLogger(new AndroidLogger(getUserStorage(AndroidLogEntry.STORAGE_KEY, AndroidLogEntry.class))); ForceCloseLogger.registerStorage(getUserStorage(ForceCloseLogEntry.STORAGE_KEY, ForceCloseLogEntry.class)); XPathErrorLogger.registerStorage(getUserStorage(XPathErrorEntry.STORAGE_KEY, XPathErrorEntry.class)); } else { Logger.registerLogger(new AndroidLogger( this.getGlobalStorage(AndroidLogEntry.STORAGE_KEY, AndroidLogEntry.class))); ForceCloseLogger.registerStorage( this.getGlobalStorage(ForceCloseLogEntry.STORAGE_KEY, ForceCloseLogEntry.class)); } } public void setPendingRefreshToLatestBuild(boolean b) { this.latestBuildRefreshPending = b; } public boolean checkPendingBuildRefresh() { if (this.latestBuildRefreshPending) { this.latestBuildRefreshPending = false; return true; } return false; } public ModernHttpRequester buildModernHttpRequester(Context context, URL url, HashMap<String, String> params, boolean isAuthenticatedRequest, boolean isPostRequest) { Pair<User, String> userAndDomain = HttpUtils.getUserAndDomain(isAuthenticatedRequest); return new AndroidModernHttpRequester(new AndroidCacheDirSetup(context), url, params, userAndDomain.first, userAndDomain.second, isAuthenticatedRequest, isPostRequest); } public DataPullRequester getDataPullRequester(){ return DataPullResponseFactory.INSTANCE; } /** * A consumer app is a CommCare build flavor in which the .ccz and restore file for a specific * app and user have been pre-packaged along with CommCare into a custom .apk, and placed on * the Play Store under a custom name/branding scheme. */ public boolean isConsumerApp() { return BuildConfig.IS_CONSUMER_APP; } public boolean shouldInvalidateCacheOnRestore() { return invalidateCacheOnRestore; } public void setInvalidateCacheFlag(boolean b) { invalidateCacheOnRestore = b; } public PrototypeFactory getPrototypeFactory(Context c) { return AndroidPrototypeFactorySetup.getPrototypeFactory(c); } }
package com.jaamsim.input; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.filechooser.FileNameExtensionFilter; import com.jaamsim.ui.ExceptionBox; import com.jaamsim.ui.FrameBox; import com.jaamsim.ui.LogBox; import com.sandwell.JavaSimulation.Entity; import com.sandwell.JavaSimulation.ErrorException; import com.sandwell.JavaSimulation.FileEntity; import com.sandwell.JavaSimulation.Group; import com.sandwell.JavaSimulation.Input; import com.sandwell.JavaSimulation.Input.ParseContext; import com.sandwell.JavaSimulation.InputErrorException; import com.sandwell.JavaSimulation.ObjectType; import com.sandwell.JavaSimulation.Palette; import com.sandwell.JavaSimulation.Simulation; import com.sandwell.JavaSimulation.StringVector; import com.sandwell.JavaSimulation3D.GUIFrame; public class InputAgent { private static final String recordEditsMarker = "RecordEdits"; private static int numErrors = 0; private static int numWarnings = 0; private static FileEntity logFile; private static double lastTimeForTrace; private static File configFile; // present configuration file private static boolean batchRun; private static boolean sessionEdited; // TRUE if any inputs have been changed after loading a configuration file private static boolean recordEditsFound; // TRUE if the "RecordEdits" marker is found in the configuration file private static boolean recordEdits; // TRUE if input changes are to be marked as edited. private static final String INP_ERR_DEFINEUSED = "The name: %s has already been used and is a %s"; private static File reportDir; static { recordEditsFound = false; sessionEdited = false; batchRun = false; configFile = null; reportDir = null; lastTimeForTrace = -1.0d; } public static void clear() { logFile = null; numErrors = 0; numWarnings = 0; recordEditsFound = false; sessionEdited = false; configFile = null; reportDir = null; lastTimeForTrace = -1.0d; setReportDirectory(null); } private static String getReportDirectory() { if (reportDir != null) return reportDir.getPath() + File.separator; if (configFile != null) return configFile.getParentFile().getPath() + File.separator; return null; } public static String getReportFileName(String name) { return getReportDirectory() + name; } public static void setReportDirectory(File dir) { reportDir = dir; } public static void prepareReportDirectory() { if (reportDir != null) reportDir.mkdirs(); } /** * Sets the present configuration file. * * @param file - the present configuration file. */ public static void setConfigFile(File file) { configFile = file; } /** * Returns the present configuration file. * <p> * Null is returned if no configuration file has been loaded or saved yet. * <p> * @return the present configuration file. */ public static File getConfigFile() { return configFile; } /** * Returns the name of the simulation run. * <p> * For example, if the configuration file name is "case1.cfg", then the * run name is "case1". * <p> * @return the name of simulation run. */ public static String getRunName() { if( InputAgent.getConfigFile() == null ) return ""; String name = InputAgent.getConfigFile().getName(); int index = name.lastIndexOf( "." ); if( index == -1 ) return name; return name.substring( 0, index ); } /** * Specifies whether a RecordEdits marker was found in the present configuration file. * * @param bool - TRUE if a RecordEdits marker was found. */ public static void setRecordEditsFound(boolean bool) { recordEditsFound = bool; } /** * Indicates whether a RecordEdits marker was found in the present configuration file. * * @return - TRUE if a RecordEdits marker was found. */ public static boolean getRecordEditsFound() { return recordEditsFound; } /** * Returns the "RecordEdits" mode for the InputAgent. * <p> * When RecordEdits is TRUE, any model inputs that are changed and any objects that * are defined are marked as "edited". When FALSE, model inputs and object * definitions are marked as "unedited". * <p> * RecordEdits mode is used to determine the way JaamSim saves a configuration file * through the graphical user interface. Object definitions and model inputs * that are marked as unedited will be copied exactly as they appear in the original * configuration file that was first loaded. Object definitions and model inputs * that are marked as edited will be generated automatically by the program. * * @return the RecordEdits mode for the InputAgent. */ public static boolean recordEdits() { return recordEdits; } /** * Sets the "RecordEdits" mode for the InputAgent. * <p> * When RecordEdits is TRUE, any model inputs that are changed and any objects that * are defined are marked as "edited". When FALSE, model inputs and object * definitions are marked as "unedited". * <p> * RecordEdits mode is used to determine the way JaamSim saves a configuration file * through the graphical user interface. Object definitions and model inputs * that are marked as unedited will be copied exactly as they appear in the original * configuration file that was first loaded. Object definitions and model inputs * that are marked as edited will be generated automatically by the program. * * @param b - boolean value for the RecordEdits mode */ public static void setRecordEdits(boolean b) { recordEdits = b; } public static boolean isSessionEdited() { return sessionEdited; } public static void setBatch(boolean batch) { batchRun = batch; } public static boolean getBatch() { return batchRun; } /** * returns true if the first and last tokens are matched braces **/ public static boolean enclosedByBraces(ArrayList<String> tokens) { if(tokens.size() < 2 || tokens.indexOf("{") < 0) // no braces return false; int level =1; int i = 1; for(String each: tokens.subList(1, tokens.size())) { if(each.equals("{")) { level++; } if(each.equals("}")) { level // Matching close brace found if(level == 0) break; } i++; } if(level == 0 && i == tokens.size()-1) { return true; } return false; } private static int getBraceDepth(ArrayList<String> tokens, int startingBraceDepth, int startingIndex) { int braceDepth = startingBraceDepth; for (int i = startingIndex; i < tokens.size(); i++) { String token = tokens.get(i); if (token.equals("{")) braceDepth++; if (token.equals("}")) braceDepth if (braceDepth < 0) { InputAgent.logBadInput(tokens, "Extra closing braces found"); tokens.clear(); } if (braceDepth > 2) { InputAgent.logBadInput(tokens, "Maximum brace depth (2) exceeded"); tokens.clear(); } } return braceDepth; } private static URI resRoot; private static URI resPath; private static final String res = "/resources/"; static { try { // locate the resource folder, and create resRoot = InputAgent.class.getResource(res).toURI(); } catch (URISyntaxException e) {} resPath = URI.create(resRoot.toString()); } private static void rethrowWrapped(Exception ex) { StringBuilder causedStack = new StringBuilder(); for (StackTraceElement elm : ex.getStackTrace()) causedStack.append(elm.toString()).append("\n"); throw new InputErrorException("Caught exception: %s", ex.getMessage() + "\n" + causedStack.toString()); } public static final void readResource(String res) { if (res == null) return; try { readStream(resRoot.toString(), resPath, res); GUIFrame.instance().setProgressText(null); } catch (URISyntaxException ex) { rethrowWrapped(ex); } } public static final boolean readStream(String root, URI path, String file) throws URISyntaxException { String shortName = file.substring(file.lastIndexOf('/') + 1, file.length()); GUIFrame.instance().setProgressText(shortName); URI resolved = getFileURI(path, file, root); URL url = null; try { url = resolved.normalize().toURL(); } catch (MalformedURLException e) { rethrowWrapped(e); } if (url == null) { InputAgent.logWarning("Unable to resolve path %s%s - %s", root, path.toString(), file); return false; } BufferedReader buf = null; try { InputStream in = url.openStream(); buf = new BufferedReader(new InputStreamReader(in)); } catch (IOException e) { InputAgent.logWarning("Could not read from %s", url.toString()); return false; } try { ArrayList<String> record = new ArrayList<String>(); int braceDepth = 0; Input.ParseContext pc = new Input.ParseContext(); pc.jail = root; pc.context = resolved; while (true) { String line = buf.readLine(); // end of file, stop reading if (line == null) break; int previousRecordSize = record.size(); Parser.tokenize(record, line, true); braceDepth = InputAgent.getBraceDepth(record, braceDepth, previousRecordSize); if( braceDepth != 0 ) continue; if (record.size() == 0) continue; InputAgent.echoInputRecord(record); if ("DEFINE".equalsIgnoreCase(record.get(0))) { InputAgent.processDefineRecord(record); record.clear(); continue; } if ("INCLUDE".equalsIgnoreCase(record.get(0))) { try { InputAgent.processIncludeRecord(pc, record); } catch (URISyntaxException ex) { rethrowWrapped(ex); } record.clear(); continue; } if ("RECORDEDITS".equalsIgnoreCase(record.get(0))) { InputAgent.setRecordEditsFound(true); InputAgent.setRecordEdits(true); record.clear(); continue; } // Otherwise assume it is a Keyword record InputAgent.processKeywordRecord(record, pc); record.clear(); } // Leftover Input at end of file if (record.size() > 0) InputAgent.logBadInput(record, "Leftover input at end of file"); buf.close(); } catch (IOException e) { // Make best effort to ensure it closes try { buf.close(); } catch (IOException e2) {} } return true; } private static void processIncludeRecord(ParseContext pc, ArrayList<String> record) throws URISyntaxException { if (record.size() != 2) { InputAgent.logError("Bad Include record, should be: Include <File>"); return; } InputAgent.readStream(pc.jail, pc.context, record.get(1).replaceAll("\\\\", "/")); } private static void processDefineRecord(ArrayList<String> record) { if (record.size() < 5 || !record.get(2).equals("{") || !record.get(record.size() - 1).equals("}")) { InputAgent.logError("Bad Define record, should be: Define <Type> { <names>... }"); return; } Class<? extends Entity> proto = null; try { if( record.get( 1 ).equalsIgnoreCase( "Palette" ) ) { proto = Palette.class; } else if( record.get( 1 ).equalsIgnoreCase( "ObjectType" ) ) { proto = ObjectType.class; } else { proto = Input.parseEntityType(record.get(1)); } } catch (InputErrorException e) { InputAgent.logError("%s", e.getMessage()); return; } // Loop over all the new Entity names for (int i = 3; i < record.size() - 1; i++) { InputAgent.defineEntity(proto, record.get(i), InputAgent.recordEdits()); } } /** * Like defineEntity(), but will generate a unique name if a name collision exists * @param proto * @param key * @param addedEntity * @return */ public static <T extends Entity> T defineEntityWithUniqueName(Class<T> proto, String key, boolean addedEntity) { // Has the provided name been used already? if (Entity.getNamedEntity(key) == null) { return defineEntity(proto, key, addedEntity); } // Try the provided name plus "-1", "-2", etc. until an unused name is found int entityNum = 1; while(true) { String name = String.format("%s-%d", key, entityNum); if (Entity.getNamedEntity(name) == null) { return defineEntity(proto, name, addedEntity); } entityNum++; } } /** * if addedEntity is true then this is an entity defined * by user interaction or after added record flag is found; * otherwise, it is from an input file define statement * before the model is configured * @param proto * @param key * @param addedEntity */ public static <T extends Entity> T defineEntity(Class<T> proto, String key, boolean addedEntity) { Entity existingEnt = Input.tryParseEntity(key, Entity.class); if (existingEnt != null) { InputAgent.logError(INP_ERR_DEFINEUSED, key, existingEnt.getClass().getSimpleName()); return null; } T ent = null; try { ent = proto.newInstance(); if (addedEntity) { ent.setFlag(Entity.FLAG_ADDED); sessionEdited = true; } } catch (InstantiationException e) {} catch (IllegalAccessException e) {} finally { if (ent == null) { InputAgent.logError("Could not create new Entity: %s", key); return null; } } ent.setInputName(key); return ent; } public static void processKeywordRecord(ArrayList<String> record, Input.ParseContext context) { Entity ent = Input.tryParseEntity(record.get(0), Entity.class); if (ent == null) { InputAgent.logError("Could not find Entity: %s", record.get(0)); return; } // Validate the tokens have the Entity Keyword { Args... } Keyword { Args... } ArrayList<KeywordIndex> words = InputAgent.getKeywords(record, context); for (KeywordIndex keyword : words) { try { InputAgent.processKeyword(ent, keyword); } catch (Throwable e) { InputAgent.logInpError("Entity: %s, Keyword: %s - %s", ent.getInputName(), keyword.keyword, e.getMessage()); } } } public static class KeywordIndex { public final ArrayList<String> input; public final String keyword; public final int start; public final int end; public final ParseContext context; public KeywordIndex(ArrayList<String> inp, int s, int e, ParseContext ctxt) { input = inp; keyword = input.get(s); start = s; end = e; context = ctxt; } } private static ArrayList<KeywordIndex> getKeywords(ArrayList<String> input, ParseContext context) { ArrayList<KeywordIndex> ret = new ArrayList<KeywordIndex>(); int braceDepth = 0; int index = 1; for (int i = 1; i < input.size(); i++) { String tok = input.get(i); if ("{".equals(tok)) { braceDepth++; continue; } if ("}".equals(tok)) { braceDepth if (braceDepth == 0) { ret.add(new KeywordIndex(input, index, i, context)); index = i + 1; continue; } } } // Look for a leftover keyword at the end of line KeywordIndex last = ret.get(ret.size() - 1); if (last.end != input.size() - 1) { ret.add(new KeywordIndex(input, last.end + 1, input.size() - 1, context)); } for (KeywordIndex kw : ret) { if (!"{".equals(input.get(kw.start + 1)) || !"}".equals(input.get(kw.end))) { throw new InputErrorException("Keyword %s not valid, should be <keyword> { <args> }", kw.keyword); } } return ret; } public static void doError(Throwable e) { if (!batchRun) return; LogBox.logLine("An error occurred in the simulation environment. Please check inputs for an error:"); LogBox.logLine(e.toString()); GUIFrame.shutdown(1); } // Load the run file public static void loadConfigurationFile( File file) throws URISyntaxException { String inputTraceFileName = InputAgent.getRunName() + ".log"; // Initializing the tracing for the model try { System.out.println( "Creating trace file" ); URI confURI = file.toURI(); URI logURI = confURI.resolve(new URI(null, inputTraceFileName, null)); // The new URI here effectively escapes the file name // Set and open the input trace file name logFile = new FileEntity( logURI.getPath()); } catch( Exception e ) { InputAgent.logWarning("Could not create trace file"); } URI dirURI = file.getParentFile().toURI(); InputAgent.readStream("", dirURI, file.getName()); GUIFrame.instance().setProgressText(null); GUIFrame.instance().setProgress(0); // At this point configuration file is loaded // The session is not considered to be edited after loading a configuration file sessionEdited = false; // Save and close the input trace file if (logFile != null) { if (InputAgent.numWarnings == 0 && InputAgent.numErrors == 0) { logFile.close(); logFile.delete(); logFile = new FileEntity( inputTraceFileName); } } // Check for found errors if( InputAgent.numErrors > 0 ) throw new InputErrorException("%d input errors and %d warnings found, check %s", InputAgent.numErrors, InputAgent.numWarnings, inputTraceFileName); if (Simulation.getPrintInputReport()) InputAgent.printInputFileKeywords(); } public static final void apply(Entity ent, KeywordIndex kw) { Input<?> in = ent.getInput(kw.keyword); if (in == null) { InputAgent.logWarning("Keyword %s could not be found for Entity %s.", kw.keyword, ent.getInputName()); return; } InputAgent.apply(ent, in, kw); FrameBox.valueUpdate(); } public static final void apply(Entity ent, Input<?> in, KeywordIndex kw) { StringVector data = new StringVector(kw.end - kw.start); for (int i = kw.start + 2; i < kw.end; i++) { data.add(kw.input.get(i)); } in.parse(data, kw.context); // Only mark the keyword edited if we have finished initial configuration if ( InputAgent.recordEdits() ) in.setEdited(true); ent.updateForInput(in); if(ent.testFlag(Entity.FLAG_GENERATED)) return; StringBuilder out = new StringBuilder(data.size() * 6); for (int i = 0; i < data.size(); i++) { String dat = data.get(i); if (Parser.needsQuoting(dat) && !dat.equals("{") && !dat.equals("}")) out.append("'").append(dat).append("'"); else out.append(dat); if( i < data.size() - 1 ) out.append(" "); } if(in.isEdited()) { ent.setFlag(Entity.FLAG_EDITED); sessionEdited = true; } in.setValueString(out.toString()); } private static void processKeyword(Entity entity, KeywordIndex key) { if (entity.testFlag(Entity.FLAG_LOCKED)) throw new InputErrorException("Entity: %s is locked and cannot be modified", entity.getName()); Input<?> input = entity.getInput( key.keyword ); if (input != null) { InputAgent.apply(entity, input, key); FrameBox.valueUpdate(); return; } if (!(entity instanceof Group)) throw new InputErrorException("Not a valid keyword"); Group grp = (Group)entity; grp.saveGroupKeyword(key); // Store the keyword data for use in the edit table for( int i = 0; i < grp.getList().size(); i++ ) { Entity ent = grp.getList().get( i ); InputAgent.apply(ent, key); } } private static class ConfigFileFilter implements FilenameFilter { @Override public boolean accept(File inFile, String fileName) { return fileName.endsWith("[cC][fF][gG]"); } } public static void load(GUIFrame gui) { LogBox.logLine("Loading..."); // Create a file chooser final JFileChooser chooser = new JFileChooser(InputAgent.getConfigFile()); // Set the file extension filters chooser.setAcceptAllFileFilterUsed(true); FileNameExtensionFilter cfgFilter = new FileNameExtensionFilter("JaamSim Configuration File (*.cfg)", "CFG"); chooser.addChoosableFileFilter(cfgFilter); chooser.setFileFilter(cfgFilter); // Show the file chooser and wait for selection int returnVal = chooser.showOpenDialog(gui); // Load the selected file if (returnVal == JFileChooser.APPROVE_OPTION) { File temp = chooser.getSelectedFile(); InputAgent.setLoadFile(gui, temp); } } public static void save(GUIFrame gui) { LogBox.logLine("Saving..."); if( InputAgent.getConfigFile() != null ) { setSaveFile(gui, InputAgent.getConfigFile().getPath() ); } else { saveAs( gui ); } } public static void saveAs(GUIFrame gui) { LogBox.logLine("Save As..."); // Create a file chooser final JFileChooser chooser = new JFileChooser(InputAgent.getConfigFile()); // Set the file extension filters chooser.setAcceptAllFileFilterUsed(true); FileNameExtensionFilter cfgFilter = new FileNameExtensionFilter("JaamSim Configuration File (*.cfg)", "CFG"); chooser.addChoosableFileFilter(cfgFilter); chooser.setFileFilter(cfgFilter); // Show the file chooser and wait for selection int returnVal = chooser.showSaveDialog(gui); // Load the selected file if (returnVal == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); String filePath = file.getPath(); // Add the file extension ".cfg" if needed filePath = filePath.trim(); if (filePath.indexOf(".") == -1) filePath = filePath.concat(".cfg"); // Confirm overwrite if file already exists File temp = new File(filePath); if (temp.exists()) { int userOption = JOptionPane.showConfirmDialog( null, file.getName() + " already exists.\n" + "Do you wish to replace it?", "Confirm Save As", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE ); if (userOption == JOptionPane.NO_OPTION) { return; } } // Save the configuration file InputAgent.setSaveFile(gui, filePath); } } public static void configure(GUIFrame gui, File file) { try { gui.clear(); InputAgent.setConfigFile(file); gui.updateForSimulationState(GUIFrame.SIM_STATE_UNCONFIGURED); try { InputAgent.loadConfigurationFile(file); } catch( InputErrorException iee ) { if (!batchRun) ExceptionBox.instance().setErrorBox(iee.getMessage()); else LogBox.logLine( iee.getMessage() ); } LogBox.logLine("Configuration File Loaded"); // show the present state in the user interface gui.setTitle( Simulation.getModelName() + " - " + InputAgent.getRunName() ); gui.updateForSimulationState(GUIFrame.SIM_STATE_CONFIGURED); gui.enableSave(InputAgent.getRecordEditsFound()); } catch( Throwable t ) { ExceptionBox.instance().setError(t); } } /** * Loads the configuration file. * <p> * @param gui - the Control Panel. * @param file - the configuration file to be loaded. */ private static void setLoadFile(final GUIFrame gui, File file) { final File chosenfile = file; new Thread(new Runnable() { @Override public void run() { InputAgent.setRecordEdits(false); InputAgent.configure(gui, chosenfile); InputAgent.setRecordEdits(true); GUIFrame.displayWindows(true); FrameBox.valueUpdate(); } }).start(); } /** * Saves the configuration file. * @param gui = Control Panel window for JaamSim * @param fileName = absolute file path and file name for the file to be saved */ private static void setSaveFile(GUIFrame gui, String fileName) { // Set root directory File temp = new File(fileName); // Save the configuration file InputAgent.printNewConfigurationFileWithName( fileName ); sessionEdited = false; InputAgent.setConfigFile(temp); // Set the title bar to match the new run name gui.setTitle( Simulation.getModelName() + " - " + InputAgent.getRunName() ); } /* * write input file keywords and values * * input file format: * Define Group { <Group names> } * Define <Object> { <Object names> } * * <Object name> <Keyword> { < values > } * */ public static void printInputFileKeywords() { // Create report file for the inputs String inputReportFileName = InputAgent.getReportFileName(InputAgent.getRunName() + ".inp"); FileEntity inputReportFile = new FileEntity( inputReportFileName); inputReportFile.flush(); // Loop through the entity classes printing Define statements for (ObjectType type : ObjectType.getAll()) { Class<? extends Entity> each = type.getJavaClass(); // Loop through the instances for this entity class int count = 0; for (Entity ent : Entity.getInstanceIterator(each)) { boolean hasinput = false; for (Input<?> in : ent.getEditableInputs()) { // If the keyword has been used, then add a record to the report if (in.getValueString().length() != 0) { hasinput = true; count++; break; } } if (hasinput) { String entityName = ent.getInputName(); if ((count - 1) % 5 == 0) { inputReportFile.putString("Define"); inputReportFile.putTab(); inputReportFile.putString(type.getInputName()); inputReportFile.putTab(); inputReportFile.putString("{ " + entityName); inputReportFile.putTab(); } else if ((count - 1) % 5 == 4) { inputReportFile.putString(entityName + " }"); inputReportFile.newLine(); } else { inputReportFile.putString(entityName); inputReportFile.putTab(); } } } if (!Entity.getInstanceIterator(each).hasNext()) { if (count % 5 != 0) { inputReportFile.putString(" }"); inputReportFile.newLine(); } inputReportFile.newLine(); } } for (ObjectType type : ObjectType.getAll()) { Class<? extends Entity> each = type.getJavaClass(); // Get the list of instances for this entity class // sort the list alphabetically ArrayList<? extends Entity> cloneList = Entity.getInstancesOf(each); // Print the entity class name to the report (in the form of a comment) if (cloneList.size() > 0) { inputReportFile.putString("\" " + each.getSimpleName() + " \""); inputReportFile.newLine(); inputReportFile.newLine(); // blank line below the class name heading } Collections.sort(cloneList, new Comparator<Entity>() { @Override public int compare(Entity a, Entity b) { return a.getInputName().compareTo(b.getInputName()); } }); // Loop through the instances for this entity class for (int j = 0; j < cloneList.size(); j++) { // Make sure the clone is an instance of the class (and not an instance of a subclass) if (cloneList.get(j).getClass() == each) { Entity ent = cloneList.get(j); String entityName = ent.getInputName(); boolean hasinput = false; // Loop through the editable keywords for this instance for (Input<?> in : ent.getEditableInputs()) { // If the keyword has been used, then add a record to the report if (in.getValueString().length() != 0) { if (!in.getCategory().contains("Graphics")) { hasinput = true; inputReportFile.putTab(); inputReportFile.putString(entityName); inputReportFile.putTab(); inputReportFile.putString(in.getKeyword()); inputReportFile.putTab(); if (in.getValueString().lastIndexOf("{") > 10) { String[] item1Array; item1Array = in.getValueString().trim().split(" }"); inputReportFile.putString("{ " + item1Array[0] + " }"); for (int l = 1; l < (item1Array.length); l++) { inputReportFile.newLine(); inputReportFile.putTabs(5); inputReportFile.putString(item1Array[l] + " } "); } inputReportFile.putString(" }"); } else { inputReportFile.putString("{ " + in.getValueString() + " }"); } inputReportFile.newLine(); } } } // Put a blank line after each instance if (hasinput) { inputReportFile.newLine(); } } } } // Close out the report inputReportFile.flush(); inputReportFile.close(); } public static void closeLogFile() { if (logFile == null) return; logFile.flush(); logFile.close(); if (numErrors ==0 && numWarnings == 0) { logFile.delete(); } logFile = null; } private static final String errPrefix = "*** ERROR *** %s%n"; private static final String inpErrPrefix = "*** INPUT ERROR *** %s%n"; private static final String wrnPrefix = "***WARNING*** %s%n"; public static int numErrors() { return numErrors; } public static int numWarnings() { return numWarnings; } private static void echoInputRecord(ArrayList<String> tokens) { if (logFile == null) return; StringBuilder line = new StringBuilder(); for (int i = 0; i < tokens.size(); i++) { line.append(" ").append(tokens.get(i)); if (tokens.get(i).startsWith("\"")) { logFile.write(line.toString()); logFile.newLine(); line.setLength(0); } } // Leftover input if (line.length() > 0) { logFile.write(line.toString()); logFile.newLine(); } logFile.flush(); } private static void logBadInput(ArrayList<String> tokens, String msg) { InputAgent.echoInputRecord(tokens); InputAgent.logError("%s", msg); } public static void logMessage(String fmt, Object... args) { String msg = String.format(fmt, args); System.out.println(msg); LogBox.logLine(msg); if (logFile == null) return; logFile.write(msg); logFile.newLine(); logFile.flush(); } public static void trace(int indent, Entity ent, String meth, String... text) { // Create an indent string to space the lines StringBuilder ind = new StringBuilder(""); for (int i = 0; i < indent; i++) ind.append(" "); String spacer = ind.toString(); // Print a TIME header every time time has advanced double traceTime = ent.getCurrentTime(); if (lastTimeForTrace != traceTime) { System.out.format(" \nTIME = %.5f\n", traceTime); lastTimeForTrace = traceTime; } // Output the traces line(s) System.out.format("%s%s %s\n", spacer, ent.getName(), meth); for (String line : text) { System.out.format("%s%s\n", spacer, line); } System.out.flush(); } public static void logWarning(String fmt, Object... args) { numWarnings++; String msg = String.format(fmt, args); InputAgent.logMessage(wrnPrefix, msg); } public static void logError(String fmt, Object... args) { numErrors++; String msg = String.format(fmt, args); InputAgent.logMessage(errPrefix, msg); } public static void logInpError(String fmt, Object... args) { numErrors++; String msg = String.format(fmt, args); InputAgent.logMessage(inpErrPrefix, msg); } /** * Prepares the keyword and input value for processing. * * @param ent - the entity whose keyword and value have been entered. * @param in - the input object for the keyword. * @param value - the input value String for the keyword. */ public static void processEntity_Keyword_Value(Entity ent, Input<?> in, String value){ processEntity_Keyword_Value(ent, in.getKeyword(), value); } /** * Prepares the keyword and input value for processing. * * @param ent - the entity whose keyword and value has been entered. * @param keyword - the keyword. * @param value - the input value String for the keyword. */ public static void processEntity_Keyword_Value(Entity ent, String keyword, String value){ // Keyword ArrayList<String> tokens = new ArrayList<String>(); tokens.add(keyword); // Opening brace tokens.add("{"); // Value if (!value.equals(Input.getNoValue())) Parser.tokenize(tokens, value, true); // Closing brace tokens.add("}"); // Parse the keyword inputs KeywordIndex kw = new KeywordIndex(tokens, 0, tokens.size() - 1, null); InputAgent.processKeyword(ent, kw); } /** * Prints the present state of the model to a new configuration file. * * @param fileName - the full path and file name for the new configuration file. */ public static void printNewConfigurationFileWithName( String fileName ) { // Copy the original configuration file up to the "RecordEdits" marker (if present) // Temporary storage for the copied lines is needed in case the original file is to be overwritten ArrayList<String> preAddedRecordLines = new ArrayList<String>(); if( InputAgent.getConfigFile() != null ) { try { BufferedReader in = new BufferedReader( new FileReader(InputAgent.getConfigFile()) ); String line; while ( ( line = in.readLine() ) != null ) { preAddedRecordLines.add( line ); if ( line.startsWith( recordEditsMarker ) ) { break; } } in.close(); } catch ( Exception e ) { throw new ErrorException( e ); } } // Create the new configuration file and copy the saved lines FileEntity file = new FileEntity( fileName); for( int i=0; i < preAddedRecordLines.size(); i++ ) { file.format("%s%n", preAddedRecordLines.get( i )); } // If not already present, insert the "RecordEdits" marker at the end of the original configuration file if( ! InputAgent.getRecordEditsFound() ) { file.format("%n%s%n", recordEditsMarker); InputAgent.setRecordEditsFound(true); } // Determine all the new classes that were created ArrayList<Class<? extends Entity>> newClasses = new ArrayList<Class<? extends Entity>>(); for (int i = 0; i < Entity.getAll().size(); i++) { Entity ent = Entity.getAll().get(i); if (!ent.testFlag(Entity.FLAG_ADDED)) continue; if (!newClasses.contains(ent.getClass())) newClasses.add(ent.getClass()); } // Add a blank line before the first object definition if( !newClasses.isEmpty() ) file.format("%n"); // Identify the object types for which new instances were defined for( Class<? extends Entity> newClass : newClasses ) { for (ObjectType o : ObjectType.getAll()) { if (o.getJavaClass() == newClass) { // Print the first part of the "Define" statement for this object type file.format("Define %s {", o.getInputName()); break; } } // Print the new instances that were defined for (int i = 0; i < Entity.getAll().size(); i++) { Entity ent = Entity.getAll().get(i); if (!ent.testFlag(Entity.FLAG_ADDED)) continue; if (ent.getClass() == newClass) file.format(" %s ", ent.getInputName()); } // Close the define statement file.format("}%n"); } // Identify the entities whose inputs were edited for (int i = 0; i < Entity.getAll().size(); i++) { Entity ent = Entity.getAll().get(i); if (ent.testFlag(Entity.FLAG_EDITED)) { file.format("%n"); writeInputsOnFile_ForEntity( file, ent ); } } // Close the new configuration file file.flush(); file.close(); } /** * Prints the configuration file entries for Entity ent to the FileEntity file. * * @param file - the target configuration file. * @param ent - the entity whose configuration file entries are to be written. */ static void writeInputsOnFile_ForEntity( FileEntity file, Entity ent ) { // Loop through the keywords for this entity for( int j=0; j < ent.getEditableInputs().size(); j++ ) { Input<?> in = ent.getEditableInputs().get( j ); if (!in.isEdited()) continue; // Print the keywords and values String value = in.getValueString(); ArrayList<String> tokens = new ArrayList<String>(); Parser.tokenize(tokens, value); if (!InputAgent.enclosedByBraces(tokens)) file.format("%s %s { %s }%n", ent.getInputName(), in.getKeyword(), value); else file.format("%s %s %s%n", ent.getInputName(), in.getKeyword(), value); } } /** * Returns the relative file path for the specified URI. * <p> * The path can start from either the folder containing the present * configuration file or from the resources folder. * <p> * @param uri - the URI to be relativized. * @return the relative file path. */ static public String getRelativeFilePath(URI uri) { // Relativize the file path against the resources folder String resString = resRoot.toString(); String inputString = uri.toString(); if (inputString.startsWith(resString)) { return String.format("'<res>/%s'", inputString.substring(resString.length())); } // Relativize the file path against the configuration file try { URI configDirURI = InputAgent.getConfigFile().getParentFile().toURI(); return String.format("'%s'", configDirURI.relativize(uri).getPath()); } catch (Exception ex) { return String.format("'%s'", uri.getPath()); } } /** * Loads the default configuration file. */ public static void loadDefault() { // Read the default configuration file InputAgent.readResource("inputs/default.cfg"); // A RecordEdits marker in the default configuration must be ignored InputAgent.setRecordEditsFound(false); // Set the model state to unedited sessionEdited = false; } /** * Split an input (list of strings) down to a single level of nested braces, this may then be called again for * further nesting. * @param input * @return */ public static ArrayList<ArrayList<String>> splitForNestedBraces(List<String> input) { ArrayList<ArrayList<String>> inputs = new ArrayList<ArrayList<String>>(); int braceDepth = 0; ArrayList<String> currentLine = null; for (int i = 0; i < input.size(); i++) { if (currentLine == null) currentLine = new ArrayList<String>(); currentLine.add(input.get(i)); if (input.get(i).equals("{")) { braceDepth++; continue; } if (input.get(i).equals("}")) { braceDepth if (braceDepth == 0) { inputs.add(currentLine); currentLine = null; continue; } } } return inputs; } /** * Expects a StringVector of one of two forms: * 1. { entry entry entry } { entry entry entry } * 2. entry entry entry * If format 1, returns a vector of stringvectors without braces. * if format 2, returns a vector of a stringvector, size1. * @param data * @return */ public static ArrayList<StringVector> splitStringVectorByBraces(StringVector data) { ArrayList<StringVector> newData = new ArrayList<StringVector>(); for (int i=0; i < data.size(); i++) { //skip over opening brace if present if (data.get(i).equals("{") ) continue; StringVector cmd = new StringVector(); //iterate until closing brace, or end of entry for (int j = i; j < data.size(); j++, i++){ if (data.get(j).equals("}")) break; cmd.add(data.get(j)); } //add to vector newData.add(cmd); } return newData; } /** * Converts a file path String to a URI. * <p> * The specified file path can be either relative or absolute. In the case * of a relative file path, a 'context' folder must be specified. A context * of null indicates an absolute file path. * <p> * To avoid bad input accessing an inappropriate file, a 'jail' folder can * be specified. The URI to be returned must include the jail folder for it * to be valid. * <p> * @param context - full file path for the folder that is the reference for relative file paths. * @param filePath - string to be resolved to a URI. * @param jailPrefix - file path to a base folder from which a relative cannot escape. * @return the URI corresponding to the context and filePath. */ public static URI getFileURI(URI context, String filePath, String jailPrefix) throws URISyntaxException { // Replace all backslashes with slashes String path = filePath.replaceAll("\\\\", "/"); int colon = path.indexOf(':'); int openBrace = path.indexOf('<'); int closeBrace = path.indexOf('>'); int firstSlash = path.indexOf('/'); // Add a leading slash if needed to convert from Windows format (e.g. from "C:" to "/C:") if (colon == 1) path = String.format("/%s", path); // 1) File path starts with a tagged folder, using the syntax "<tagName>/" URI ret = null; if (openBrace == 0 && closeBrace != -1 && firstSlash == closeBrace + 1) { String specPath = path.substring(openBrace + 1, closeBrace); // Resources folder in the Jar file if (specPath.equals("res")) { ret = new URI(resRoot.getScheme(), resRoot.getSchemeSpecificPart() + path.substring(closeBrace+2), null).normalize(); } } // 2) Normal file path else { URI pathURI = new URI(null, path, null).normalize(); if (context != null) { if (context.isOpaque()) { // Things are going to get messy in here URI schemeless = new URI(null, context.getSchemeSpecificPart(), null); URI resolved = schemeless.resolve(pathURI).normalize(); // Note: we are using the one argument constructor here because the 'resolved' URI is already encoded // and we do not want to double-encode (and schemes should never need encoding, I hope) ret = new URI(context.getScheme() + ":" + resolved.toString()); } else { ret = context.resolve(pathURI).normalize(); } } else { // We have no context, so append a 'file' scheme if necessary if (pathURI.getScheme() == null) { ret = new URI("file", pathURI.getPath(), null); } else { ret = pathURI; } } } // Check that the file path includes the jail folder if (jailPrefix != null && ret.toString().indexOf(jailPrefix) != 0) { LogBox.format("Failed jail test: %s in jail: %s context: %s\n", ret.toString(), jailPrefix, context.toString()); LogBox.getInstance().setVisible(true); return null; // This resolved URI is not in our jail } return ret; } /** * Determines whether or not a file exists. * <p> * @param filePath - URI for the file to be tested. * @return true if the file exists, false if it does not. */ public static boolean fileExists(URI filePath) { try { InputStream in = filePath.toURL().openStream(); in.close(); return true; } catch (MalformedURLException ex) { return false; } catch (IOException ex) { return false; } } }
package com.jaamsim.input; import java.awt.FileDialog; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import javax.swing.JOptionPane; import com.jaamsim.ui.ExceptionBox; import com.jaamsim.ui.FrameBox; import com.sandwell.JavaSimulation.Entity; import com.sandwell.JavaSimulation.ErrorException; import com.sandwell.JavaSimulation.FileEntity; import com.sandwell.JavaSimulation.Group; import com.sandwell.JavaSimulation.Input; import com.sandwell.JavaSimulation.InputErrorException; import com.sandwell.JavaSimulation.ObjectType; import com.sandwell.JavaSimulation.Palette; import com.sandwell.JavaSimulation.Simulation; import com.sandwell.JavaSimulation.StringVector; import com.sandwell.JavaSimulation.Util; import com.sandwell.JavaSimulation.Vector; import com.sandwell.JavaSimulation3D.DisplayEntity; import com.sandwell.JavaSimulation3D.GUIFrame; public class InputAgent { private static final String addedRecordMarker = "\" *** Added Records ***"; private static int numErrors = 0; private static int numWarnings = 0; private static FileEntity logFile; private static double lastTimeForTrace; private static String configFileName; private static boolean batchRun; private static boolean sessionEdited; private static boolean addedRecordFound; private static boolean endOfFileReached; // notes end of cfg files // ConfigurationFile load and save variables final protected static int SAVE_ONLY = 2; private static final String INP_ERR_DEFINEUSED = "The name: %s has already been used and is a %s"; private static boolean printInputReport; private static String reportDirectory; static { addedRecordFound = false; sessionEdited = false; endOfFileReached = false; batchRun = false; configFileName = null; reportDirectory = ""; lastTimeForTrace = -1.0d; printInputReport = false; } public static void clear() { logFile = null; numErrors = 0; numWarnings = 0; addedRecordFound = false; sessionEdited = false; configFileName = null; reportDirectory = ""; lastTimeForTrace = -1.0d; printInputReport = false; } public static void setPrintInputs(boolean print) { printInputReport = print; } public static String getReportDirectory() { return reportDirectory; } public static void setReportDirectory(String dir) { reportDirectory = Util.getAbsoluteFilePath(dir); if (!reportDirectory.substring(reportDirectory.length() - 1).equals("\\")) reportDirectory = reportDirectory + "\\"; // Create the report directory if it does not already exist // This code should probably be added to FileEntity someday to // create necessary folders on demand. File f = new File(reportDirectory); f.mkdirs(); } public static void setConfigFileName(String name) { configFileName = name; } public static String getConfigFileName() { return configFileName; } public static String getRunName() { String runName; if( InputAgent.getConfigFileName() == null ) { runName = ""; } else { int index = Util.fileShortName( InputAgent.getConfigFileName() ).indexOf( "." ); if( index > -1 ) { runName = Util.fileShortName( InputAgent.getConfigFileName() ).substring( 0, index ); } else { runName = Util.fileShortName( InputAgent.getConfigFileName() ); } } return runName; } public static boolean hasAddedRecords() { return addedRecordFound; } public static boolean isSessionEdited() { return sessionEdited; } public static void setBatch(boolean batch) { batchRun = batch; } public static boolean getBatch() { return batchRun; } /** * returns true if the first and last tokens are matched braces **/ public static boolean enclosedByBraces(ArrayList<String> tokens) { if(tokens.size() < 2 || tokens.indexOf("{") < 0) // no braces return false; int level =1; int i = 1; for(String each: tokens.subList(1, tokens.size())) { if(each.equals("{")) { level++; } if(each.equals("}")) { level // Matching close brace found if(level == 0) break; } i++; } if(level == 0 && i == tokens.size()-1) { return true; } return false; } private static int getBraceDepth(ArrayList<String> tokens, int startingBraceDepth, int startingIndex) { int braceDepth = startingBraceDepth; for (int i = startingIndex; i < tokens.size(); i++) { String token = tokens.get(i); if (token.equals("{")) braceDepth++; if (token.equals("}")) braceDepth if (braceDepth < 0) { InputAgent.logBadInput(tokens, "Extra closing braces found"); tokens.clear(); } if (braceDepth > 2) { InputAgent.logBadInput(tokens, "Maximum brace depth (2) exceeded"); tokens.clear(); } } return braceDepth; } private static URI pwdPath; private static URI pwdRoot; private static URI resRoot; private static URI resPath; private static final String res = "/resources/inputs/"; static { // Walk up the parent list until we find a parentless entry, call that // the 'root' File f = new File(System.getProperty("user.dir")); File par = f; while (true) { File t = par.getParentFile(); if (t == null) { pwdRoot = par.toURI(); break; } par = t; } pwdPath = pwdRoot.relativize(f.toURI()); try { // locate the resource folder, and create resRoot = InputAgent.class.getResource(res).toURI(); } catch (URISyntaxException e) {} resPath = URI.create(""); } public static final void readResource(String res) { if (res == null) return; readStream(resRoot, resPath, res); } public static final boolean readStream(URI root, URI path, String file) { URI resolved = path.resolve(file); resolved.normalize(); if (resolved.getRawPath().contains("../")) { InputAgent.logWarning("Unable to resolve path %s%s - %s", root.toString(), path.toString(), file); return false; } URL t = null; try { t = new URI(root.toString() + resolved.toString()).toURL(); } catch (MalformedURLException e) {} catch (URISyntaxException e) {} if (t == null) { InputAgent.logWarning("Unable to resolve path %s%s - %s", root.toString(), path.toString(), file); return false; } readURL(t); return true; } public static void readURL(URL url) { if (url == null) return; BufferedReader buf = null; try { InputStream in = url.openStream(); buf = new BufferedReader(new InputStreamReader(in)); } catch (IOException e) { InputAgent.logWarning("Could not read from %s", url.toString()); return; } try { ArrayList<String> record = new ArrayList<String>(); int braceDepth = 0; while (true) { String line = buf.readLine(); // end of file, stop reading if (line == null) break; if ( line.trim().equalsIgnoreCase( addedRecordMarker ) ) { addedRecordFound = true; } int previousRecordSize = record.size(); Parser.tokenize(record, line); braceDepth = InputAgent.getBraceDepth(record, braceDepth, previousRecordSize); if( braceDepth != 0 ) continue; Parser.removeComments(record); InputAgent.processRecord(url, record); record.clear(); } // Leftover Input at end of file if (record.size() > 0) InputAgent.logBadInput(record, "Leftover input at end of file"); buf.close(); } catch (IOException e) { // Make best effort to ensure it closes try { buf.close(); } catch (IOException e2) {} } } private static void processRecord(URL url, ArrayList<String> record) { //InputAgent.echoInputRecord(record); if (record.size() == 0) return; if (record.get(0).equalsIgnoreCase("INCLUDE")) { InputAgent.processIncludeRecord(url, record); return; } if (record.get(0).equalsIgnoreCase("DEFINE")) { InputAgent.processDefineRecord(record); return; } // Otherwise assume it is a Keyword record InputAgent.processKeywordRecord(record); } private static void processIncludeRecord(URL baseURL, ArrayList<String> record) { if (record.size() != 2) { InputAgent.logError("Bad Include record, should be: Include <File>"); return; } // Ensure the include filename is well formed URL finalURL = null; try { URI incFile = new URI(record.get(1).replaceAll("\\\\", "/")); // Construct a base file in case this URI is relative and split at ! to // account for a jar:file:<jarfilename>!<internalfilename> URL int bangIndex = baseURL.toString().lastIndexOf("!") + 1; String prefix = baseURL.toString().substring(0, bangIndex); String folder = baseURL.toString().substring(bangIndex); URI folderURI = new URI(folder).resolve(incFile); // Remove all remaining relative path directives ../ String noRelative = folderURI.toString().replaceAll("\\.\\./", ""); finalURL = new URL(prefix + noRelative); } catch (NullPointerException e) {} catch (URISyntaxException e) {} catch (MalformedURLException e) {} finally { if (finalURL == null) { InputAgent.logError("Unable to parse filename: %s", record.get(1)); return; } } InputAgent.readURL(finalURL); } private static void processDefineRecord(ArrayList<String> record) { if (record.size() < 5 || !record.get(2).equals("{") || !record.get(record.size() - 1).equals("}")) { InputAgent.logError("Bad Define record, should be: Define <Type> { <names>... }"); return; } Class<? extends Entity> proto = null; try { if( record.get( 1 ).equalsIgnoreCase( "Palette" ) ) { proto = Palette.class; } else if( record.get( 1 ).equalsIgnoreCase( "ObjectType" ) ) { proto = ObjectType.class; } else { proto = Input.parseEntityType(record.get(1)); } } catch (InputErrorException e) { InputAgent.logError("%s", e.getMessage()); return; } // Loop over all the new Entity names for (int i = 3; i < record.size() - 1; i++) { InputAgent.defineEntity(proto, record.get(i), addedRecordFound); } } /** * Like defineEntity(), but will generate a unique name if a name collision exists * @param proto * @param key * @param addedEntity * @return */ public static <T extends Entity> T defineEntityWithUniqueName(Class<T> proto, String key, boolean addedEntity) { // Has the provided name been used already? if (Entity.getNamedEntity(key) == null) { return defineEntity(proto, key, addedEntity); } // Try the provided name plus "-1", "-2", etc. until an unused name is found int entityNum = 1; while(true) { String name = String.format("%s-%d", key, entityNum); if (Entity.getNamedEntity(name) == null) { return defineEntity(proto, name, addedEntity); } entityNum++; } } /** * if addedEntity is true then this is an entity defined * by user interaction or after added record flag is found; * otherwise, it is from an input file define statement * before the model is configured * @param proto * @param key * @param addedEntity */ public static <T extends Entity> T defineEntity(Class<T> proto, String key, boolean addedEntity) { Entity existingEnt = Input.tryParseEntity(key, Entity.class); if (existingEnt != null) { InputAgent.logError(INP_ERR_DEFINEUSED, key, existingEnt.getClass().getSimpleName()); return null; } T ent = null; try { ent = proto.newInstance(); if (addedEntity) { ent.setFlag(Entity.FLAG_ADDED); sessionEdited = true; } } catch (InstantiationException e) {} catch (IllegalAccessException e) {} finally { if (ent == null) { InputAgent.logError("Could not create new Entity: %s", key); return null; } } ent.setInputName(key); return ent; } private static void processKeywordRecord(ArrayList<String> record) { Entity ent = Input.tryParseEntity(record.get(0), Entity.class); if (ent == null) { InputAgent.logError("Could not find Entity: %s", record.get(0)); return; } ArrayList<ArrayList<String>> keywords = InputAgent.splitKeywords(record); for (ArrayList<String> keyword : keywords) { if (keyword.size() < 3 || !keyword.get(1).equals("{") || !keyword.get(keyword.size() - 1).equals("}")) { InputAgent.logError("Keyword not valid, should be <keyword> { <args> }"); continue; } String key = keyword.get(0); StringVector args = new StringVector(keyword.size() - 3); for (int i = 2; i < keyword.size() - 1; i++) { args.add(keyword.get(i)); } try { InputAgent.processKeyword(ent, args, key); } catch (Throwable e) { InputAgent.logError("Exception thrown from Entity: %s for keyword:%s - %s", ent.getInputName(), key, e.getMessage()); } } } private static ArrayList<ArrayList<String>> splitKeywords(ArrayList<String> input) { ArrayList<ArrayList<String>> inputs = new ArrayList<ArrayList<String>>(); int braceDepth = 0; ArrayList<String> currentLine = null; for (int i = 1; i < input.size(); i++) { if (currentLine == null) currentLine = new ArrayList<String>( input.size() ); currentLine.add(input.get(i)); if (input.get(i).equals("{")) { braceDepth++; continue; } if (input.get(i).equals("}")) { braceDepth if (braceDepth == 0) { inputs.add(currentLine); currentLine = null; continue; } } } return inputs; } public static void doError(Throwable e) { if (!batchRun) return; System.out.println("An error occurred in the simulation environment. Please check inputs for an error:"); System.out.println(e); GUIFrame.shutdown(1); } // Load the run file public static void loadConfigurationFile( String fileName) { String inputTraceFileName = InputAgent.getRunName() + ".log"; // Initializing the tracing for the model try { System.out.println( "Creating trace file" ); // Set and open the input trace file name logFile = new FileEntity( inputTraceFileName, FileEntity.FILE_WRITE, false ); } catch( Exception e ) { throw new ErrorException( "Could not create trace file" ); } InputAgent.loadConfigurationFile(fileName, true); // At this point configuration file is loaded // The session is not considered to be edited after loading a configuration file sessionEdited = false; // Save and close the input trace file if (logFile != null) { if (InputAgent.numWarnings == 0 && InputAgent.numErrors == 0) { logFile.close(); logFile.delete(); logFile = new FileEntity( inputTraceFileName, FileEntity.FILE_WRITE, false ); } } // Check for found errors if( InputAgent.numErrors > 0 ) throw new InputErrorException("%d input errors found, check log file", InputAgent.numErrors); if (printInputReport) InputAgent.printInputFileKeywords(); } /** * * @param fileName * @param firstTime ( true => this is the main config file (run file); false => this is an included file within main config file or another included file ) */ public static void loadConfigurationFile( String fileName, boolean firstTime ) { //System.out.println( "load configuration file " + fileName ); FileEntity file; Vector record; // If the file does not exist, write an error and exit if( !FileEntity.fileExists( fileName ) ) { System.out.println( (("Error -- The input file " + fileName) + " was not found ") ); GUIFrame.shutdown(0); } // Open the file file = new FileEntity( fileName, FileEntity.FILE_READ, false ); String mainRootDirectory = null; String originalJarFileRootDirectory = null; if( firstTime ) { // Store the directory of the first input file file.setRootDirectory(); } else { // Save the directory of the first file mainRootDirectory = FileEntity.getRootDirectory(); // Switch to the directory of the current input file file.setRootDirectory(); // Save the directory of the first file within the jar file originalJarFileRootDirectory = FileEntity.getJarFileRootDirectory(); } // Initialize the input file file.toStart(); GUIFrame.instance().setProgressText(file.getFileName()); // For each line in the file while( true ) { // Read the next line to record record = getNextParsedRecord( file ); // System.out.println( record.toString() ); // Determine the amount of file read and update the progress gauge int per = (int)(((double)file.getNumRead()) / ((double)file.getLength()) * 100.0); GUIFrame.instance().setProgress( per ); // When end-of-file is reached, record.size() == 0 if( endOfFileReached ) { break; } // Process this line if it is not empty if ( record.size() > 0 ) { // If there is an included file, LoadConfigurationFile is run for that (This is recursive) InputAgent.readRecord(record, file); } } // Reset the progress bar to zero and remove its label GUIFrame.instance().setProgressText(null); GUIFrame.instance().setProgress(0); // Close the file file.close(); // Restore to the directory of the first input file if ( ! firstTime ) { FileEntity.setRootDirectory( mainRootDirectory ); FileEntity.setJarFileRootDirectory( originalJarFileRootDirectory ); } } /** * Reads record, either as a default, define statement, include, or keyword * @param record * @param file */ private static void readRecord(Vector record, FileEntity file) { if(record.size() < 2){ InputAgent.logError("Invalid input line - missing keyword or parameter"); return; } try { if( "DEFINE".equalsIgnoreCase( (String)record.get( 0 ) ) ) { ArrayList<String> tempCopy = new ArrayList<String>(record.size()); for (int i = 0; i < record.size(); i++) tempCopy.add((String)record.get(i)); InputAgent.processDefineRecord(tempCopy); } // Process other files else if( "INCLUDE".equalsIgnoreCase( (String)record.get( 0 ) ) ) { if( record.size() == 2 ) { if( FileEntity.fileExists( (String)record.get( 1 ) ) ) { // Load the included file and process its records first InputAgent.loadConfigurationFile( (String)record.get( 1 ), false ); GUIFrame.instance().setProgressText(file.getFileName()); } else { InputAgent.logError("File not found: %s", (String)record.get(1)); } } else { InputAgent.logError("There must be exactly two entries in an Include record"); } } // is a keyword else { InputAgent.processData(record); } } catch( InputErrorException iee ) { InputAgent.logError( iee.getMessage() ); } } // Read the next line of the file protected static Vector getNextParsedRecord(FileEntity file) { Vector record = new Vector(); int noOfUnclosedBraces = 0; do { Vector nextLine = file.readAndParseRecord(); InputAgent.echoInput(nextLine); if (nextLine.size() == 0) { endOfFileReached = true; } else { endOfFileReached = false; } // Set flag if input records added through the EditBox interface are found if ( !(endOfFileReached) && ( ((String) nextLine.get( 0 )).equalsIgnoreCase( addedRecordMarker ) ) ) { addedRecordFound = true; } Util.discardComment( nextLine ); // Count braces and allow input with a missing space following an opening brace and/or a missing space preceding a closing brace for (int i = 0; i < nextLine.size(); i++) { String checkRecord = (String)nextLine.get( i ); Vector parsedString = new Vector( nextLine.size() ); // Check for braces for (int j=0; j<checkRecord.length(); j++) { // '(' & ')' are not allowed in the input file if( checkRecord.charAt(j) == '(' || checkRecord.charAt(j) == ')' ) { throw new ErrorException( "\n\"" + checkRecord.charAt(j) + "\"" + " is not allowed in the input file: \n" + nextLine + "\n" + FileEntity.getRootDirectory() + file.getFileName() ); } if (checkRecord.charAt(j) == '{') { noOfUnclosedBraces++; parsedString.add("{"); } else if (checkRecord.charAt(j) == '}') { noOfUnclosedBraces parsedString.add("}"); } else { // no brace is found, assume it is a whole word until the next brace StringBuffer stringDump = new StringBuffer( checkRecord.length() ); // iterate through for ( int k = j; k<checkRecord.length(); k++ ) { // if a brace is found, end checking this word if ( checkRecord.charAt(k) == '{' || checkRecord.charAt(k) == '}' ) { k = checkRecord.length(); } // otherwise, make the word else { stringDump.append( checkRecord.charAt(k) ); } } j += stringDump.length() - 1; parsedString.add(stringDump.toString()); } } // Add brackets as separate entries if (parsedString.size() > 1 ) { nextLine.remove( i ); nextLine.addAll( i , parsedString ); i = i + parsedString.size() - 1; } } record.addAll(nextLine); } while ( ( noOfUnclosedBraces != 0 ) && ( !endOfFileReached ) ); if( noOfUnclosedBraces != 0 ) { InputAgent.logError("Missing closing brace"); } return record; } public static final void apply(Entity ent, Input<?> in, StringVector data) { in.parse(data); ent.updateForInput(in); } public static final void apply(Entity ent, StringVector data, String keyword) throws InputErrorException { Input<?> in = ent.getInput(keyword); if (in != null) { InputAgent.apply(ent, in, data); FrameBox.valueUpdate(); } else { ent.readData_ForKeyword(data, keyword); FrameBox.valueUpdate(); } } private static void processKeyword( Entity entity, StringVector recordCmd, String keyword) { if (keyword == null) throw new InputErrorException("The keyword is null."); if (entity.testFlag(Entity.FLAG_LOCKED)) throw new InputErrorException("Entity: %s is locked and cannot be modified", entity.getName()); try { Input<?> input = entity.getInput( keyword ); if( input != null && input.isAppendable() ) { ArrayList<StringVector> splitData = Util.splitStringVectorByBraces(recordCmd); for ( int i = 0; i < splitData.size(); i++ ) { InputAgent.apply(entity, input, splitData.get(i)); } } else { InputAgent.apply(entity, recordCmd, keyword); } // Create a list of entities to update in the edit table ArrayList<Entity> updateList = null; if (entity instanceof Group && input == null) { updateList = ((Group)entity).getList(); } else { updateList = new ArrayList<Entity>(1); updateList.add(entity); } // Store the keyword data for use in the edit table for( int i = 0; i < updateList.size(); i++ ) { Entity ent = updateList.get( i ); Input<?> in = ent.getInput(keyword); if (in != null) { InputAgent.updateInput(ent, in, recordCmd); } // The keyword is not on the editable keyword list else { InputAgent.logWarning("Keyword %s is obsolete. Please replace the Keyword. Refer to the manual for more detail.", keyword); } } } catch ( InputErrorException e ) { InputAgent.logError("Entity: %s Keyword: %s - %s", entity.getName(), keyword, e.getMessage()); throw e; } } protected static class KeywordValuePair { public String keyword; public StringVector value; public KeywordValuePair( int size ) { keyword = null; value = new StringVector( size ); } } public static void processData(Entity ent, Vector rec) { if( rec.get( 1 ).toString().trim().equals( "{" ) ) { InputAgent.logError("A keyword expected after: %s", ent.getName()); } ArrayList<KeywordValuePair> multiCmds = InputAgent.splitMultipleCommands(rec); // Process each command for( int i = 0; i < multiCmds.size(); i++ ) { KeywordValuePair cmd = multiCmds.get(i); // Process the record InputAgent.processKeyword(ent, cmd.value, cmd.keyword); } return; } /** * process's input data from record for use as a keyword. * format of record: <obj-name> <keyword> <data> <keyword> <data> * braces are included */ public static void processData( Vector record ) { String item1 = ((String)record.get( 0 )).trim(); // Checks on Entity: Entity obj = Input.tryParseEntity(item1, Entity.class); if (obj == null) { InputAgent.logError("Object not found: %s", item1); return; } // Entity exists with name <entityName> or name <region>/<entityName> InputAgent.processData(obj, record); } /** * returns a vector of vectors * each vector will be of form <obj-name> <kwd> <data> <data> * no braces are returned */ private static ArrayList<KeywordValuePair> splitMultipleCommands( Vector record ) { // SUPPORTED SYNTAX: // <obj-name> <kwd> { <par> } // <obj-name> <kwd> { <par> <par> ... } // <obj-name> <kwd> { <par> <par> ... } <kwd> { <par> <par> ... } ... // <obj-name> <kwd> <par> <kwd> { <par> <par> ... } ... ArrayList<KeywordValuePair> multiCmds = new ArrayList<KeywordValuePair>(); int noOfUnclosedBraces = 0; // Loop through the keywords and assemble new commands for( int i = 1; i < record.size(); ) { // Enter the class, object, and keyword in the new command KeywordValuePair cmd = new KeywordValuePair( record.size() ); // Keyword changes as loop proceeds cmd.keyword = ((String)record.get(i)); i++; // For a command of the new form "<obj-name> <file-name>", record // will be empty here. if( i < record.size() ) { // If there is an opening brace, then the keyword has a list of // parameters String openingBrace = (String)record.get( i ); if( openingBrace.equals("{") ) { noOfUnclosedBraces ++ ; i++; // move past the opening brace { // Iterate through record while( (i < record.size()) && ( noOfUnclosedBraces > 0 ) ) { if ( record.get(i).equals("{") ) noOfUnclosedBraces ++ ; else if (record.get(i).equals("}")) noOfUnclosedBraces cmd.value.add((String)record.get(i)); i++; } if( ( record.size() == i ) && ( noOfUnclosedBraces != 0) ) { // corresponding "}" is missing InputAgent.logError("Closing brace } is missing."); return multiCmds; } // Last item added was the corresponding closing brace else { cmd.value.remove(cmd.value.size()-1); // throw out the closing brace } multiCmds.add( cmd ); } } // If there is no brace, then the keyword must have a single // parameter. else { cmd.value.add((String)record.get(i)); i++; multiCmds.add( cmd ); } } // Record contains no other items else { multiCmds.add( cmd ); } } return multiCmds; } private static class ConfigFileFilter implements FilenameFilter { @Override public boolean accept(File inFile, String fileName) { return fileName.endsWith("[cC][fF][gG]"); } } public static void load(GUIFrame gui) { System.out.println("Loading..."); FileDialog chooser = new FileDialog(gui, "Load Configuration File", FileDialog.LOAD); chooser.setFilenameFilter(new ConfigFileFilter()); String chosenFileName = chooseFile(chooser, FileDialog.LOAD); if (chosenFileName != null) { //dispose(); setLoadFile(gui, chosenFileName); } else { //dispose(); } } public static void save(GUIFrame gui) { System.out.println("Saving..."); if( InputAgent.getConfigFileName() != null ) { setSaveFile(gui, FileEntity.getRootDirectory() + System.getProperty( "file.separator" ) + InputAgent.getConfigFileName(), SAVE_ONLY ); } else { saveAs( gui ); } } public static void saveAs(GUIFrame gui) { System.out.println("Save As..."); FileDialog chooser = new FileDialog(gui, "Save Configuration File As", FileDialog.SAVE); chooser.setFilenameFilter(new ConfigFileFilter()); String chosenFileName = chooseFile(chooser, FileDialog.SAVE); if ( chosenFileName != null ) { //dispose(); setSaveFile(gui, chosenFileName, FileDialog.SAVE ); } else { //dispose(); } } /** * Opens browser to choose file. returns a boolean if a file was picked, false if canceled or closed. */ private static String chooseFile(FileDialog chooser, int saveOrLoadType) { // filter if (saveOrLoadType == FileDialog.SAVE) { chooser.setFile( InputAgent.getConfigFileName() ); } else { chooser.setFile( "*.cfg" ); } // display browser //this.show(); chooser.setVisible( true ); // if a file was picked, set entryarea to be this file if( chooser.getFile() != null ) { //chooser should not set root directory //FileEntity.setRootDirectory( chooser.getDirectory() ); String chosenFileName = chooser.getDirectory() + chooser.getFile(); return chosenFileName.trim(); } else { return null; } } public static void configure(GUIFrame gui, String configFileName) { try { gui.clear(); Simulation.setSimState(Simulation.SIM_STATE_UNCONFIGURED); InputAgent.setConfigFileName(configFileName); gui.updateForSimulationState(); try { InputAgent.loadConfigurationFile(configFileName); } catch( InputErrorException iee ) { if (!batchRun) ExceptionBox.instance().setError(iee); else System.out.println( iee.getMessage() ); } // store the present state Simulation.setSimState(Simulation.SIM_STATE_CONFIGURED); System.out.println("Configuration File Loaded"); // show the present state in the user interface gui.setTitle( Simulation.getModelName() + " - " + InputAgent.getRunName() ); gui.updateForSimulationState(); } catch( Throwable t ) { ExceptionBox.instance().setError(t); } } /** * Loads configuration file , calls GraphicSimulation.configure() method */ private static void setLoadFile(final GUIFrame gui, String fileName) { final String chosenFileName = fileName; new Thread(new Runnable() { @Override public void run() { File temp = new File(chosenFileName); if( temp.isAbsolute() ) { FileEntity.setRootDirectory( temp.getParentFile() ); InputAgent.configure(gui, temp.getName()); } else { InputAgent.configure(gui, chosenFileName); } GUIFrame.displayWindows(true); FrameBox.valueUpdate(); } }).start(); } /** * saves the cfg/pos file. checks for 'save' and 'save as', recursively goes to 'save as' if 'save' is not possible. * updates runname and filename of file. * if editbox is open and unaccepted, accepts changes. */ private static void setSaveFile(GUIFrame gui, String fileName, int saveOrLoadType) { String configFilePath = FileEntity.getRootDirectory() + System.getProperty( "file.separator" ) + InputAgent.getConfigFileName(); // check ending string of filename, force cfg onto end if needed if (!(fileName.endsWith(".cfg"))) { fileName = fileName.concat(".cfg"); } File temp = new File(fileName); //System.out.println("fileName is " + fileName); // If the original configuration file is the same as the file to save, and there were no added records, // then do not save the file because it would be recursive, i.e. contain "include <fileName>" if( configFilePath.equalsIgnoreCase( fileName ) ) { if( !InputAgent.hasAddedRecords() ) { if( saveOrLoadType == FileDialog.SAVE) { // recursive -- if can't overwrite base file, 'save as' // Ask if appending to base configuration is ok int appendOption = JOptionPane.showConfirmDialog( null, "Cannot overwrite base configuration file. Do you wish to append changes?", "Confirm Append", JOptionPane.YES_OPTION, JOptionPane.WARNING_MESSAGE ); // Perform append only if yes if (appendOption == JOptionPane.YES_OPTION) { FileEntity configFile = new FileEntity( fileName, FileEntity.FILE_WRITE, true ); configFile.write( "\n" + addedRecordMarker ); addedRecordFound = true; } else { InputAgent.saveAs(gui); return; } } else { InputAgent.saveAs(gui); return; } } else if ( saveOrLoadType == SAVE_ONLY) { System.out.println("Saving..."); } } // set root directory FileEntity.setRootDirectory( temp.getParentFile() ); //saveFile = new FileEntity( fileName, FileEntity.FILE_WRITE, false ); //simulation.printNewConfigurationFileOn( saveFile ); InputAgent.printNewConfigurationFileWithName( fileName ); sessionEdited = false; //TODOalan set directory of model.. ? InputAgent.setConfigFileName(Util.fileShortName(fileName)); // Set the title bar to match the new run name gui.setTitle( Simulation.getModelName() + " - " + InputAgent.getRunName() ); // close the window //dispose(); } /* * write input file keywords and values * * input file format: * Define Group { <Group names> } * Define <Object> { <Object names> } * * <Object name> <Keyword> { < values > } * */ public static void printInputFileKeywords() { Entity ent; // Create report file for the inputs FileEntity inputReportFile; String inputReportFileName = InputAgent.getReportDirectory() + InputAgent.getRunName() + ".inp"; if( FileEntity.fileExists( inputReportFileName ) ) { inputReportFile = new FileEntity( inputReportFileName, FileEntity.FILE_WRITE, false ); inputReportFile.flush(); } else { inputReportFile = new FileEntity( inputReportFileName, FileEntity.FILE_WRITE, false ); } // Loop through the entity classes boolean hasinput = false; // for formating output int count = 0; // for formating output String entityName = null; // to take out Region name // print Define statements for( ObjectType type : ObjectType.getAll() ) { Class<? extends Entity> each = type.getJavaClass(); // Loop through the instances for this entity class ArrayList<? extends Entity> cloneList = Entity.getInstancesOf(each); count = 0; for( int j=0; j < cloneList.size(); j++ ) { hasinput = false; ent = cloneList.get(j); for( Input<?> in : ent.getEditableInputs() ){ // If the keyword has been used, then add a record to the report if ( in.getValueString().length() != 0 ){ hasinput = true; count++; break; } } if ( each.getSimpleName().equalsIgnoreCase("Region") && ! hasinput ) { count++; hasinput = true; } if( hasinput ){ entityName = cloneList.get(j).getInputName(); if ( (count-1)%5 == 0) { inputReportFile.putString( "Define" ); inputReportFile.putTab(); inputReportFile.putString(type.getInputName()); inputReportFile.putTab(); inputReportFile.putString( "{ " + entityName ); inputReportFile.putTab(); } else if ( (count-1)%5 == 4 ){ inputReportFile.putString( entityName + " }" ); inputReportFile.newLine(); } else { inputReportFile.putString( entityName ); inputReportFile.putTab(); } } } if ( cloneList.size() > 0 ){ if ( count%5 != 0 ){ inputReportFile.putString( " }" ); inputReportFile.newLine(); } inputReportFile.newLine(); } } for( ObjectType type : ObjectType.getAll() ) { Class<? extends Entity> each = type.getJavaClass(); // Get the list of instances for this entity class // sort the list alphabetically ArrayList<? extends Entity> cloneList = Entity.getInstancesOf(each); // Print the entity class name to the report (in the form of a comment) if( cloneList.size() > 0 ) { inputReportFile.putString( "\" " + each.getSimpleName() + " \""); inputReportFile.newLine(); inputReportFile.newLine(); // blank line below the class name heading } Collections.sort(cloneList, new Comparator<Entity>() { @Override public int compare(Entity a, Entity b) { return a.getInputName().compareTo(b.getInputName()); } }); // Loop through the instances for this entity class for( int j=0; j < cloneList.size(); j++ ) { // Make sure the clone is an instance of the class (and not an instance of a subclass) if (cloneList.get(j).getClass() == each) { ent = cloneList.get(j); entityName = cloneList.get(j).getInputName(); hasinput = false; // Loop through the editable keywords for this instance for( Input<?> in : ent.getEditableInputs() ) { // If the keyword has been used, then add a record to the report if ( in.getValueString().length() != 0 ) { if ( ! in.getCategory().contains("Graphics") ) { hasinput = true; inputReportFile.putTab(); inputReportFile.putString( entityName ); inputReportFile.putTab(); inputReportFile.putString( in.getKeyword() ); inputReportFile.putTab(); if( in.getValueString().lastIndexOf( "{" ) > 10 ) { String[] item1Array; item1Array = in.getValueString().trim().split( " }" ); inputReportFile.putString( "{ " + item1Array[0] + " }" ); for (int l = 1; l < (item1Array.length); l++ ){ inputReportFile.newLine(); inputReportFile.putTabs( 5 ); inputReportFile.putString( item1Array[l] + " } " ); } inputReportFile.putString( " }" ); } else { inputReportFile.putString( "{ " + in.getValueString() + " }" ); } inputReportFile.newLine(); } } } // Put a blank line after each instance if ( hasinput ) { inputReportFile.newLine(); } } } } // Close out the report inputReportFile.flush(); inputReportFile.close(); } public static void closeLogFile() { if (logFile == null) return; logFile.flush(); logFile.close(); if (numErrors ==0 && numWarnings == 0) { logFile.delete(); } logFile = null; } private static final String errPrefix = "*** ERROR *** %s%n"; private static final String wrnPrefix = "***WARNING*** %s%n"; public static int numErrors() { return numErrors; } public static int numWarnings() { return numWarnings; } private static void echoInputRecord(ArrayList<String> tokens) { StringBuilder line = new StringBuilder(); for (int i = 0; i < tokens.size(); i++) { line.append(" ").append(tokens.get(i)); if (tokens.get(i).startsWith("\"")) { InputAgent.logMessage("%s", line.toString()); line.setLength(0); } } // Leftover input if (line.length() > 0) InputAgent.logMessage("%s", line.toString()); } private static void logBadInput(ArrayList<String> tokens, String msg) { InputAgent.echoInputRecord(tokens); InputAgent.logError("%s", msg); } public static void logMessage(String fmt, Object... args) { String msg = String.format(fmt, args); System.out.println(msg); if (logFile == null) return; logFile.write(msg); logFile.newLine(); logFile.flush(); } public static void trace(int indent, Entity ent, String meth, String... text) { // Create an indent string to space the lines StringBuilder ind = new StringBuilder(""); for (int i = 0; i < indent; i++) ind.append(" "); String spacer = ind.toString(); // Print a TIME header every time time has advanced double traceTime = ent.getCurrentTime(); if (lastTimeForTrace != traceTime) { System.out.format(" \nTIME = %.5f\n", traceTime); lastTimeForTrace = traceTime; } // Output the traces line(s) System.out.format("%s%s %s\n", spacer, ent.getName(), meth); for (String line : text) { System.out.format("%s%s\n", spacer, line); } System.out.flush(); } /* * Log the input to a file, but don't echo it out as well. */ public static void echoInput(Vector line) { // if there is no log file currently, output nothing if (logFile == null) return; StringBuilder msg = new StringBuilder(); for (Object each : line) { msg.append(" "); msg.append(each); } logFile.write(msg.toString()); logFile.newLine(); logFile.flush(); } public static void logWarning(String fmt, Object... args) { numWarnings++; String msg = String.format(fmt, args); InputAgent.logMessage(wrnPrefix, msg); } public static void logError(String fmt, Object... args) { numErrors++; String msg = String.format(fmt, args); InputAgent.logMessage(errPrefix, msg); } public static void processEntity_Keyword_Value(Entity ent, Input<?> in, String value){ ArrayList<String> tokens = new ArrayList<String>(); Parser.tokenize(tokens, value); if(! InputAgent.enclosedByBraces(tokens) ) { tokens.add(0, "{"); tokens.add("}"); } Parser.removeComments(tokens); tokens.add(0, ent.getInputName()); tokens.add(1, in.getKeyword()); Vector data = new Vector(tokens.size()); data.addAll(tokens); InputAgent.processData(ent, data); } public static void processEntity_Keyword_Value(Entity ent, String keyword, String value){ Input<?> in = ent.getInput( keyword ); processEntity_Keyword_Value(ent, in, value); } public static void updateInput(Entity ent, Input<?> in, StringVector data) { if(ent.testFlag(Entity.FLAG_GENERATED)) return; StringBuilder out = new StringBuilder(data.size() * 6); for (int i = 0; i < data.size(); i++) { out.append(data.get(i)); if( i < data.size() - 1 ) out.append(" "); } String str = out.toString(); // Takes care of old format, displaying as new format -- appending onto end of record. if( in.isAppendable() && ! data.get(0).equals("{") ) { str = String.format("%s { %s }", in.getValueString(), str ); } if(in.isEdited()) { ent.setFlag(Entity.FLAG_EDITED); sessionEdited = true; } in.setValueString(str); } /** * Print out a configuration file with all the edited changes attached */ public static void printNewConfigurationFileWithName( String fileName ) { ArrayList<String> preAddedRecordLines = new ArrayList<String>(); String configFilePath = FileEntity.getRootDirectory() + System.getProperty( "file.separator" ) + InputAgent.getConfigFileName(); if( InputAgent.hasAddedRecords() && FileEntity.fileExists( configFilePath ) ) { // Store the original configuration file lines up to added records try { BufferedReader in = new BufferedReader( new FileReader( configFilePath ) ); String line; while ( ( line = in.readLine() ) != null ) { if ( line.startsWith( addedRecordMarker ) ) { break; } else { preAddedRecordLines.add( line ); } } in.close(); } catch ( Exception e ) { throw new ErrorException( e ); } } FileEntity file = new FileEntity( fileName, FileEntity.FILE_WRITE, false ); // include the original configuration file if (!InputAgent.hasAddedRecords()) { file.format( "\" File: %s\n\n", file.getFileName() ); file.format( "include %s\n\n", InputAgent.getConfigFileName() ); } else { for( int i=0; i < preAddedRecordLines.size(); i++ ) { String line = preAddedRecordLines.get( i ); if( line.startsWith( "\" File: " ) ) { file.format( "\" File: %s\n", file.getFileName() ); } else { file.format("%s\n", line); } } } file.format("%s\n", addedRecordMarker); addedRecordFound = true; // Print changes to simulation writeInputsOnFile_ForEntity( file, DisplayEntity.simulation ); file.format("\n"); // Determine all the new classes that were created ArrayList<Class<? extends Entity>> newClasses = new ArrayList<Class<? extends Entity>>(); for (int i = 0; i < Entity.getAll().size(); i++) { Entity ent = Entity.getAll().get(i); if (!ent.testFlag(Entity.FLAG_ADDED)) continue; if (!newClasses.contains(ent.getClass())) newClasses.add(ent.getClass()); } // Print the define statements for each new class for( Class<? extends Entity> newClass : newClasses ) { for (ObjectType o : ObjectType.getAll()) { if (o.getJavaClass() == newClass) { file.putString( "Define " + o.getInputName()+" {" ); break; } } for (int i = 0; i < Entity.getAll().size(); i++) { Entity ent = Entity.getAll().get(i); if (!ent.testFlag(Entity.FLAG_ADDED)) continue; if (ent.getClass() == newClass) file.format(" %s ", ent.getInputName()); } file.format("}\n"); } // List all the changes that were saved for each edited entity for (int i = 0; i < Entity.getAll().size(); i++) { Entity ent = Entity.getAll().get(i); if( ent == DisplayEntity.simulation ) continue; if (!ent.testFlag(Entity.FLAG_EDITED)) continue; writeInputsOnFile_ForEntity( file, ent ); } file.flush(); file.close(); } static void writeInputsOnFile_ForEntity( FileEntity file, Entity ent ) { // Write new configuration file for non-appendable keywords file.format("\n"); for( int j=0; j < ent.getEditableInputs().size(); j++ ) { Input<?> in = ent.getEditableInputs().get( j ); if( in.isEdited() ) { // Each line starts with the entity name followed by changed keyword file.format("%s %s ", ent.getInputName(), in.getKeyword()); String value = in.getValueString(); ArrayList<String> tokens = new ArrayList<String>(); Parser.tokenize(tokens, value); if(! InputAgent.enclosedByBraces(tokens) ) { value = String.format("{ %s }", value); } file.format("%s\n", value); } } } public static void loadDefault() { // Read the default configuration file InputAgent.readResource("default.cfg"); sessionEdited = false; } /** * Split an input (list of strings) down to a single level of nested braces, this may then be called again for * further nesting. * @param input * @return */ public static ArrayList<ArrayList<String>> splitForNestedBraces(List<String> input) { ArrayList<ArrayList<String>> inputs = new ArrayList<ArrayList<String>>(); int braceDepth = 0; ArrayList<String> currentLine = null; for (int i = 0; i < input.size(); i++) { if (currentLine == null) currentLine = new ArrayList<String>(); currentLine.add(input.get(i)); if (input.get(i).equals("{")) { braceDepth++; continue; } if (input.get(i).equals("}")) { braceDepth if (braceDepth == 0) { inputs.add(currentLine); currentLine = null; continue; } } } return inputs; } }
package com.microsoft.rest; import com.fasterxml.jackson.annotation.JsonProperty; import org.apache.commons.lang3.ClassUtils; import org.apache.commons.lang3.reflect.FieldUtils; import org.joda.time.DateTime; import org.joda.time.LocalDate; import javax.xml.ws.Service; import java.lang.reflect.Field; import java.util.List; import java.util.Map; /** * ServiceClient is the abstraction for accessing REST operations and their payload data types. */ public class Validator { public static void validate(Object parameter) throws ServiceException { // Validation of top level payload is done outside if (parameter == null) { return; } Field[] fields = FieldUtils.getAllFields(parameter.getClass()); for (Field field : fields) { field.setAccessible(true); JsonProperty annotation = field.getAnnotation(JsonProperty.class); Object property = null; try { property = field.get(parameter); } catch (IllegalAccessException e) { throw new ServiceException(e); } if (property == null) { if (annotation != null && annotation.required()) { throw new ServiceException( new IllegalArgumentException(field.getName() + " is required and cannot be null.")); } } else { try { Class propertyType = property.getClass(); if (ClassUtils.isAssignable(propertyType, List.class)) { List<?> items = (List<?>)property; for (Object item : items) { Validator.validate(item); } } if (ClassUtils.isAssignable(propertyType, Map.class)) { Map<?, ?> entries = (Map<?, ?>)property; for (Map.Entry<?, ?> entry : entries.entrySet()) { Validator.validate(entry.getKey()); Validator.validate(entry.getValue()); } } else if (!(ClassUtils.isPrimitiveOrWrapper(propertyType) || propertyType.isEnum() || ClassUtils.isAssignable(propertyType, LocalDate.class) || ClassUtils.isAssignable(propertyType, DateTime.class) || ClassUtils.isAssignable(propertyType, String.class))) { Validator.validate(property); } } catch (ServiceException ex) { IllegalArgumentException cause = (IllegalArgumentException)(ex.getCause()); if (cause != null) { // Build property chain throw new ServiceException( new IllegalArgumentException(field.getName() + "." + cause.getMessage())); } else { throw ex; } } } } } public static void validate(Object parameter, ServiceCallback<?> serviceCallback) { try { validate(parameter); } catch (ServiceException ex) { serviceCallback.failure(ex); } } }
package com.ociweb.gl.api; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Enumeration; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ociweb.gl.impl.BridgeConfigImpl; import com.ociweb.gl.impl.BuilderImpl; import com.ociweb.gl.impl.ChildClassScanner; import com.ociweb.gl.impl.ChildClassScannerVisitor; import com.ociweb.gl.impl.RestListenerBase; import com.ociweb.gl.impl.schema.MessageSubscription; import com.ociweb.gl.impl.schema.TrafficOrderSchema; import com.ociweb.gl.impl.stage.EgressConverter; import com.ociweb.gl.impl.stage.IngressConverter; import com.ociweb.gl.impl.stage.ReactiveListenerStage; import com.ociweb.gl.impl.stage.ReactiveManagerPipeConsumer; import com.ociweb.gl.impl.stage.ReactiveOperators; import com.ociweb.pronghorn.network.NetGraphBuilder; import com.ociweb.pronghorn.network.ServerCoordinator; import com.ociweb.pronghorn.network.ServerPipesConfig; import com.ociweb.pronghorn.network.http.HTTP1xRouterStageConfig; import com.ociweb.pronghorn.network.module.FileReadModuleStage; import com.ociweb.pronghorn.network.schema.ClientHTTPRequestSchema; import com.ociweb.pronghorn.network.schema.HTTPRequestSchema; import com.ociweb.pronghorn.network.schema.NetPayloadSchema; import com.ociweb.pronghorn.network.schema.NetResponseSchema; import com.ociweb.pronghorn.network.schema.ServerResponseSchema; import com.ociweb.pronghorn.pipe.DataInputBlobReader; import com.ociweb.pronghorn.pipe.Pipe; import com.ociweb.pronghorn.pipe.PipeConfig; import com.ociweb.pronghorn.pipe.PipeConfigManager; import com.ociweb.pronghorn.pipe.util.hash.IntHashTable; import com.ociweb.pronghorn.stage.PronghornStage; import com.ociweb.pronghorn.stage.route.ReplicatorStage; import com.ociweb.pronghorn.stage.scheduling.GraphManager; import com.ociweb.pronghorn.stage.scheduling.NonThreadScheduler; import com.ociweb.pronghorn.stage.scheduling.StageScheduler; import com.ociweb.pronghorn.stage.test.PipeCleanerStage; public class MsgRuntime<B extends BuilderImpl, L extends ListenerFilter> { public static final Logger logger = LoggerFactory.getLogger(MsgRuntime.class); protected static final int nsPerMS = 1_000_000; public B builder; protected final GraphManager gm; protected final String[] args; protected StageScheduler scheduler; protected static final int defaultCommandChannelLength = 16; protected static final int defaultCommandChannelMaxPayload = 256; //largest i2c request or pub sub payload protected static final int defaultCommandChannelHTTPMaxPayload = 1<<14; //must be at least 32K for TLS support protected boolean transducerAutowiring = true; private final PipeConfigManager listenerPipeConfigs = buildPipeManager(); protected static final PipeConfig<NetResponseSchema> responseNetConfig = new PipeConfig<NetResponseSchema>(NetResponseSchema.instance, defaultCommandChannelLength, defaultCommandChannelHTTPMaxPayload); protected static final PipeConfig<ClientHTTPRequestSchema> requestNetConfig = new PipeConfig<ClientHTTPRequestSchema>(ClientHTTPRequestSchema.instance, defaultCommandChannelLength, defaultCommandChannelMaxPayload); protected static final PipeConfig<ServerResponseSchema> serverResponseNetConfig = new PipeConfig<ServerResponseSchema>(ServerResponseSchema.instance, 1<<12, defaultCommandChannelHTTPMaxPayload); protected static final PipeConfig<MessageSubscription> messageSubscriptionConfig = new PipeConfig<MessageSubscription>(MessageSubscription.instance, defaultCommandChannelLength, defaultCommandChannelMaxPayload); protected static final PipeConfig<ServerResponseSchema> fileResponseConfig = new PipeConfig<ServerResponseSchema>(ServerResponseSchema.instance, 1<<12, defaultCommandChannelHTTPMaxPayload); private PipeConfig<HTTPRequestSchema> fileRequestConfig;// = builder.restPipeConfig.grow2x(); protected int netResponsePipeIdx = 0;//this implementation is dependent upon graphManager returning the pipes in the order created! protected int subscriptionPipeIdx = 0; //this implementation is dependent upon graphManager returning the pipes in the order created! protected final IntHashTable subscriptionPipeLookup = new IntHashTable(10);//NOTE: this is a maximum of 1024 listeners protected final IntHashTable netPipeLookup = new IntHashTable(10);//NOTE: this is a maximum of 1024 listeners private BridgeConfig[] bridges = new BridgeConfig[0]; protected int parallelInstanceUnderActiveConstruction = -1; protected Pipe<?>[] outputPipes = null; protected ChildClassScannerVisitor gatherPipesVisitor = new ChildClassScannerVisitor<MsgCommandChannel>() { @Override public boolean visit(MsgCommandChannel cmdChnl, Object topParent) { IntHashTable usageChecker = getUsageChecker(); if (null!=usageChecker) { if (!ChildClassScanner.notPreviouslyHeld(cmdChnl, topParent, usageChecker)) { logger.error("Command channel found in "+ topParent.getClass().getSimpleName()+ " can not be used in more than one Behavior"); assert(false) : "A CommandChannel instance can only be used exclusivly by one object or lambda. Double check where CommandChannels are passed in."; } } MsgCommandChannel.setListener(cmdChnl, (Behavior)topParent); //add this to the count of publishers //CharSequence[] supportedTopics = cmdChnl.supportedTopics(); //get count of subscribers per topic as well. //get the pipe ID of the singular PubSub... outputPipes = PronghornStage.join(outputPipes, cmdChnl.getOutputPipes()); return true;//keep looking } }; private ChildClassScannerVisitor transVisitor = new ChildClassScannerVisitor<ListenerTransducer>() { @Override public boolean visit(ListenerTransducer child, Object topParent) { // TODO found this child inside this Behavior ReactiveOperators operators = ReactiveListenerStage.operators; int i = operators.interfaces.size(); while (--i>=0) { if (operators.interfaces.get(i).isInstance(child)) { //need this pipe } } //put all the children into lists by the listener type for notifications return true;//keep going } }; public void disableTransducerAutowiring() { transducerAutowiring = false; } private void keepBridge(BridgeConfig bridge) { boolean isFound = false; int i = bridges.length; while (--i>=0) { isFound |= bridge == bridges[0]; } if (!isFound) { i = bridges.length; BridgeConfig[] newArray = new BridgeConfig[i+1]; System.arraycopy(bridges, 0, newArray, 0, i); newArray[i] = bridge; bridges = newArray; } } public MsgRuntime(String[] args) { this.gm = new GraphManager(); this.args = args; } public String[] args() { return args; } public final void bridgeSubscription(CharSequence topic, BridgeConfig config) { config.addSubscription(topic); keepBridge(config); } public final void subscriptionBridge(CharSequence internalTopic, CharSequence extrnalTopic, BridgeConfig config) { config.addSubscription(internalTopic,extrnalTopic); keepBridge(config); } public final void subscriptionBridge(CharSequence internalTopic, CharSequence extrnalTopic, BridgeConfig config, IngressConverter converter) { config.addSubscription(internalTopic,extrnalTopic,converter); keepBridge(config); } public final void bridgeTransmission(CharSequence topic, BridgeConfig config) { config.addTransmission(this, topic); keepBridge(config); } public final void transmissionBridge(CharSequence internalTopic, CharSequence extrnalTopic, BridgeConfig config) { config.addTransmission(this, internalTopic,extrnalTopic); keepBridge(config); } public final void transmissionBridge(CharSequence internalTopic, CharSequence extrnalTopic, BridgeConfig config, EgressConverter converter) { config.addTransmission(this, internalTopic,extrnalTopic, converter); keepBridge(config); } public final L addRestListener(RestListener listener) { return (L) registerListenerImpl(listener); } public final L addResponseListener(HTTPResponseListener listener) { return (L) registerListenerImpl(listener); } public final L addStartupListener(StartupListener listener) { return (L) registerListenerImpl(listener); } public final L addShutdownListener(ShutdownListener listener) { return (L) registerListenerImpl(listener); } public final L addTimePulseListener(TimeListener listener) { return (L) registerListenerImpl(listener); } @Deprecated public final L addTimeListener(TimeListener listener) { return (L) addTimePulseListener(listener); } public final L addPubSubListener(PubSubListener listener) { return (L) registerListenerImpl(listener); } public final <E extends Enum<E>> L addStateChangeListener(StateChangeListener<E> listener) { return (L) registerListenerImpl(listener); } public L registerListener(Behavior listener) { return (L) registerListenerImpl(listener); } public long fieldId(int routeId, byte[] fieldName) { return builder.fieldId(routeId, fieldName); } protected void logStageScheduleRates() { int totalStages = GraphManager.countStages(gm); for(int i=1;i<=totalStages;i++) { PronghornStage s = GraphManager.getStage(gm, i); if (null != s) { Object rate = GraphManager.getNota(gm, i, GraphManager.SCHEDULE_RATE, null); if (null == rate) { logger.debug("{} is running without breaks",s); } else { logger.debug("{} is running at rate of {}",s,rate); } } } } public String getArgumentValue(String longName, String shortName, String defaultValue) { return getOptArg(longName,shortName, args, defaultValue); } public static String getOptArg(String longName, String shortName, String[] args, String defaultValue) { if (args == null) { return defaultValue; } String prev = null; for (String token : args) { if (longName.equals(prev) || shortName.equals(prev)) { if (token == null || token.trim().length() == 0 || token.startsWith("-")) { return defaultValue; } return reportChoice(longName, shortName, token.trim()); } prev = token; } return reportChoice(longName, shortName, defaultValue); } public boolean hasArgument(String longName, String shortName) { return hasArg(longName,shortName, args); } public static boolean hasArg(String longName, String shortName, String[] args) { if (args == null) { return false; } for (String token : args) { if (longName.equals(token) || shortName.equals(token)) { return true; } } return false; } static String reportChoice(final String longName, final String shortName, final String value) { System.out.print(longName); System.out.print(" "); System.out.print(shortName); System.out.print(" "); System.out.println(value); return value; } protected void configureStageRate(Object listener, ReactiveListenerStage stage) { //if we have a time event turn it on. long rate = builder.getTriggerRate(); if (rate>0 && listener instanceof TimeListener) { stage.setTimeEventSchedule(rate, builder.getTriggerStart()); //Since we are using the time schedule we must set the stage to be faster long customRate = (rate*nsPerMS)/NonThreadScheduler.granularityMultiplier;// in ns and guanularityXfaster than clock trigger long appliedRate = Math.min(customRate,builder.getDefaultSleepRateNS()); GraphManager.addNota(gm, GraphManager.SCHEDULE_RATE, appliedRate, stage); } } public StageScheduler getScheduler() { return scheduler; } public void shutdownRuntime() { //only do if not already done. if (!ReactiveListenerStage.isShutdownRequested()) { if (null == scheduler || null == builder) { System.exit(0); return; } final Runnable lastCall = new Runnable() { @Override public void run() { //all the software has now stopped so shutdown the hardware now. builder.shutdown(); } }; //notify all the reactors to begin shutdown. ReactiveListenerStage.requestSystemShutdown(new Runnable() { @Override public void run() { scheduler.shutdown(); scheduler.awaitTermination(3, TimeUnit.SECONDS, lastCall, lastCall); } }); } } public void shutdownRuntime(int timeoutInSeconds) { //clean shutdown providing time for the pipe to empty scheduler.shutdown(); scheduler.awaitTermination(timeoutInSeconds, TimeUnit.SECONDS); //timeout error if this does not exit cleanly withing this time. //all the software has now stopped so now shutdown the hardware. builder.shutdown(); } //only build this when assertions are on public static IntHashTable cmdChannelUsageChecker; static { assert(setupForChannelAssertCheck()); } private static boolean setupForChannelAssertCheck() { cmdChannelUsageChecker = new IntHashTable(9); return true; } private static IntHashTable getUsageChecker() { return cmdChannelUsageChecker; } protected int addGreenPipesCount(Behavior listener, int pipesCount) { if (this.builder.isListeningToHTTPResponse(listener)) { pipesCount++; //these are calls to URL responses } if (this.builder.isListeningToSubscription(listener)) { pipesCount++; } if (this.builder.isListeningHTTPRequest(listener)) { pipesCount += ListenerConfig.computeParallel(builder, parallelInstanceUnderActiveConstruction); } return pipesCount; } protected void populateGreenPipes(Behavior listener, int pipesCount, Pipe<?>[] inputPipes) { if (this.builder.isListeningToHTTPResponse(listener)) { Pipe<NetResponseSchema> netResponsePipe1 = new Pipe<NetResponseSchema>(responseNetConfig) { @SuppressWarnings("unchecked") @Override protected DataInputBlobReader<NetResponseSchema> createNewBlobReader() { return new HTTPResponseReader(this); } }; Pipe<NetResponseSchema> netResponsePipe = netResponsePipe1; int pipeIdx = netResponsePipeIdx++; inputPipes[--pipesCount] = netResponsePipe; boolean addedItem = IntHashTable.setItem(netPipeLookup, builder.behaviorId((Behavior)listener), pipeIdx); if (!addedItem) { throw new RuntimeException("Could not find unique identityHashCode for "+listener.getClass().getCanonicalName()); } } if (this.builder.isListeningToSubscription(listener)) { inputPipes[--pipesCount]=buildPublishPipe(listener); } //if we push to this 1 pipe all the requests... //JoinStage to take N inputs and produce 1 output. //we use splitter for single pipe to 2 databases //we use different group for parallel processing //for mutiple we must send them all to the reactor. if (this.builder.isListeningHTTPRequest(listener) ) { Pipe<HTTPRequestSchema>[] httpRequestPipes; httpRequestPipes = ListenerConfig.newHTTPRequestPipes(builder, ListenerConfig.computeParallel(builder, parallelInstanceUnderActiveConstruction)); int i = httpRequestPipes.length; assert(i>0) : "This listens to Rest requests but none have been routed here"; while (--i >= 0) { inputPipes[--pipesCount] = httpRequestPipes[i]; } } } /** * This pipe returns all the data this object has requested via subscriptions elsewhere. * @param listener */ public Pipe<MessageSubscription> buildPublishPipe(Object listener) { Pipe<MessageSubscription> subscriptionPipe = buildMessageSubscriptionPipe(); return attachListenerIndexToMessageSubscriptionPipe(listener, subscriptionPipe); } public Pipe<MessageSubscription> buildPublishPipe(int listenerHash) { Pipe<MessageSubscription> subscriptionPipe = buildMessageSubscriptionPipe(); if (!IntHashTable.setItem(subscriptionPipeLookup, listenerHash, subscriptionPipeIdx++)) { throw new RuntimeException("HashCode must be unique"); } assert(!IntHashTable.isEmpty(subscriptionPipeLookup)); return subscriptionPipe; } private Pipe<MessageSubscription> attachListenerIndexToMessageSubscriptionPipe(Object listener, Pipe<MessageSubscription> subscriptionPipe) { //store this value for lookup later //logger.info("adding hash listener {} to pipe ",System.identityHashCode(listener)); if (!IntHashTable.setItem(subscriptionPipeLookup, System.identityHashCode(listener), subscriptionPipeIdx++)) { throw new RuntimeException("Could not find unique identityHashCode for "+listener.getClass().getCanonicalName()); } assert(!IntHashTable.isEmpty(subscriptionPipeLookup)); return subscriptionPipe; } private Pipe<MessageSubscription> buildMessageSubscriptionPipe() { Pipe<MessageSubscription> subscriptionPipe = new Pipe<MessageSubscription>(messageSubscriptionConfig) { @SuppressWarnings("unchecked") @Override protected DataInputBlobReader<MessageSubscription> createNewBlobReader() { return new MessageReader(this); } }; return subscriptionPipe; } protected void constructingParallelInstance(int i) { parallelInstanceUnderActiveConstruction = i; } protected void constructingParallelInstancesEnding() { parallelInstanceUnderActiveConstruction = -1; } //server and other behavior public void declareBehavior(MsgApp app) { if (builder.isUseNetServer()) { buildGraphForServer(app); } else { app.declareBehavior(this); if (app instanceof MsgAppParallel) { int parallelism = builder.parallelism(); //since server was not started and did not create each parallel instance this will need to be done here for(int i = 0;i<parallelism;i++) { //do not use this loop, we will loop inside server setup.. constructingParallelInstance(i); ((MsgAppParallel)app).declareParallelBehavior(this); } } } constructingParallelInstancesEnding(); //Init bridges int b = bridges.length; while (--b>=0) { ((BridgeConfigImpl)bridges[b]).finish(this); } } private void buildGraphForServer(MsgApp app) { ServerPipesConfig serverConfig = new ServerPipesConfig(builder.isLarge(), builder.isServerTLS()); ServerCoordinator serverCoord = new ServerCoordinator( builder.isServerTLS(), (String) builder.bindHost(), builder.bindPort(), serverConfig.maxConnectionBitsOnServer, serverConfig.maxPartialResponsesServer, builder.parallelism()); final int routerCount = builder.parallelism(); final Pipe<NetPayloadSchema>[] encryptedIncomingGroup = Pipe.buildPipes(serverConfig.maxPartialResponsesServer, serverConfig.incomingDataConfig); Pipe[] acks = NetGraphBuilder.buildSocketReaderStage(gm, serverCoord, routerCount, serverConfig, encryptedIncomingGroup, -1); Pipe[] handshakeIncomingGroup=null; Pipe[] planIncomingGroup; if (builder.isServerTLS()) { planIncomingGroup = Pipe.buildPipes(serverConfig.maxPartialResponsesServer, serverConfig.incomingDataConfig); handshakeIncomingGroup = NetGraphBuilder.populateGraphWithUnWrapStages(gm, serverCoord, serverConfig.serverRequestUnwrapUnits, serverConfig.handshakeDataConfig, encryptedIncomingGroup, planIncomingGroup, acks, -1); } else { planIncomingGroup = encryptedIncomingGroup; } //Must call here so the beginning stages of the graph are drawn first when exporting graph. app.declareBehavior(this); buildLastHalfOfGraphForServer(app, serverConfig, serverCoord, routerCount, acks, handshakeIncomingGroup, planIncomingGroup); } private void buildLastHalfOfGraphForServer(MsgApp app, ServerPipesConfig serverConfig, ServerCoordinator serverCoord, final int routerCount, Pipe[] acks, Pipe[] handshakeIncomingGroup, Pipe[] planIncomingGroup) { //create the working modules if (app instanceof MsgAppParallel) { int p = builder.parallelism(); for (int i = 0; i < p; i++) { constructingParallelInstance(i); ((MsgAppParallel)app).declareParallelBehavior(this); //this creates all the modules for this parallel instance } } else { if (builder.parallelism()>1) { throw new UnsupportedOperationException( "Remove call to parallelism("+builder.parallelism()+") OR make the application implement GreenAppParallel or something extending it."); } } HTTP1xRouterStageConfig routerConfig = builder.routerConfig(); ArrayList<Pipe> forPipeCleaner = new ArrayList<Pipe>(); Pipe<HTTPRequestSchema>[][] fromRouterToModules = new Pipe[routerCount][]; int t = routerCount; int totalRequestPipes = 0; while (--t>=0) { //[router/parallel] then [parser/routes] int path = routerConfig.routesCount(); ///for catch all if (path==0) { path=1; } fromRouterToModules[t] = new Pipe[path]; while (--path >= 0) { ArrayList<Pipe<HTTPRequestSchema>> requestPipes = builder.buildFromRequestArray(t, path); //with a single pipe just pass it one, otherwise use the replicator to fan out from a new single pipe. int size = requestPipes.size(); totalRequestPipes += size; if (1==size) { fromRouterToModules[t][path] = requestPipes.get(0); } else { //we only create a pipe when we are about to use the replicator fromRouterToModules[t][path] = builder.newHTTPRequestPipe(builder.restPipeConfig); if (0==size) { logger.info("warning there are routes without any consumers"); //we have no consumer so tie it to pipe cleaner forPipeCleaner.add(fromRouterToModules[t][path]); } else { ReplicatorStage.newInstance(gm, fromRouterToModules[t][path], requestPipes.toArray(new Pipe[requestPipes.size()])); } } } if (0==totalRequestPipes) { logger.warn("ERROR: includeRoutes or includeAllRoutes must be called on REST listener."); } } if (!forPipeCleaner.isEmpty()) { PipeCleanerStage.newInstance(gm, forPipeCleaner.toArray(new Pipe[forPipeCleaner.size()])); } //NOTE: building arrays of pipes grouped by parallel/routers heading out to order supervisor Pipe<ServerResponseSchema>[][] fromModulesToOrderSuper = new Pipe[routerCount][]; Pipe<ServerResponseSchema>[] errorResponsePipes = new Pipe[routerCount]; PipeConfig<ServerResponseSchema> errConfig = ServerResponseSchema.instance.newPipeConfig(4, 512); int r = routerCount; while (--r>=0) { errorResponsePipes[r] = new Pipe<ServerResponseSchema>(errConfig); fromModulesToOrderSuper[r] = PronghornStage.join(builder.buildToOrderArray(r),errorResponsePipes[r]); } boolean catchAll = builder.routerConfig().routesCount()==0; NetGraphBuilder.buildRouters(gm, routerCount, planIncomingGroup, acks, fromRouterToModules, errorResponsePipes, routerConfig, serverCoord, -1, catchAll); final GraphManager graphManager = gm; Pipe<NetPayloadSchema>[] fromOrderedContent = NetGraphBuilder.buildRemainderOfServerStages(graphManager, serverCoord, serverConfig, handshakeIncomingGroup, -1); NetGraphBuilder.buildOrderingSupers(graphManager, serverCoord, routerCount, fromModulesToOrderSuper, fromOrderedContent, -1); } //end of server and other behavior public void setExclusiveTopics(MsgCommandChannel cc, String ... exlusiveTopics) { // TODO Auto-generated method stub throw new UnsupportedOperationException("Not yet implemented"); } //Not for general consumption, only used when we need the low level Pipes to connect directly to the pub/sub or other dynamic subsystem. public static GraphManager getGraphManager(MsgRuntime runtime) { return runtime.gm; } public RouteFilter addFileServer(String path) { //adds server to all routes final int parallelIndex = (-1 == parallelInstanceUnderActiveConstruction) ? 0 : parallelInstanceUnderActiveConstruction; //due to internal implementation we must keep the same number of outputs as inputs. Pipe<HTTPRequestSchema>[] inputs = new Pipe[1]; Pipe<ServerResponseSchema>[] outputs = new Pipe[1]; populateHTTPInOut(inputs, outputs, 0, parallelIndex); File rootPath = buildFilePath(path); FileReadModuleStage.newInstance(gm, inputs, outputs, builder.httpSpec, rootPath); return new StageRouteFilter(inputs[0], builder, parallelIndex); } public RouteFilter addFileServer(String resourceRoot, String resourceDefault) { final int parallelIndex = (-1 == parallelInstanceUnderActiveConstruction) ? 0 : parallelInstanceUnderActiveConstruction; //due to internal implementation we must keep the same number of outputs as inputs. Pipe<HTTPRequestSchema>[] inputs = new Pipe[1]; Pipe<ServerResponseSchema>[] outputs = new Pipe[1]; populateHTTPInOut(inputs, outputs, 0, parallelIndex); FileReadModuleStage.newInstance(gm, inputs, outputs, builder.httpSpec, resourceRoot, resourceDefault); return new StageRouteFilter(inputs[0], builder, parallelIndex); } private void populateHTTPInOut(Pipe<HTTPRequestSchema>[] inputs, Pipe<ServerResponseSchema>[] outputs, int idx, int parallelIndex) { if (null == fileRequestConfig) { fileRequestConfig = builder.restPipeConfig.grow2x(); } inputs[idx] = builder.newHTTPRequestPipe(fileRequestConfig); outputs[idx] = builder.newNetResponsePipe(fileResponseConfig, parallelIndex); } //TODO: needs a lot of re-work. private File buildFilePath(String path) { // Strip URL space tokens from incoming path strings to avoid issues. // TODO: This should be made garbage free. // TODO: Is this expected behavior? path = path.replaceAll("\\Q%20\\E", " "); //TODO: MUST FIND PATH... Enumeration<URL> resource; try { resource = ClassLoader.getSystemResources(path); while (resource.hasMoreElements()) { System.err.println("looking for resoruce: "+path+" and found "+String.valueOf(resource.nextElement())); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // ClassLoader.getSystemResource(path); File rootPath = new File(path); if (!rootPath.exists()) { //test if this is under development File devPath = new File("./src/main/resources/"+path); if (devPath.exists()) { rootPath = devPath; } } if (!rootPath.exists()) { throw new UnsupportedOperationException("Path not found: "+rootPath); } return rootPath; } //end of file server public Builder getBuilder(){ if(this.builder==null){ this.builder = (B) new BuilderImpl(gm,args); } return this.builder; } private ListenerFilter registerListenerImpl(final Behavior listener) { //OUTPUT outputPipes = new Pipe<?>[0]; //extract pipes used by listener and use cmdChannelUsageChecker to confirm its not re-used ChildClassScanner.visitUsedByClass(listener, gatherPipesVisitor, MsgCommandChannel.class);//populates outputPipes //INPUT //add green features, count first then create the pipes //NOTE: that each Behavior is inspected and will find Transducers which need inputs as well int pipesCount = addGreenPipesCount(listener, 0); Pipe<?>[] inputPipes = new Pipe<?>[pipesCount]; populateGreenPipes(listener, pipesCount, inputPipes); //this is empty when transducerAutowiring is off final ArrayList<ReactiveManagerPipeConsumer> consumers = new ArrayList<ReactiveManagerPipeConsumer>(); //extract this into common method to be called in GL and FL if (transducerAutowiring) { inputPipes = autoWireTransducers(listener, inputPipes, consumers); } ReactiveListenerStage reactiveListener = builder.createReactiveListener(gm, listener, inputPipes, outputPipes, consumers, parallelInstanceUnderActiveConstruction); if (listener instanceof RestListenerBase) { GraphManager.addNota(gm, GraphManager.DOT_RANK_NAME, "ModuleStage", reactiveListener); } //StartupListener is not driven by any response data and is called when the stage is started up. no pipe needed. //TimeListener, time rate signals are sent from the stages its self and therefore does not need a pipe to consume. configureStageRate(listener,reactiveListener); int testId = -1; int i = inputPipes.length; while (--i>=0) { if (inputPipes[i]!=null && Pipe.isForSchema((Pipe<MessageSubscription>)inputPipes[i], MessageSubscription.class)) { testId = inputPipes[i].id; } } assert(-1==testId || GraphManager.allPipesOfType(gm, MessageSubscription.instance)[subscriptionPipeIdx-1].id==testId) : "GraphManager has returned the pipes out of the expected order"; return reactiveListener; } protected Pipe<?>[] autoWireTransducers(final Behavior listener, Pipe<?>[] inputPipes, final ArrayList<ReactiveManagerPipeConsumer> consumers) { final Grouper g = new Grouper(inputPipes); ChildClassScannerVisitor tVisitor = new ChildClassScannerVisitor() { @Override public boolean visit(Object child, Object topParent) { if (g.additions()==0) { //add first value g.add(ReactiveListenerStage.operators.createPipes(listener,listenerPipeConfigs)); } Pipe[] pipes = ReactiveListenerStage.operators.createPipes(child,listenerPipeConfigs); consumers.add(new ReactiveManagerPipeConsumer(child, ReactiveListenerStage.operators, pipes)); //roll these pipes with the others by type. g.add(pipes); return true; } }; ChildClassScanner.visitUsedByClass(listener, tVisitor, ListenerTransducer.class); if (g.additions()>0) { inputPipes = g.firstArray(); g.buildReplicators(gm); } return inputPipes; } protected PipeConfigManager buildPipeManager() { PipeConfigManager pcm = new PipeConfigManager(); pcm.addConfig(defaultCommandChannelLength,0,TrafficOrderSchema.class ); return pcm; } }
package com.okta.tools.saml; import com.okta.tools.authentication.BrowserAuthentication; import com.okta.tools.OktaAwsCliEnvironment; import com.okta.tools.authentication.OktaAuthentication; import com.okta.tools.helpers.CookieHelper; import org.apache.http.HttpStatus; import org.apache.http.client.CookieStore; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.cookie.Cookie; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.json.JSONException; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.select.Elements; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Optional; public class OktaSaml { private final OktaAwsCliEnvironment environment; private final CookieHelper cookieHelper; public OktaSaml(OktaAwsCliEnvironment environment, CookieHelper cookieHelper) { this.environment = environment; this.cookieHelper = cookieHelper; } public String getSamlResponse() throws IOException { OktaAuthentication authentication = new OktaAuthentication(environment); if (reuseSession()) { return getSamlResponseForAwsRefresh(); } else if (environment.browserAuth) { try { return BrowserAuthentication.login(environment); } catch (InterruptedException e) { throw new RuntimeException(e); } } else { String oktaSessionToken = authentication.getOktaSessionToken(); return getSamlResponseForAws(oktaSessionToken); } } private String getSamlResponseForAws(String oktaSessionToken) throws IOException { Document document = launchOktaAwsAppWithSessionToken(environment.oktaAwsAppUrl, oktaSessionToken); return getSamlResponseForAwsFromDocument(document); } private String getSamlResponseForAwsRefresh() throws IOException { Document document = launchOktaAwsApp(environment.oktaAwsAppUrl); return getSamlResponseForAwsFromDocument(document); } private String getSamlResponseForAwsFromDocument(Document document) { Elements samlResponseInputElement = document.select("form input[name=SAMLResponse]"); if (samlResponseInputElement.isEmpty()) { if (isPasswordAuthenticationChallenge(document)) { throw new IllegalStateException("Unsupported App sign on rule: 'Prompt for re-authentication'. \nPlease contact your administrator."); } else if (isPromptForFactorChallenge(document)) { throw new IllegalStateException("Unsupported App sign on rule: 'Prompt for factor'. \nPlease contact your administrator."); } else { Elements errorContent = document.getElementsByClass("error-content"); Elements errorHeadline = errorContent.select("h1"); if (errorHeadline.hasText()) { throw new RuntimeException(errorHeadline.text()); } else { throw new RuntimeException("You do not have access to AWS through Okta. \nPlease contact your administrator."); } } } return samlResponseInputElement.attr("value"); } // Heuristic based on undocumented behavior observed experimentally // This condition may be missed if Okta significantly changes the app-level re-auth page private boolean isPasswordAuthenticationChallenge(Document document) { return document.getElementById("password-verification-challenge") != null; } // Heuristic based on undocumented behavior observed experimentally // This condition may be missed if Okta significantly changes the app-level MFA page private boolean isPromptForFactorChallenge(Document document) { return document.getElementById("okta-sign-in") != null; } private Document launchOktaAwsAppWithSessionToken(String appUrl, String oktaSessionToken) throws IOException { return launchOktaAwsApp(appUrl + "?onetimetoken=" + oktaSessionToken); } private Document launchOktaAwsApp(String appUrl) throws IOException { HttpGet httpget = new HttpGet(appUrl); CookieStore cookieStore = cookieHelper.loadCookies(); try (CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).useSystemProperties().build(); CloseableHttpResponse oktaAwsAppResponse = httpClient.execute(httpget)) { if (oktaAwsAppResponse.getStatusLine().getStatusCode() >= 500) { throw new RuntimeException("Server error when loading Okta AWS App: " + oktaAwsAppResponse.getStatusLine().getStatusCode()); } else if (oktaAwsAppResponse.getStatusLine().getStatusCode() >= 400) { throw new RuntimeException("Client error when loading Okta AWS App: " + oktaAwsAppResponse.getStatusLine().getStatusCode()); } cookieHelper.storeCookies(cookieStore); return Jsoup.parse( oktaAwsAppResponse.getEntity().getContent(), StandardCharsets.UTF_8.name(), appUrl ); } } private boolean reuseSession() throws JSONException, IOException { CookieStore cookieStore = cookieHelper.loadCookies(); Optional<String> sidCookie = cookieStore.getCookies().stream().filter(cookie -> "sid".equals(cookie.getName())).findFirst().map(Cookie::getValue); if (!sidCookie.isPresent()) { return false; } HttpPost httpPost = new HttpPost("https://" + environment.oktaOrg + "/api/v1/sessions/me/lifecycle/refresh"); httpPost.addHeader("Accept", "application/json"); httpPost.addHeader("Content-Type", "application/json"); httpPost.addHeader("Cookie", "sid=" + sidCookie.get()); try (CloseableHttpClient httpClient = HttpClients.createSystem()) { CloseableHttpResponse authnResponse = httpClient.execute(httpPost); return authnResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK; } } }
package com.team2502.robot2017; import com.kauailabs.navx.frc.AHRS; import com.team2502.robot2017.subsystem.*; import edu.wpi.first.wpilibj.Compressor; import edu.wpi.first.wpilibj.IterativeRobot; import edu.wpi.first.wpilibj.SerialPort; import edu.wpi.first.wpilibj.command.Scheduler; import edu.wpi.first.wpilibj.livewindow.LiveWindow; import logger.Log; @SuppressWarnings({ "WeakerAccess", "unused" }) public final class Robot extends IterativeRobot { public static final DriveTrainSubsystem DRIVE_TRAIN = new DriveTrainSubsystem(); public static final PressureSensorSubsystem PRESSURE_SENSOR = new PressureSensorSubsystem(); public static final VisionSubsystem VISION = new VisionSubsystem(); public static final Compressor COMPRESSOR = new Compressor(); public static final ShooterSubsystem SHOOTER = new ShooterSubsystem(); public static final DistanceSensorSubsystem DISTANCE_SENSOR = new DistanceSensorSubsystem(); public static final ActiveIntakeSubsystem ACTIVE = new ActiveIntakeSubsystem(); public static final DriveTrainTransmissionSubsystem DRIVE_TRAIN_GEAR_SWITCH; public static final AHRS NAVX = new AHRS(SerialPort.Port.kMXP); static { /* I don't know why but this prevents problems. */ DRIVE_TRAIN_GEAR_SWITCH = new DriveTrainTransmissionSubsystem(); } /** * This function is run when the robot is first started up and should be * used for any initialization code. */ public void robotInit() { Log.createLogger(true); DashboardData.setup(); OI.init(); } /** * This function is called once each time the robot enters Disabled mode. * You can use it to reset any subsystem information you want to clear when * the robot is disabled. */ public void disabledInit() {} public void disabledPeriodic() { Scheduler.getInstance().run(); DashboardData.update(); DRIVE_TRAIN.stop(); } /** * This autonomous (along with the chooser code above) shows how to select between different autonomous modes * using the dashboard. The sendable chooser code works with the Java SmartDashboard. If you prefer the LabVIEW * Dashboard, remove all of the chooser code and uncomment the getString code to get the auto name from the text box * below the Gyro * <p> * You can add additional auto modes by adding additional commands to the chooser code above (like the commented example) * or additional comparisons to the switch structure below with additional strings and commands. */ public void autonomousInit() { Scheduler.getInstance().add(DashboardData.getAutonomous()); } /** * This function is called periodically during autonomous */ public void autonomousPeriodic() { Scheduler.getInstance().run(); DashboardData.update(); } public void teleopInit() { // This makes sure that the autonomous stops running when // teleop starts running. If you want the autonomous to // continue until interrupted by another command, remove // this line or comment it out. } /** * This function is called periodically during operator control */ public void teleopPeriodic() { Scheduler.getInstance().run(); DashboardData.update(); } /** * This function is called periodically during test mode */ public void testPeriodic() { LiveWindow.run(); DashboardData.update(); } }
package com.ticketmanor.model; import javax.persistence.*; import javax.validation.constraints.NotNull; /* * Person - One individual person who has some interaction with the system. */ @Entity @Table(name="People") public class Person { @Id @GeneratedValue(strategy=GenerationType.AUTO) long id; @NotNull protected String firstName; protected String middles; @NotNull protected String lastName; String email; @Embedded Address address; public Person() { // EMPTY } public Person(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return getClass().getSimpleName() + getFullName(); } @Transient public String getFullName() { StringBuilder sb = new StringBuilder(firstName); if (middles != null) { sb.append(" ").append(middles); } sb.append(" ").append(lastName); return sb.toString(); } }
package dataGridSrv1; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController @EnableAutoConfiguration public class DataGridWritter { // Constantes de la clase private static final String JDG_HOST = "jdg.host"; private static final String HOTROD_PORT = "jdg.hotrod.port"; private static final String PROPERTIES_FILE = "jdg.properties"; private static final String PRENDAS_KEY = "prendas"; public static final String ID_TRAZA = " // Variables globales private RemoteCacheManager cacheManager; private RemoteCache<String, Object> cache; @RequestMapping("/") String homeMethod() { return "<br><h1><strong>dataGridSrv1</strong></h1></br>" + "<br>Poner prendas en la caché: http://datagrid-srv1.accenture.cloud/put?parametro1=</h1></br>" + "<br>Sacar prendas de la caché: http://datagrid-srv1.accenture.cloud/get?parametro1=</h1></br>"; } @RequestMapping("/put") String putMethod(@RequestParam(value = "parametro1", defaultValue = "1") String sParametro1) { // variables int iParametro1; HashMap<String, Prenda> prendasMap; long lTimeBefore, lTimeAfter; String trazaPrendas = ""; try { init(); try { iParametro1 = Integer.parseInt(sParametro1); } catch (Exception e) { iParametro1 = 1; } prendasMap = (HashMap<String, Prenda>) cache.get(PRENDAS_KEY); // Si el HashMap no existe, ceamos uno nuevo if (prendasMap == null) prendasMap = new HashMap<String, Prenda>(); // Generamos las prendas con el id secuencial del indice del for for (int i = 0; i < iParametro1; i++) { Prenda pPrenda = calculoPrenda("" + i); // Si ya existe, no la inserto if (cache.get(pPrenda.getPrendaName()) != null) { System.out.println(ID_TRAZA + "el elemento: " + i + " ya se encuentra en la caché"); trazaPrendas += "la prenda: " + i + " ya se encuentra en la caché"; } else { prendasMap.put(pPrenda.getPrendaName(), pPrenda); lTimeBefore = System.currentTimeMillis(); cache.put(pPrenda.getPrendaName(), pPrenda); lTimeAfter = System.currentTimeMillis(); System.out.println(ID_TRAZA + "Se ha enviado en " + (lTimeAfter - lTimeBefore) + " milisegundos " + "la prenda " + pPrenda.toString()); trazaPrendas += "<br>Se ha enviado en " + (lTimeAfter - lTimeBefore) + " milisegundos " + "la prenda " + pPrenda.toString() + "</br>"; } } lTimeBefore = System.currentTimeMillis(); cache.put(PRENDAS_KEY, prendasMap); lTimeAfter = System.currentTimeMillis(); System.out.println(ID_TRAZA + "Se ha enviado en " + (lTimeAfter - lTimeBefore) + " milisegundos " + "el mapa de prendas " + prendasMap.toString()); } catch (Exception e) { e.printStackTrace(); return "<br><h1><strong>dataGridSrv1</strong></h1></br>" + "<br>PUT Finalizado con Error.</br>" + "<br>error:\n " + e.getStackTrace().toString() + "\n\n...</br>"; } return "<br><h1><strong>dataGridSrv1 Método PUT</strong></h1></br>" + trazaPrendas + "<br>Se ha enviado la lista en " + (lTimeAfter - lTimeBefore) + " milisegundos </br>" + "<br>La lista de prendas es " + prendasMap.toString() + "<br>Listo para enviar valores a la caché....</br>"; } /** * Metodo retorna valores de la cache * * @param sId * @return */ @RequestMapping("/get") String getMethod(@RequestParam(value = "parametro1", defaultValue = "1") String sId) { // variables HashMap<String, Prenda> prendasMap; long lTimeBefore, lTimeAfter; String trazaPrendas = ""; Prenda pPrenda; prendasMap = (HashMap<String, Prenda>) cache.get(PRENDAS_KEY); try { init(); // Obtenemos el HashMap de prendas lTimeBefore = System.currentTimeMillis(); lTimeAfter = System.currentTimeMillis(); trazaPrendas += "<br>Se ha recuperado el HashMap de prendas en " + (lTimeAfter - lTimeBefore) + " milisegundos </br>"; if (cache.get(sId) != null) { lTimeBefore = System.currentTimeMillis(); pPrenda = (Prenda) cache.get(sId); lTimeAfter = System.currentTimeMillis(); trazaPrendas += "<br>Se ha recuperado en " + (lTimeAfter - lTimeBefore) + " milisegundos " + "la prenda " + pPrenda.toString() + "</br>"; System.out.println(ID_TRAZA + "Se ha obtenido en " + (lTimeAfter - lTimeBefore) + " milisegundos " + "la prenda " + pPrenda.toString()); } else { trazaPrendas += "<br>La prenda " + sId + " no existe, se calculará e insertará en la caché</br>"; lTimeBefore = System.currentTimeMillis(); pPrenda = calculoPrenda(sId); cache.put(sId, pPrenda); lTimeAfter = System.currentTimeMillis(); trazaPrendas += "<br>Se ha calculado y enviado en " + (lTimeAfter - lTimeBefore) + " milisegundos " + "la prenda " + pPrenda.toString() + "</br>"; System.out.println(ID_TRAZA + "Se ha calculado y enviado en " + (lTimeAfter - lTimeBefore) + " milisegundos " + "la prenda " + pPrenda.toString()); // Actualizamos el HashMap de prendas y lo subimos a la prendasMap.put(sId, pPrenda); lTimeBefore = System.currentTimeMillis(); cache.put(PRENDAS_KEY, prendasMap); lTimeAfter = System.currentTimeMillis(); System.out.println(ID_TRAZA + "Se ha calculado y enviado en " + (lTimeAfter - lTimeBefore) + " milisegundos " + "la prenda " + pPrenda.toString()); } return "<br><h1><strong>dataGridSrv1</strong></h1></br>" + "<br>Datos de la cache.</br>" + trazaPrendas + "<br>Prenda: " + pPrenda.toString() + "</br>" + "<br>Lista Prendas: " + prendasMap.toString() + "</br>"; } catch (Exception e) { e.printStackTrace(); return "<br><h1><strong>dataGridSrv1</strong></h1></br>" + "<br>GET Finalizado con Error.</br>" + "<br>error:\n " + e.getStackTrace().toString() + "\n\n...</br>"; } } private void init() throws Exception { try { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.addServer().host(jdgProperty(JDG_HOST)).port(Integer.parseInt(jdgProperty(HOTROD_PORT))); System.out.println( " cacheManager = new RemoteCacheManager(builder.build()); cache = cacheManager.getCache("prendas"); if (!cache.containsKey(PRENDAS_KEY)) { Map<String, Prenda> prendasMap = new HashMap<String, Prenda>(); cache.put(PRENDAS_KEY, prendasMap); } } catch (Exception e) { System.out.println("Init Caught: " + e); e.printStackTrace(); throw e; } } private Prenda calculoPrenda(String sNombrePrenda) { // Creo la prenda Prenda pNuevaPrenda = new Prenda(sNombrePrenda); // Pongo colores por defecto pNuevaPrenda.addColor("Negro"); pNuevaPrenda.addColor("Blanco"); pNuevaPrenda.addColor("Azul"); // Retardo de 100 Milisegundos try { Thread.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } return pNuevaPrenda; } public static String jdgProperty(String name) { Properties props = new Properties(); try { props.load(DataGridWritter.class.getClassLoader().getResourceAsStream(PROPERTIES_FILE)); } catch (IOException ioe) { throw new RuntimeException(ioe); } return props.getProperty(name); } public static void main(String[] args) throws Exception { SpringApplication.run(DataGridWritter.class, args); } }
package dk.br.mail; import dk.br.zurb.inky.Inky; import java.io.*; import java.net.*; import java.util.*; import java.util.regex.*; import javax.mail.internet.*; import javax.xml.transform.*; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.*; /** * @author TietoEnator Consulting * @since 15. juni 2004 */ public class MailMessageParser { private final static Logger LOG = LoggerFactory.getLogger(MailMessageParser.class); private final boolean useCssInliner; private MailMessageParser() { useCssInliner = "1|yes|true".contains(System.getProperty("dk.br.mail.inline-css", "false")); } private final static Pattern CSS_URL_PATTERN = Pattern.compile("(.*)url\\(([^\\)]+)\\)(.*)"); public static MailMessageData[] parseMails(Node mailListNode) throws IOException { MailMessageParser parser = new MailMessageParser(); List<MailMessageData> result = new LinkedList<MailMessageData>(); NodeList mailListNodes = mailListNode.getChildNodes(); for (int j = 0; j < mailListNodes.getLength(); j++) { Node mailList = mailListNodes.item(j); if ("email-list".equals(mailList.getNodeName())) { LOG.debug("### parsing {}", mailList.getNodeName()); NodeList mailNodes = mailList.getChildNodes(); for (int i = 0; i < mailNodes.getLength(); i++) { Node mailNode = mailNodes.item(i); if ("email".equals(mailNode.getNodeName())) { MailMessageData msg = parser.tryParseMail(mailNode); result.add(msg); } } } else if ("email".equals(mailList.getNodeName())) { MailMessageData msg = parser.tryParseMail(mailList); result.add(msg); } } return result.toArray(new MailMessageData[result.size()]); } /** * Parses custom XML e-mail specification into a serializable, transportable, object. */ public static MailMessageData parseMail(Node mailNode) throws IOException { return new MailMessageParser().tryParseMail(mailNode); } private MailMessageData tryParseMail(Node mailNode) throws IOException { LOG.debug("### parsing {}", mailNode.getNodeName()); MailMessageData msg = new MailMessageData(); NodeList mailProperties = mailNode.getChildNodes(); for (int i = 0; i < mailProperties.getLength(); i++) { Node propertyNode = mailProperties.item(i); if (propertyNode.getNodeType() != Node.ELEMENT_NODE) continue; String propertyName = propertyNode.getNodeName(); if ("subject".equals(propertyName)) { String subject = _text(propertyNode); LOG.debug("SUBJECT: {}", subject); msg.setSubject(subject); } else if ("plain-body".equals(propertyName)) { String body = _text(propertyNode); LOG.info("text/plain body: {} characters", body.length()); msg.setPlainBody(body); } else if ("html-body".equals(propertyName)) { NodeList bodyNodes = propertyNode.getChildNodes(); HtmlPartParser parser = new HtmlPartParser(); parser.digest(bodyNodes, msg); } else if ("addresses".equals(propertyName)) { parseAddresses(propertyNode.getChildNodes(), msg); } else if ("header".equals(propertyName)) { String name = ((Element)propertyNode).getAttribute("name"); String value = ((Element)propertyNode).getAttribute("value"); if (StringUtils.isEmpty(value)) value = _text(propertyNode); LOG.debug("{}: {}", name, value); msg.setCustomHeader(name, value); } else if ("attachment".equals(propertyName)) { String src = ((Element)propertyNode).getAttribute("src"); msg.attach(MailPartSource.remote(new URL(src))); } else { LOG.error("{}: invalid mail property", propertyName); } } return msg; } private void parseAddresses(NodeList addressNodes, MailMessageData msg) { for (int i = 0; i < addressNodes.getLength(); i++) { Node addressNode = addressNodes.item(i); if (addressNode.getNodeType() == Node.ELEMENT_NODE) addAddress((Element)addressNode, msg); } } private void addAddress(Element addressElement, MailMessageData msg) { String type = addressElement.getNodeName(); InternetAddress addr = getAddress(addressElement); LOG.debug("{} {}", type, addr); if ("to".equals(type)) msg.addRecipientTo(addr); else if ("cc".equals(type)) msg.addRecipientCc(addr); else if ("bcc".equals(type)) msg.addRecipientBcc(addr); else if ("from".equals(type)) msg.addFrom(addr); else if ("reply-to".equals(type)) msg.addReplyTo(addr); else if ("sender".equals(type)) msg.setSender(addr); else if ("reply-to".equals(type)) msg.addReplyTo(addr); else if ("bounce-to".equals(type)) msg.setBounceAddress(addr); else LOG.error("{}: unknown address type", type); } /** * Gets the address attribute of a DOM element * * @param element Description of the Parameter * @return The address value */ private InternetAddress getAddress(Element element) { String address = _text(element.getElementsByTagName("email-address").item(0)); if (address == null || address.equals("")) throw new IllegalArgumentException("email-address is missing"); Node personal = element.getElementsByTagName("personal").item(0); try { InternetAddress addr = new InternetAddress(address, personal == null ? null : _text(personal)); try { addr.validate(); } catch (AddressException ex) { throw new IllegalArgumentException("unparseable email-address " + address + " - " + ex.getMessage()); } return addr; } catch (UnsupportedEncodingException ex) { throw new RuntimeException(ex.getMessage()); } } private class HtmlPartParser { boolean seenInky; URL m_baseHref; Map<String,String> m_resources = new HashMap<String,String>(); Map<String,MailPartSource> m_resourceContent = new HashMap<String,MailPartSource>(); private void digest(NodeList bodyNodes, MailMessageData msg) throws IOException { // Initialize: seenInky = false; m_resources.clear(); m_resourceContent.clear(); // Traverse HTML DOM, extracting and dereferencing external resources (style sheets, // images, etc.) as we go: digestHtmlNodeList(bodyNodes); // Serialize the modified back HTML to text: String bodyText = _htmlText(bodyNodes, "iso-8859-1", seenInky, useCssInliner); msg.setHtmlBody(bodyText); // Attach the dereferenced resources to be included as "related" MIME parts in the // final result: LOG.debug("HTML BODY: {} characters", bodyText.length()); for (Map.Entry<String,String> e : m_resources.entrySet()) { String ref = e.getKey(); String partId = e.getValue(); MailPartSource partSource = partFromRef(ref); msg.addRelatedBodyPart(partId, partSource); } } private void digestHtmlNodeList(NodeList children) throws IOException { for (int i = 0; i < children.getLength(); i++) digestHtmlNode(children.item(i)); } private void digestHtmlAttributes(NamedNodeMap children) throws IOException { for (int i = 0; i < children.getLength(); i++) digestHtmlNode(children.item(i)); } private void digestHtmlNode(Node node) throws IOException { // Replace URLs for resources to be embedded: String nodeName = node.getNodeName(); short nodeType = node.getNodeType(); if ("img".equalsIgnoreCase(nodeName) && nodeType == Node.ELEMENT_NODE) { replaceResource((Element)node, "src"); } else if ("base".equalsIgnoreCase(nodeName) && nodeType == Node.ELEMENT_NODE) { String href = ((Element)node).getAttribute("href"); try { m_baseHref = new URL(href); LOG.debug("base href: {}", m_baseHref); } catch (MalformedURLException ex) { LOG.error("bad <base href=\"{}\">", href, ex); } } else if ("link".equalsIgnoreCase(nodeName) && nodeType == Node.ELEMENT_NODE) { replaceResource((Element)node, "href"); } else if ("weblink".equalsIgnoreCase(nodeName) && nodeType == Node.ELEMENT_NODE) { digestWebLink((Element)node); } else if ("style".equalsIgnoreCase(nodeName) && nodeType == Node.ATTRIBUTE_NODE) { digestStyleAttribute((Attr)node); } else if (("body".equalsIgnoreCase(nodeName) || "table".equalsIgnoreCase(nodeName) || "tr".equalsIgnoreCase(nodeName) || "td".equalsIgnoreCase(nodeName) || "div".equalsIgnoreCase(nodeName) || "th".equalsIgnoreCase(nodeName)) && nodeType == Node.ELEMENT_NODE) { replaceResource((Element)node, "background"); } else if (("row".equalsIgnoreCase(nodeName) || "columns".equalsIgnoreCase(nodeName) || "callout".equalsIgnoreCase(nodeName) || "container".equalsIgnoreCase(nodeName) || "wrapper".equalsIgnoreCase(nodeName) || "spacer".equalsIgnoreCase(nodeName) || "callout".equalsIgnoreCase(nodeName)) && nodeType == Node.ELEMENT_NODE) { seenInky = true; } else if ("include".equalsIgnoreCase(nodeName)) { includeResource(node); } else if ("binary-content".equalsIgnoreCase(nodeName)) { node.getParentNode().removeChild(node); } else if (nodeType == Node.TEXT_NODE) { digestHtmlTextNode((Text)node); } if (node.hasAttributes()) digestHtmlAttributes(node.getAttributes()); // Recurse: digestHtmlNodeList(node.getChildNodes()); } private void digestHtmlTextNode(Text text) { // Do nothing right now - this could be a great place // for "BBCode"-style post-processing variable text. if (LOG.isDebugEnabled()) LOG.debug("### '{}'", text.getData()); } private void digestWebLink(Element anchor) { // TODO: implement an alternative markup for <a href="{$public-root}/...">bla bla</a>, // to take some burden (e.g. the root path and the Analytics-tagging) off of the // stylesheets... // E.g.: <weblink action="search.do"> // <parm name="iid" value="166654" /> // <tag name="utm_source" value="searchagent" /> // <tag name="utm_term" value="wegner" /> // etc. // <anchor>bla bla</anchor> // </weblink> // Tag values should be inheritable from outer-level defaults throw new RuntimeException("not yet implemented"); } private void digestStyleAttribute(Attr attr) { String oldStyle = attr.getValue(); String newStyle = digestStyleUrls(oldStyle); if (!oldStyle.equals(newStyle)) { if (LOG.isDebugEnabled()) LOG.debug("### STYLE FIXUP: \"{}\" -> \"{}\"", oldStyle, newStyle); attr.setValue(newStyle); } } private String digestStyleUrls(String style) { Matcher m = CSS_URL_PATTERN.matcher(style); if (!m.matches()) return style; return digestStyleUrls(m.group(1)) + "url(" + cidReference(m.group(2)) + ")" + digestStyleUrls(m.group(3)); } private void replaceResource(Element elem, String resourceAttribute) throws DOMException, IOException { String urlText = elem.getAttribute(resourceAttribute); if (StringUtils.isEmpty(urlText)) { // No source URL specified. Look for embedded <binary-content> instead NodeList children = elem.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); if ("binary-content".equalsIgnoreCase(child.getNodeName())) { String md5 = ((Element)child).getAttribute("md5"); String contentType = ((Element)child).getAttribute("type"); urlText = "mem:/" + md5; MailPartSource binaryContent = (MailPartSource)m_resourceContent.get(urlText); if (binaryContent == null) { String binaryContentBase64 = _text(child); byte bytes[] = Base64.decodeBase64(binaryContentBase64.getBytes()); binaryContent = MailPartSource.from(contentType, md5, bytes); m_resourceContent.put(urlText, binaryContent); } break; } } } if (StringUtils.isEmpty(urlText)) return; String embed = elem.getAttribute("embed"); if (!"false".equals(embed)) { // Embed resource as related MIME part. Replace the URL value by // intra-mail 'cid:'-... reference: String cidRef = cidReference(urlText); elem.setAttribute(resourceAttribute, cidRef); } elem.removeAttribute("embed"); } private String cidReference(String urlText) { // Store the resource content away in m_resources for attachment later, and // replace the URL-attribute by an appropriate intra-mail reference: String partId = m_resources.get(urlText); if (partId == null) { partId = "part." + (m_resources.size() + 1) + "." + System.currentTimeMillis() + "@mail"; m_resources.put(urlText, partId); LOG.debug("{}: resource embedded as MIME part <{}>", urlText, partId); } return "cid:" + partId; } private void includeResource(Node node) throws DOMException, IOException { String urlText = ((Element)node).getAttribute("src"); LOG.debug("{}: embedding resource", urlText); if (!StringUtils.isEmpty(urlText)) { try { URL url = new URL(urlText); InputStream is = url.openStream(); Reader rdr = new InputStreamReader(is, "iso-8859-1"); char buf[] = new char[256]; int count; StringBuilder sb = new StringBuilder(); while ((count = rdr.read(buf)) > 0) sb.append(buf, 0, count); rdr.close(); is.close(); Text res = node.getOwnerDocument().createTextNode(sb.toString()); node.getParentNode().replaceChild(res, node); } catch (MalformedURLException ex) { LOG.error(ex.getMessage(), ex); } } } private String embedResource(String md5, byte content[]) { String key = "local:" + md5; String partId = m_resources.get(key); if (partId == null) { partId = "part." + (m_resources.size() + 1) + "." + System.currentTimeMillis() + "@mail"; m_resources.put(key, partId); LOG.debug("{}: resource embedded as MIME part <{}>", key, partId); } return "cid:" + partId; } private MailPartSource partFromRef(String ref) throws IOException { if (ref.startsWith("mem:")) { return m_resourceContent.get(ref); } else if (ref.startsWith("res:")) { URL url = getClass().getClassLoader().getResource(ref.substring("res:".length())); return MailPartSource.local(url); } else if (ref.startsWith("file:") || ref.startsWith("jar:")) { return MailPartSource.local(new URL(ref)); } else if (ref.startsWith("http:") || ref.startsWith("https:")) { return MailPartSource.remote(new URL(ref)); } else { if (m_baseHref == null) throw new IOException("cannot resolve '"+ref+"' - no <base href=\"...\"> present"); URL src = new URL(m_baseHref, ref); LOG.debug("\"{}\" relative to \"{}\":\n\t\"{}\"", URI.create(ref), m_baseHref, src); try { return MailPartSource.remote(src); } catch (RuntimeException ex) { LOG.error("{}: {}", src, ex.getMessage()); throw ex; } } } } private static String _text(Node n) { StringBuilder result = new StringBuilder(); NodeList children = n.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { String s = children.item(i).getNodeValue(); if (s != null) result.append(s); } return result.toString(); } private static Inky inky; /** * Converts an org.w3c.dom.NodeList to a Java String. * * @param node org.w3c.dom.Node to convert * @param method either "xml", "html", or "text" to control the formatting * @param compact whether or not to maintain line breaks and indentation. Valid * for "xml" and "html" methods only. */ private static String _htmlText(NodeList nodeList, String encoding, boolean useInky, boolean useCssInliner) { if (nodeList.getLength() == 0) return ""; ByteArrayOutputStream out = new ByteArrayOutputStream(); Result result = new StreamResult(out); try { if (useInky) { if (inky == null) inky = new Inky(); for (int i = 0; i < nodeList.getLength(); i++) { Node item = nodeList.item(i); inky.transform(new DOMSource(item), result, useCssInliner); } } else { Transformer s = _serializer(); for (int i = 0; i < nodeList.getLength(); i++) { Node item = nodeList.item(i); s.transform(new DOMSource(item), result); } } return new String(out.toByteArray(), encoding); } catch (UnsupportedEncodingException ex) { throw new RuntimeException("XML serialization error", ex); } catch (TransformerException ex) { throw new RuntimeException("XML transformation error", ex); } } private static Transformer _serializer() { try { Transformer xf = TransformerFactory.newInstance().newTransformer(); xf.setOutputProperty(OutputKeys.METHOD, "html"); xf.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); xf.setOutputProperty(OutputKeys.INDENT, "no"); xf.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); return xf; } catch (TransformerException ex) { throw new RuntimeException("XML serialization error", ex); } } }
package emufog.util; import java.util.concurrent.TimeUnit; public class ConversionsUtils { /** * Converts an interval of start and endpoint to a string * representing the duration in the format e.g. '1h1min1s1ms'. * * @param start start point of the interval in ns * @param end end point of the interval in ns * @return string representation of the interval to print */ public static String intervalToString(long start, long end) { long duration = end - start; duration = Math.max(duration, 0); StringBuilder sb = new StringBuilder(); boolean started = false; long hours = TimeUnit.HOURS.convert(duration, TimeUnit.NANOSECONDS); if (hours > 0) { sb.append(hours).append("h "); started = true; } long minutes = TimeUnit.MINUTES.convert(duration, TimeUnit.NANOSECONDS); if (started || minutes > 0) { sb.append(minutes).append("min "); started = true; } long seconds = TimeUnit.SECONDS.convert(duration, TimeUnit.NANOSECONDS); if (started || seconds > 0) { sb.append(seconds).append("s "); } long milliseconds = TimeUnit.MILLISECONDS.convert(duration, TimeUnit.NANOSECONDS); sb.append(milliseconds).append("ms"); return sb.toString(); } }
// modification, are permitted provided that the following conditions are met: // documentation and/or other materials provided with the distribution. // * Neither the name of the <organization> nor the // names of its contributors may be used to endorse or promote products // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL DAVID J. PEARCE BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package wyc; import static wyil.util.ErrorMessages.CYCLIC_CONSTANT_DECLARATION; import static wyil.util.ErrorMessages.INVALID_BINARY_EXPRESSION; import static wyil.util.ErrorMessages.INVALID_BOOLEAN_EXPRESSION; import static wyil.util.ErrorMessages.INVALID_CONSTANT_EXPRESSION; import static wyil.util.ErrorMessages.INVALID_LIST_EXPRESSION; import static wyil.util.ErrorMessages.INVALID_NUMERIC_EXPRESSION; import static wyil.util.ErrorMessages.INVALID_SET_EXPRESSION; import static wyil.util.ErrorMessages.errorMessage; import static wyil.util.SyntaxError.syntaxError; import static wyil.util.SyntaxError.internalFailure; import java.util.*; import wyautl.lang.*; import wyc.lang.Expr; import wyc.lang.UnresolvedType; import wyc.lang.WhileyFile; import wyc.lang.WhileyFile.Declaration; import wyc.util.Nominal; import wyil.ModuleLoader; import wyil.lang.*; import wyil.util.*; import wyil.util.path.Path; /** * <p> * A Name Resolver is responsible for searching the WHILEYPATH to resolve given * names and packages. For example, we may wish to resolve a name "Reader" * within a given import context of "import whiley.io.*". In such case, the name * resolver will first locate the package "whiley.io", and then decide whether * there is a module named "Reader". * </p> * * * @author David J. Pearce * */ public final class Resolver { private final ModuleLoader loader; /** * A map from module identifiers to WhileyFile objects. This is required to * permit registration of source files during compilation. */ private HashMap<ModuleID, WhileyFile> files = new HashMap<ModuleID, WhileyFile>(); /** * The import cache caches specific import queries to their result sets. * This is extremely important to avoid recomputing these result sets every * time. For example, the statement <code>import whiley.lang.*</code> * corresponds to the triple <code>("whiley.lang",*,null)</code>. */ private HashMap<Triple<PkgID,String,String>,ArrayList<ModuleID>> importCache = new HashMap(); /** * The constant cache contains a cache of expanded constant values. */ HashMap<NameID, Value> constantCache = new HashMap(); public Resolver(ModuleLoader loader) { this.loader = loader; } public void register(WhileyFile WhileyFile) { files.put(WhileyFile.module, WhileyFile); } /** * This function checks whether the supplied package exists or not. * * @param pkg * The package whose existence we want to check for. * * @return true if the package exists, false otherwise. */ public boolean isPackage(PkgID pkg) { try { loader.resolvePackage(pkg); return true; } catch(ResolveError e) { return false; } } /** * This function checks whether the supplied name exists or not. * * @param nid * The name whose existence we want to check for. * * @return true if the package exists, false otherwise. */ public boolean isName(NameID nid) { ModuleID mid = nid.module(); WhileyFile wf = files.get(mid); if(wf != null) { return wf.hasName(nid.name()); } else { try { Module m = loader.loadModule(mid); return m.hasName(nid.name()); } catch(ResolveError e) { return false; } } } /** * This method takes a given import declaration, and expands it to find all * matching modules. * * @param imp * @return */ private List<ModuleID> matchImport(WhileyFile.Import imp) { Triple<PkgID,String,String> key = new Triple(imp.pkg,imp.module,imp.name); ArrayList<ModuleID> matches = importCache.get(key); if(matches != null) { // cache hit return matches; } else { // cache miss matches = new ArrayList<ModuleID>(); for (PkgID pid : matchPackage(imp.pkg)) { try { for(ModuleID mid : loader.loadPackage(pid)) { if (imp.matchModule(mid.module())) { matches.add(mid); } } } catch (ResolveError ex) { // dead code } } importCache.put(key, matches); } return matches; } /** * This method takes a given package id from an import declaration, and * expands it to find all matching packages. Note, the package id may * contain various wildcard characters to match multiple actual packages. * * @param imp * @return */ private List<PkgID> matchPackage(PkgID pkg) { ArrayList<PkgID> matches = new ArrayList<PkgID>(); try { loader.resolvePackage(pkg); matches.add(pkg); } catch(ResolveError er) {} return matches; } // ResolveAsName /** * This methods attempts to resolve the correct package for a named item, * given a list of imports. Resolving the correct package may require * loading modules as necessary from the WHILEYPATH and/or compiling modules * for which only source code is currently available. * * @param name * A module name without package specifier. * @param imports * A list of import declarations to search through. Imports are * searched in order of appearance. * @return The resolved name. * @throws ResolveError * if it couldn't resolve the name */ public NameID resolveAsName(String name, List<WhileyFile.Import> imports) throws ResolveError { for (WhileyFile.Import imp : imports) { if (imp.matchName(name)) { for (ModuleID mid : matchImport(imp)) { NameID nid = new NameID(mid, name); if (isName(nid)) { return nid; } } } } throw new ResolveError("name not found: " + name); } /** * This methods attempts to resolve the given list of names into a single * named item (e.g. type, method, constant, etc). For example, * <code>["whiley","lang","Math","max"]</code> would be resolved, since * <code>whiley.lang.Math.max</code> is a valid function name. In contrast, * <code>["whiley","lang","Math"]</code> does not resolve since * <code>whiley.lang.Math</code> refers to a module. * * @param names * A list of components making up the name, which may include the * package and enclosing module. * @param imports * A list of import declarations to search through. Imports are * searched in order of appearance. * @return The resolved name. * @throws ResolveError * if it couldn't resolve the name */ public NameID resolveAsName(List<String> names, List<WhileyFile.Import> imports) throws ResolveError { if(names.size() == 1) { return resolveAsName(names.get(0),imports); } else if(names.size() == 2) { String name = names.get(1); ModuleID mid = resolveAsModule(names.get(0),imports); NameID nid = new NameID(mid, name); if (isName(nid)) { return nid; } } else { String name = names.get(names.size()-1); String module = names.get(names.size()-2); PkgID pkg = new PkgID(names.subList(0,names.size()-2)); ModuleID mid = new ModuleID(pkg,module); NameID nid = new NameID(mid, name); if (isName(nid)) { return nid; } } String name = null; for(String n : names) { if(name != null) { name = name + "." + n; } else { name = n; } } throw new ResolveError("name not found: " + name); } /** * This method attempts to resolve the given name as a module name, given a * list of imports. * * @param name * @param imports * @return * @throws ResolveError */ public ModuleID resolveAsModule(String name, List<WhileyFile.Import> imports) throws ResolveError { for (WhileyFile.Import imp : imports) { for(ModuleID mid : matchImport(imp)) { if(mid.module().equals(name)) { return mid; } } } throw new ResolveError("module not found: " + name); } // ResolveAsType public Nominal.Function resolveAsType(UnresolvedType.Function t, List<WhileyFile.Import> imports) throws ResolveError { return (Nominal.Function) resolveAsType((UnresolvedType)t,imports); } public Nominal.Method resolveAsType(UnresolvedType.Method t, List<WhileyFile.Import> imports) throws ResolveError { return (Nominal.Method) resolveAsType((UnresolvedType)t,imports); } public Nominal.Message resolveAsType(UnresolvedType.Message t, List<WhileyFile.Import> imports) throws ResolveError { return (Nominal.Message) resolveAsType((UnresolvedType)t,imports); } /** * Resolve a given type by identifying all unknown names and replacing them * with nominal types. * * @param t * @param imports * @return * @throws ResolveError */ public Nominal resolveAsType(UnresolvedType t, List<WhileyFile.Import> imports) throws ResolveError { Type nominalType = resolveAsType(t, imports, true); Type rawType = resolveAsType(t, imports, false); return Nominal.construct(nominalType, rawType); } private Type resolveAsType(UnresolvedType t, List<WhileyFile.Import> imports, boolean nominal) throws ResolveError { if(t instanceof UnresolvedType.Primitive) { if (t instanceof UnresolvedType.Any) { return Type.T_ANY; } else if (t instanceof UnresolvedType.Void) { return Type.T_VOID; } else if (t instanceof UnresolvedType.Null) { return Type.T_NULL; } else if (t instanceof UnresolvedType.Bool) { return Type.T_BOOL; } else if (t instanceof UnresolvedType.Byte) { return Type.T_BYTE; } else if (t instanceof UnresolvedType.Char) { return Type.T_CHAR; } else if (t instanceof UnresolvedType.Int) { return Type.T_INT; } else if (t instanceof UnresolvedType.Real) { return Type.T_REAL; } else if (t instanceof UnresolvedType.Strung) { return Type.T_STRING; } else { throw new ResolveError("unrecognised type encountered (" + t.getClass().getName() + ")"); } } else { ArrayList<Automaton.State> states = new ArrayList<Automaton.State>(); HashMap<NameID,Integer> roots = new HashMap<NameID,Integer>(); resolveAsType(t,imports,states,roots,nominal); return Type.construct(new Automaton(states)); } } /** * The following method resolves a given type using a list of import * statements. * * @param t * @param imports * @return * @throws ResolveError */ private int resolveAsType(UnresolvedType t, List<WhileyFile.Import> imports, ArrayList<Automaton.State> states, HashMap<NameID, Integer> roots, boolean nominal) throws ResolveError { if(t instanceof UnresolvedType.Primitive) { return resolveAsType((UnresolvedType.Primitive)t,imports,states); } int myIndex = states.size(); int myKind; int[] myChildren; Object myData = null; boolean myDeterministic = true; states.add(null); // reserve space for me if(t instanceof UnresolvedType.List) { UnresolvedType.List lt = (UnresolvedType.List) t; myKind = Type.K_LIST; myChildren = new int[1]; myChildren[0] = resolveAsType(lt.element,imports,states,roots,nominal); myData = false; } else if(t instanceof UnresolvedType.Set) { UnresolvedType.Set st = (UnresolvedType.Set) t; myKind = Type.K_SET; myChildren = new int[1]; myChildren[0] = resolveAsType(st.element,imports,states,roots,nominal); myData = false; } else if(t instanceof UnresolvedType.Dictionary) { UnresolvedType.Dictionary st = (UnresolvedType.Dictionary) t; myKind = Type.K_DICTIONARY; myChildren = new int[2]; myChildren[0] = resolveAsType(st.key,imports,states,roots,nominal); myChildren[1] = resolveAsType(st.value,imports,states,roots,nominal); } else if(t instanceof UnresolvedType.Record) { UnresolvedType.Record tt = (UnresolvedType.Record) t; HashMap<String,UnresolvedType> ttTypes = tt.types; Type.Record.State fields = new Type.Record.State(tt.isOpen,ttTypes.keySet()); Collections.sort(fields); myKind = Type.K_RECORD; myChildren = new int[fields.size()]; for(int i=0;i!=fields.size();++i) { String field = fields.get(i); myChildren[i] = resolveAsType(ttTypes.get(field),imports,states,roots,nominal); } myData = fields; } else if(t instanceof UnresolvedType.Tuple) { UnresolvedType.Tuple tt = (UnresolvedType.Tuple) t; ArrayList<UnresolvedType> ttTypes = tt.types; myKind = Type.K_TUPLE; myChildren = new int[ttTypes.size()]; for(int i=0;i!=ttTypes.size();++i) { myChildren[i] = resolveAsType(ttTypes.get(i),imports,states,roots,nominal); } } else if(t instanceof UnresolvedType.Nominal) { // This case corresponds to a user-defined type. This will be // defined in some module (possibly ours), and we need to identify // what module that is here, and save it for future use. UnresolvedType.Nominal dt = (UnresolvedType.Nominal) t; NameID nid = resolveAsName(dt.names, imports); if(nominal) { myKind = Type.K_NOMINAL; myData = nid; myChildren = Automaton.NOCHILDREN; } else { // At this point, we're going to expand the given nominal type. // We're going to use resolveAsType(NameID,...) to do this which // will load the expanded type onto states at the current point. // Therefore, we need to remove the initial null we loaded on. states.remove(myIndex); return resolveAsType(nid,imports,states,roots); } } else if(t instanceof UnresolvedType.Not) { UnresolvedType.Not ut = (UnresolvedType.Not) t; myKind = Type.K_NEGATION; myChildren = new int[1]; myChildren[0] = resolveAsType(ut.element,imports,states,roots,nominal); } else if(t instanceof UnresolvedType.Union) { UnresolvedType.Union ut = (UnresolvedType.Union) t; ArrayList<UnresolvedType.NonUnion> utTypes = ut.bounds; myKind = Type.K_UNION; myChildren = new int[utTypes.size()]; for(int i=0;i!=utTypes.size();++i) { myChildren[i] = resolveAsType(utTypes.get(i),imports,states,roots,nominal); } myDeterministic = false; } else if(t instanceof UnresolvedType.Reference) { UnresolvedType.Reference ut = (UnresolvedType.Reference) t; myKind = Type.K_REFERENCE; myChildren = new int[1]; myChildren[0] = resolveAsType(ut.element,imports,states,roots,nominal); } else { UnresolvedType.FunctionOrMethodOrMessage ut = (UnresolvedType.FunctionOrMethodOrMessage) t; ArrayList<UnresolvedType> utParamTypes = ut.paramTypes; UnresolvedType receiver = null; int start = 0; if(ut instanceof UnresolvedType.Message) { UnresolvedType.Message mt = (UnresolvedType.Message) ut; receiver = mt.receiver; myKind = Type.K_MESSAGE; start++; } else if(ut instanceof UnresolvedType.Method) { myKind = Type.K_METHOD; } else { myKind = Type.K_FUNCTION; } myChildren = new int[start + 2 + utParamTypes.size()]; if(receiver != null) { myChildren[0] = resolveAsType(receiver,imports,states,roots,nominal); } myChildren[start++] = resolveAsType(ut.ret,imports,states,roots,nominal); if(ut.throwType == null) { // this case indicates the user did not provide a throws clause. myChildren[start++] = resolveAsType(new UnresolvedType.Void(),imports,states,roots,nominal); } else { myChildren[start++] = resolveAsType(ut.throwType,imports,states,roots,nominal); } for(UnresolvedType pt : utParamTypes) { myChildren[start++] = resolveAsType(pt,imports,states,roots,nominal); } } states.set(myIndex,new Automaton.State(myKind,myData,myDeterministic,myChildren)); return myIndex; } private int resolveAsType(NameID key, List<WhileyFile.Import> imports, ArrayList<Automaton.State> states, HashMap<NameID, Integer> roots) throws ResolveError { // First, check the various caches we have Integer root = roots.get(key); if (root != null) { return root; } // check whether this type is external or not WhileyFile wf = files.get(key.module()); if (wf == null) { // indicates a non-local key which we can resolve immediately Module mi = loader.loadModule(key.module()); Module.TypeDef td = mi.type(key.name()); return append(td.type(),states); } WhileyFile.TypeDef td = wf.typeDecl(key.name()); if(td == null) { Value v = resolveAsConstant(key); Type t = v.type(); if(t instanceof Type.Set) { Type.Set ts = (Type.Set) t; // FIXME: add constraints return append(ts.element(),states); } else { // FIXME: need a better error message! throw new ResolveError("type not found: " + key.name()); } } // following is needed to terminate any recursion roots.put(key, states.size()); UnresolvedType type = td.unresolvedType; // now, expand the given type fully if(type instanceof Type.Leaf) { // to avoid unnecessarily creating an array of size one int myIndex = states.size(); int kind = Type.leafKind((Type.Leaf)type); Object data = Type.leafData((Type.Leaf)type); states.add(new Automaton.State(kind,data,true,Automaton.NOCHILDREN)); return myIndex; } else { return resolveAsType(type,imports,states,roots,false); } // TODO: performance can be improved here, but actually assigning the // constructed type into a cache of previously expanded types cache. // This is challenging, in the case that the type may not be complete at // this point. In particular, if it contains any back-links above this // index there could be an issue. } private int resolveAsType(UnresolvedType.Primitive t, List<WhileyFile.Import> imports, ArrayList<Automaton.State> states) throws ResolveError { int myIndex = states.size(); int kind; if (t instanceof UnresolvedType.Any) { kind = Type.K_ANY; } else if (t instanceof UnresolvedType.Void) { kind = Type.K_VOID; } else if (t instanceof UnresolvedType.Null) { kind = Type.K_NULL; } else if (t instanceof UnresolvedType.Bool) { kind = Type.K_BOOL; } else if (t instanceof UnresolvedType.Byte) { kind = Type.K_BYTE; } else if (t instanceof UnresolvedType.Char) { kind = Type.K_CHAR; } else if (t instanceof UnresolvedType.Int) { kind = Type.K_INT; } else if (t instanceof UnresolvedType.Real) { kind = Type.K_RATIONAL; } else if (t instanceof UnresolvedType.Strung) { kind = Type.K_STRING; } else { throw new ResolveError("unrecognised type encountered (" + t.getClass().getName() + ")"); } states.add(new Automaton.State(kind, null, true, Automaton.NOCHILDREN)); return myIndex; } private static int append(Type type, ArrayList<Automaton.State> states) { int myIndex = states.size(); Automaton automaton = Type.destruct(type); Automaton.State[] tStates = automaton.states; int[] rmap = new int[tStates.length]; for (int i = 0, j = myIndex; i != rmap.length; ++i, ++j) { rmap[i] = j; } for (Automaton.State state : tStates) { states.add(Automata.remap(state, rmap)); } return myIndex; } // ResolveAsConstant public Value resolveAsConstant(NameID nid) throws ResolveError { return resolveAsConstant(nid,new HashSet<NameID>()); } public Value resolveAsConstant(Expr e, String filename, List<WhileyFile.Import> imports) throws ResolveError { return resolveAsConstant(e,filename,imports,new HashSet<NameID>()); } private Value resolveAsConstant(NameID key, HashSet<NameID> visited) throws ResolveError { // FIXME: cyclic constants Value result = constantCache.get(key); if(result != null) { return result; } else if(visited.contains(key)) { throw new ResolveError("cyclic constant definition encountered (" + key + " -> " + key + ")"); } else { visited.add(key); } WhileyFile wf = files.get(key.module()); if (wf != null) { WhileyFile.Declaration decl = wf.declaration(key.name()); if(decl instanceof WhileyFile.Constant) { WhileyFile.Constant cd = (WhileyFile.Constant) decl; if (cd.resolvedValue == null) { cd.resolvedValue = resolveAsConstant(cd.constant, wf.filename, buildImports(wf, cd), visited); } result = cd.resolvedValue; } else { throw new ResolveError("unable to find constant " + key); } } else { Module module = loader.loadModule(key.module()); Module.ConstDef cd = module.constant(key.name()); if(cd != null) { result = cd.constant(); } else { throw new ResolveError("unable to find constant " + key); } } constantCache.put(key, result); return result; } private Value resolveAsConstant(Expr expr, String filename, List<WhileyFile.Import> imports, HashSet<NameID> visited) throws ResolveError { try { if (expr instanceof Expr.Constant) { Expr.Constant c = (Expr.Constant) expr; return c.value; } else if (expr instanceof Expr.AbstractVariable) { Expr.AbstractVariable av = (Expr.AbstractVariable) expr; NameID nid = resolveAsName(av.var,imports); return resolveAsConstant(nid,visited); } else if (expr instanceof Expr.BinOp) { Expr.BinOp bop = (Expr.BinOp) expr; Value lhs = resolveAsConstant(bop.lhs, filename, imports, visited); Value rhs = resolveAsConstant(bop.rhs, filename, imports, visited); return evaluate(bop,lhs,rhs,filename); } else if (expr instanceof Expr.Set) { Expr.Set nop = (Expr.Set) expr; ArrayList<Value> values = new ArrayList<Value>(); for (Expr arg : nop.arguments) { values.add(resolveAsConstant(arg,filename,imports, visited)); } return Value.V_SET(values); } else if (expr instanceof Expr.List) { Expr.List nop = (Expr.List) expr; ArrayList<Value> values = new ArrayList<Value>(); for (Expr arg : nop.arguments) { values.add(resolveAsConstant(arg,filename,imports, visited)); } return Value.V_LIST(values); } else if (expr instanceof Expr.Record) { Expr.Record rg = (Expr.Record) expr; HashMap<String,Value> values = new HashMap<String,Value>(); for(Map.Entry<String,Expr> e : rg.fields.entrySet()) { Value v = resolveAsConstant(e.getValue(),filename,imports,visited); if(v == null) { return null; } values.put(e.getKey(), v); } return Value.V_RECORD(values); } else if (expr instanceof Expr.Tuple) { Expr.Tuple rg = (Expr.Tuple) expr; ArrayList<Value> values = new ArrayList<Value>(); for(Expr e : rg.fields) { Value v = resolveAsConstant(e, filename, imports,visited); if(v == null) { return null; } values.add(v); } return Value.V_TUPLE(values); } else if (expr instanceof Expr.Dictionary) { Expr.Dictionary rg = (Expr.Dictionary) expr; HashSet<Pair<Value,Value>> values = new HashSet<Pair<Value,Value>>(); for(Pair<Expr,Expr> e : rg.pairs) { Value key = resolveAsConstant(e.first(), filename, imports,visited); Value value = resolveAsConstant(e.second(), filename, imports,visited); if(key == null || value == null) { return null; } values.add(new Pair<Value,Value>(key,value)); } return Value.V_DICTIONARY(values); } else if(expr instanceof Expr.AbstractFunctionOrMethodOrMessage) { Expr.AbstractFunctionOrMethodOrMessage f = (Expr.AbstractFunctionOrMethodOrMessage) expr; // FIXME: consider function parameters as well Pair<NameID,Nominal.FunctionOrMethod> p = resolveAsFunctionOrMethod(f.name, imports); Type.FunctionOrMethod fmt = p.second().raw(); return Value.V_FUN(p.first(),p.second().raw()); } } catch(SyntaxError.InternalFailure e) { throw e; } catch(Throwable e) { internalFailure("internal failure",filename,expr,e); } internalFailure("unknown constant expression (" + expr.getClass().getName() + ")",filename,expr); return null; // deadcode } private Value evaluate(Expr.BinOp bop, Value v1, Value v2, String filename) { Type lub = Type.Union(v1.type(), v2.type()); // FIXME: there are bugs here related to coercions. if(Type.isSubtype(Type.T_BOOL, lub)) { return evaluateBoolean(bop,(Value.Bool) v1,(Value.Bool) v2, filename); } else if(Type.isSubtype(Type.T_REAL, lub)) { return evaluate(bop,(Value.Rational) v1, (Value.Rational) v2, filename); } else if(Type.isSubtype(Type.List(Type.T_ANY, false), lub)) { return evaluate(bop,(Value.List)v1,(Value.List)v2, filename); } else if(Type.isSubtype(Type.Set(Type.T_ANY, false), lub)) { return evaluate(bop,(Value.Set) v1, (Value.Set) v2, filename); } syntaxError(errorMessage(INVALID_BINARY_EXPRESSION),filename,bop); return null; } private Value evaluateBoolean(Expr.BinOp bop, Value.Bool v1, Value.Bool v2, String filename) { switch(bop.op) { case AND: return Value.V_BOOL(v1.value & v2.value); case OR: return Value.V_BOOL(v1.value | v2.value); case XOR: return Value.V_BOOL(v1.value ^ v2.value); } syntaxError(errorMessage(INVALID_BOOLEAN_EXPRESSION),filename,bop); return null; } private Value evaluate(Expr.BinOp bop, Value.Rational v1, Value.Rational v2, String filename) { switch(bop.op) { case ADD: return Value.V_RATIONAL(v1.value.add(v2.value)); case SUB: return Value.V_RATIONAL(v1.value.subtract(v2.value)); case MUL: return Value.V_RATIONAL(v1.value.multiply(v2.value)); case DIV: return Value.V_RATIONAL(v1.value.divide(v2.value)); case REM: return Value.V_RATIONAL(v1.value.intRemainder(v2.value)); } syntaxError(errorMessage(INVALID_NUMERIC_EXPRESSION),filename,bop); return null; } private Value evaluate(Expr.BinOp bop, Value.List v1, Value.List v2, String filename) { switch(bop.op) { case ADD: ArrayList<Value> vals = new ArrayList<Value>(v1.values); vals.addAll(v2.values); return Value.V_LIST(vals); } syntaxError(errorMessage(INVALID_LIST_EXPRESSION),filename,bop); return null; } private Value evaluate(Expr.BinOp bop, Value.Set v1, Value.Set v2, String filename) { switch(bop.op) { case UNION: { HashSet<Value> vals = new HashSet<Value>(v1.values); vals.addAll(v2.values); return Value.V_SET(vals); } case INTERSECTION: { HashSet<Value> vals = new HashSet<Value>(); for(Value v : v1.values) { if(v2.values.contains(v)) { vals.add(v); } } return Value.V_SET(vals); } case SUB: { HashSet<Value> vals = new HashSet<Value>(); for(Value v : v1.values) { if(!v2.values.contains(v)) { vals.add(v); } } return Value.V_SET(vals); } } syntaxError(errorMessage(INVALID_SET_EXPRESSION),filename,bop); return null; } // BindFunction and BindMessage /** * Responsible for determining the true type of a method or function being * invoked. In this case, no argument types are given. This means that any * match is returned. However, if there are multiple matches, then an * ambiguity error is reported. * * @param nid * @param qualification * @param parameters * @param elem * @return * @throws ResolveError */ public Pair<NameID,Nominal.FunctionOrMethod> resolveAsFunctionOrMethod(String name, List<WhileyFile.Import> imports) throws ResolveError { return resolveAsFunctionOrMethod(name,null,imports); } /** * Responsible for determining the true type of a method, function or * message. In this case, no argument types are given. This means that any * match is returned. However, if there are multiple matches, then an * ambiguity error is reported. * * @param nid * @param qualification * @param parameters * @param elem * @return * @throws ResolveError */ public Pair<NameID,Nominal.FunctionOrMethodOrMessage> resolveAsFunctionOrMethodOrMessage(String name, List<WhileyFile.Import> imports) throws ResolveError { try { return (Pair) resolveAsFunctionOrMethod(name,null,imports); } catch(ResolveError e) { return (Pair) resolveAsMessage(name,null,null,imports); } } /** * Responsible for determining the true type of a method or function being * invoked. To do this, it must find the function/method with the most * precise type that matches the argument types. * * @param nid * @param qualification * @param parameters * @param elem * @return * @throws ResolveError */ public Pair<NameID,Nominal.FunctionOrMethod> resolveAsFunctionOrMethod(String name, List<Nominal> parameters, List<WhileyFile.Import> imports) throws ResolveError { ArrayList<Pair<NameID,Nominal.FunctionOrMethod>> candidates = new ArrayList(); // first, try to find the matching message for (WhileyFile.Import imp : imports) { if (imp.matchName(name)) { for (ModuleID mid : matchImport(imp)) { NameID nid = new NameID(mid,name); addCandidateFunctionsAndMethods(nid,parameters,candidates); } } } return selectCandidateFunctionOrMethod(name,parameters,candidates); } /** * Responsible for determining the true type of a method or function being * invoked. To do this, it must find the function/method with the most * precise type that matches the argument types. * * @param nid * @param qualification * @param parameters * @param elem * @return * @throws ResolveError */ public Nominal.FunctionOrMethod resolveAsFunctionOrMethod(NameID nid, List<Nominal> parameters) throws ResolveError { ArrayList<Pair<NameID, Nominal.FunctionOrMethod>> candidates = new ArrayList(); addCandidateFunctionsAndMethods(nid, parameters, candidates); return selectCandidateFunctionOrMethod(nid.name(), parameters, candidates).second(); } public Pair<NameID,Nominal.Message> resolveAsMessage(String name, Type.Reference receiver, List<Nominal> parameters, List<WhileyFile.Import> imports) throws ResolveError { ArrayList<Pair<NameID,Nominal.Message>> candidates = new ArrayList<Pair<NameID,Nominal.Message>>(); // first, try to find the matching message for (WhileyFile.Import imp : imports) { if (imp.matchName(name)) { for (ModuleID mid : matchImport(imp)) { NameID nid = new NameID(mid,name); addCandidateMessages(nid,parameters,candidates); } } } return selectCandidateMessage(name,receiver,parameters,candidates); } public Nominal.Message resolveAsMessage(NameID nid, Type.Reference receiver, List<Nominal> parameters) throws ResolveError { ArrayList<Pair<NameID, Nominal.Message>> candidates = new ArrayList<Pair<NameID, Nominal.Message>>(); addCandidateMessages(nid, parameters, candidates); return selectCandidateMessage(nid.name(), receiver, parameters, candidates).second(); } private boolean paramSubtypes(Type.FunctionOrMethodOrMessage f1, Type.FunctionOrMethodOrMessage f2) { List<Type> f1_params = f1.params(); List<Type> f2_params = f2.params(); if(f1_params.size() == f2_params.size()) { for(int i=0;i!=f1_params.size();++i) { Type f1_param = f1_params.get(i); Type f2_param = f2_params.get(i); if(!Type.isImplicitCoerciveSubtype(f1_param,f2_param)) { return false; } } return true; } return false; } private String parameterString(List<Nominal> paramTypes) { String paramStr = "("; boolean firstTime = true; if(paramTypes == null) { paramStr += "..."; } else { for(Nominal t : paramTypes) { if(!firstTime) { paramStr += ","; } firstTime=false; paramStr += t.nominal(); } } return paramStr + ")"; } private Pair<NameID,Nominal.FunctionOrMethod> selectCandidateFunctionOrMethod(String name, List<Nominal> parameters, ArrayList<Pair<NameID, Nominal.FunctionOrMethod>> candidates) throws ResolveError { List<Type> rawParameters; Type.Function target; if (parameters != null) { rawParameters = stripNominal(parameters); target = (Type.Function) Type.Function(Type.T_ANY, Type.T_ANY, rawParameters); } else { rawParameters = null; target = null; } NameID candidateID = null; Nominal.FunctionOrMethod candidateType = null; for (Pair<NameID,Nominal.FunctionOrMethod> p : candidates) { Nominal.FunctionOrMethod nft = p.second(); Type.FunctionOrMethod ft = nft.raw(); if (parameters == null || (ft.params().size() == parameters.size() && paramSubtypes( ft, target))) { // this is now a genuine candidate if(candidateType == null || paramSubtypes(candidateType.raw(), ft)) { candidateType = nft; candidateID = p.first(); } else if(!paramSubtypes(ft, candidateType.raw())){ // this is an ambiguous error String msg = name + parameterString(parameters) + " is ambiguous"; // FIXME: should report all ambiguous matches here msg += "\n\tfound: " + candidateID + " : " + candidateType.nominal(); msg += "\n\tfound: " + p.first() + " : " + p.second().nominal(); throw new ResolveError(msg); } } } if(candidateType == null) { // second, didn't find matching message so generate error message String msg = "no match for " + name + parameterString(parameters); for (Pair<NameID, Nominal.FunctionOrMethod> p : candidates) { msg += "\n\tfound: " + p.first() + " : " + p.second().nominal(); } throw new ResolveError(msg); } return new Pair(candidateID,candidateType); } private Pair<NameID,Nominal.Message> selectCandidateMessage(String name, Type.Reference receiver, List<Nominal> parameters, ArrayList<Pair<NameID, Nominal.Message>> candidates) throws ResolveError { List<Type> rawParameters; Type.Function target; if (parameters != null) { rawParameters = stripNominal(parameters); target = (Type.Function) Type.Function(Type.T_ANY, Type.T_ANY, rawParameters); } else { rawParameters = null; target = null; } NameID candidateID = null; Nominal.Message candidateType = null; for (Pair<NameID,Nominal.Message> p : candidates) { Nominal.Message nmt = p.second(); Type.Message mt = nmt.raw(); Type funrec = mt.receiver(); if (receiver == funrec || receiver == null || (funrec != null && Type .isImplicitCoerciveSubtype(receiver, funrec))) { // receivers match up OK ... if (parameters == null || (mt.params().size() == parameters.size() && paramSubtypes( mt, target))) { // this is now a genuine candidate if(candidateType == null || paramSubtypes(candidateType.raw(), mt)) { candidateType = nmt; candidateID = p.first(); } else if(!paramSubtypes(mt, candidateType.raw())) { // this is an ambiguous error String msg = name + parameterString(parameters) + " is ambiguous"; // FIXME: should report all ambiguous matches here msg += "\n\tfound: " + candidateID + " : " + candidateType.nominal(); msg += "\n\tfound: " + p.first() + " : " + p.second().nominal(); throw new ResolveError(msg); } } } } if (candidateType == null) { // second, didn't find matching message so generate error message String msg = "no match for " + receiver + "::" + name + parameterString(parameters); for (Pair<NameID, Nominal.Message> p : candidates) { msg += "\n\tfound: " + p.first() + " : " + p.second().nominal(); } throw new ResolveError(msg); } return new Pair(candidateID,candidateType); } private void addCandidateFunctionsAndMethods(NameID nid, List<?> parameters, ArrayList<Pair<NameID, Nominal.FunctionOrMethod>> candidates) throws ResolveError { ModuleID mid = nid.module(); int nparams = parameters != null ? parameters.size() : -1; WhileyFile wf = files.get(mid); if(wf != null) { // FIXME: need to include methods here as well for (WhileyFile.FunctionOrMethod f : wf.declarations( WhileyFile.FunctionOrMethod.class, nid.name())) { if (nparams == -1 || f.parameters.size() == nparams) { Nominal.FunctionOrMethod ft = (Nominal.FunctionOrMethod) resolveAsType(f.unresolvedType(),buildImports(wf,f)); candidates.add(new Pair(nid,ft)); } } } else { try { Module m = loader.loadModule(mid); for(Module.Method mm : m.methods()) { if ((mm.isFunction() || mm.isMethod()) && mm.name().equals(nid.name()) && (nparams == -1 || mm.type().params().size() == nparams)) { // FIXME: loss of nominal information Type.FunctionOrMethod t = (Type.FunctionOrMethod) mm.type(); Nominal.FunctionOrMethod fom; if(t instanceof Type.Function) { Type.Function ft = (Type.Function) t; fom = new Nominal.Function(ft,ft); } else { Type.Method mt = (Type.Method) t; fom = new Nominal.Method(mt,mt); } candidates.add(new Pair(nid,fom)); } } } catch(ResolveError e) { } } } private void addCandidateMessages(NameID nid, List<?> parameters, ArrayList<Pair<NameID, Nominal.Message>> candidates) throws ResolveError { ModuleID mid = nid.module(); int nparams = parameters != null ? parameters.size() : -1; WhileyFile wf = files.get(mid); if(wf != null) { // FIXME: need to include methods here as well for (WhileyFile.Message m : wf.declarations( WhileyFile.Message.class, nid.name())) { if (nparams == -1 || m.parameters.size() == nparams) { Nominal.Message ft = (Nominal.Message) resolveAsType(m.unresolvedType(),buildImports(wf,m)); candidates.add(new Pair(nid,ft)); } } } else { try { Module m = loader.loadModule(mid); for (Module.Method mm : m.methods()) { if (mm.isMessage() && mm.name().equals(nid.name()) && (nparams == -1 || mm.type().params().size() == nparams)) { // FIXME: loss of nominal information Nominal.Message ft = new Nominal.Message( mm.type(), (Type.Message) mm.type()); candidates.add(new Pair(nid, ft)); } } } catch(ResolveError e) { } } } private ArrayList<WhileyFile.Import> buildImports(WhileyFile wf, WhileyFile.Declaration decl) { ModuleID mid = wf.module; ArrayList<WhileyFile.Import> imports = new ArrayList<WhileyFile.Import>(); for (Declaration d : wf.declarations) { if (d instanceof WhileyFile.Import) { imports.add((WhileyFile.Import) d); } if (d == decl) { break; } } imports.add(new WhileyFile.Import(new PkgID("whiley","lang"), "*", null)); imports.add(new WhileyFile.Import(mid.pkg(), "*", null)); imports.add(new WhileyFile.Import(mid.pkg(), mid.module(), "*")); Collections.reverse(imports); return imports; } private static List<Type> stripNominal(List<Nominal> types) { ArrayList<Type> r = new ArrayList<Type>(); for (Nominal t : types) { r.add(t.raw()); } return r; } }
package japsa.bio.np; import japsa.seq.Alphabet; import japsa.seq.Alphabet.DNA; import japsa.seq.FastaReader; import japsa.seq.Sequence; import japsa.seq.SequenceBuilder; import japsa.seq.SequenceOutputStream; import japsa.seq.SequenceReader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; /** * Provides functionality for error correction and find the best allele/sequence. * Potentially will use HMM/FSM * * @author minhduc * * */ public class ErrorCorrection { private static final Logger LOG = LoggerFactory.getLogger(ErrorCorrection.class); public static String prefix = "tmp"; public static String msa = "kalign"; public static double needle(Sequence seq1, Sequence seq2, String prefix) throws IOException, InterruptedException{ String seq1File = prefix + seq1.getName() + ".fasta"; String seq2File = prefix + seq2.getName() + ".fasta"; seq1.writeFasta(seq1File); seq2.writeFasta(seq2File); String needleOut = prefix + "_alignment.needle"; String cmd = "needle -gapopen 10 -gapextend 0.5 -asequence " + seq1File + " -bsequence " + seq2File + " -outfile " + needleOut; LOG.info("Running " + cmd); Process process = Runtime.getRuntime().exec(cmd); process.waitFor(); LOG.info("Run'ed " + cmd ); BufferedReader scoreBf = new BufferedReader(new FileReader(needleOut)); String scoreLine = null; double score = 0; while ((scoreLine = scoreBf.readLine())!=null){ String [] scoreToks = scoreLine.split(" "); if (scoreToks.length == 3 && scoreToks[1].equals("Score:")){ score = Double.parseDouble(scoreToks[2]); break;//while } }//while scoreBf.close(); return score; } public static Sequence consensusSequence(ArrayList<Sequence> readList, String prefix, String msa) throws IOException, InterruptedException{ if (readList != null && readList.size() > 0) return consensusSequence(readList, readList.size(), prefix, msa); else return null; } public static Sequence consensusSequence(ArrayList<Sequence> readList, int max, String prefix, String msa) throws IOException, InterruptedException{ //String faiFile = prefix + "_" + this.currentReadCount; Sequence consensus = null; if (readList != null && readList.size() > 0){ //1.0 write alignment to faiFile if (readList.size() == 1){ readList.get(0).setName("consensus"); consensus = readList.get(0); }else{ String faiFile = prefix + "_ai.fasta";//name of fasta files of reads mapped to the gene String faoFile = prefix + "_ao.fasta";//name of fasta files of reads mapped to the gene { SequenceOutputStream faiSt = SequenceOutputStream.makeOutputStream(faiFile); int count = 0; for (Sequence seq:readList){ LOG.info(seq.getName() + " " + seq.length()); seq.writeFasta(faiSt); count ++; if (count >= max) break;//for } faiSt.close(); } //2.0 Run multiple alignment { String cmd = ""; if (msa.startsWith("poa")){ cmd = "poa -read_fasta " + faiFile + " -clustal " + faoFile + " -hb blosum80.mat"; }else if (msa.startsWith("muscle")){ cmd = "muscle -in " + faiFile + " -out " + faoFile + " -maxiters 5 -quiet"; }else if (msa.startsWith("clustal")) { cmd = "clustalo --force -i " + faiFile + " -o " + faoFile; }else if (msa.startsWith("kalign")){ cmd = "kalign -gpo 60 -gpe 10 -tgpe 0 -bonus 0 -q -i " + faiFile + " -o " + faoFile; }else if (msa.startsWith("msaprobs")){ cmd = "msaprobs -o " + faoFile + " " + faiFile; }else if (msa.startsWith("mafft")){ cmd = "mafft_wrapper.sh " + faiFile + " " + faoFile; }else{ LOG.error("Unknown msa function " + msa); return null; } LOG.info("Running " + cmd); Process process = Runtime.getRuntime().exec(cmd); process.waitFor(); LOG.info("Done " + cmd); } if ("poa".equals(msa)){ SequenceBuilder sb = new SequenceBuilder(Alphabet.DNA(), readList.get(0).length()); BufferedReader bf = FastaReader.openFile(faoFile); String line = bf.readLine(); while ( (line = bf.readLine()) != null){ if (line.startsWith("CONSENS0")){ for (int i = 10;i < line.length();i++){ char c = line.charAt(i); int base = DNA.DNA().char2int(c); if (base >= 0 && base < 4) sb.append((byte)base); }//for } }//while sb.setName("consensus"); LOG.info(sb.getName() + " " + sb.length()); return sb.toSequence(); } //3.0 Read in multiple alignment ArrayList<Sequence> seqList = new ArrayList<Sequence>(); { SequenceReader msaReader = FastaReader.getReader(faoFile); Sequence nSeq = null; while ((nSeq = msaReader.nextSequence(Alphabet.DNA())) != null) { seqList.add(nSeq); } msaReader.close(); } //4.0 get consensus and write to facFile { int [] coef = new int[seqList.size()]; for (int y = 0; y < seqList.size(); y++){ coef[y] = 1; //if (seqList.get(y).getName().contains("twodi")) // coef[y] = 2; } //TODO: combine error profiles?? int [] counts = new int[6]; SequenceBuilder sb = new SequenceBuilder(Alphabet.DNA(), seqList.get(0).length()); for (int x = 0; x < seqList.get(0).length();x++){ Arrays.fill(counts, 0); for (int y = 0; y < seqList.size(); y++){ byte base = seqList.get(y).getBase(x); if (base >= 6) counts[4] += coef[y]; else counts[base] += coef[y]; }//for y int maxIdx = 0; for (int y = 1; y < counts.length; y++){ if (counts[y] > counts[maxIdx]) maxIdx = y; }//for y if (maxIdx < Alphabet.DNA.GAP){//not a gap sb.append((byte)maxIdx); } }//for x sb.setName("consensus"); LOG.info(sb.getName() + " " + sb.length()); consensus = sb.toSequence(); } } } return consensus; } }
package kodkod.engine; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import kodkod.ast.Expression; import kodkod.ast.Formula; import kodkod.ast.Relation; import kodkod.engine.config.ExtendedOptions; import kodkod.engine.config.Options; import kodkod.engine.config.Reporter; import kodkod.engine.satlab.ExternalSolver; import kodkod.engine.unbounded.ElectrodPrinter; import kodkod.engine.unbounded.ElectrodReader; import kodkod.engine.unbounded.InvalidUnboundedProblem; import kodkod.engine.unbounded.InvalidUnboundedSolution; import kodkod.instance.PardinusBounds; import kodkod.instance.TemporalInstance; /** * A computational engine for solving unbounded temporal relational * satisfiability problems. Such a problem is described by a * {@link kodkod.ast.Formula formula} in first order temporal relational logic; * finite unbounded temporal {@link PardinusBounds bounds} on the value of each * {@link Relation relation} constrained by the respective formula; and a set of * {@link ExtendedOptions options}, although there are currently no particular * options for unbounded temporal solving. * * <p> * An {@link ElectrodSolver} takes as input a relational problem and produces a * satisfying model or a {@link TemporalInstance temporal instance} of it, if * one exists. * </p> * * <p> * Iteration over Electrod is implemented through the "formulation" of the * previous temporal instance, introducing its negation into the formula, and * restarting the solver. * </p> * * @author Nuno Macedo // [HASLab] unbounded temporal model finding */ public class ElectrodSolver implements UnboundedSolver<ExtendedOptions>, TemporalSolver<ExtendedOptions>, IterableSolver<PardinusBounds, ExtendedOptions> { private final ExtendedOptions options; /** * Constructs a new Electrod solver with the given options. * * @param options the solver options. * @throws NullPointerException * options = null */ public ElectrodSolver(ExtendedOptions options) { if (options == null) throw new NullPointerException(); this.options = options; } /** * {@inheritDoc} */ public ExtendedOptions options() { return options; } /** * {@inheritDoc} */ public Solution solve(Formula formula, PardinusBounds bounds) throws InvalidUnboundedProblem, InvalidUnboundedSolution { return ElectrodSolver.go(formula,bounds,options); } /** * {@inheritDoc} */ public Iterator<Solution> solveAll(Formula formula, PardinusBounds bounds) { return new SolutionIterator(formula, bounds, options); } private final static class SolutionIterator implements Iterator<Solution> { private Formula formula; private final PardinusBounds bounds; private Map<Object,Expression> reifs; private ExtendedOptions options; SolutionIterator(Formula formula, PardinusBounds bounds, ExtendedOptions options) { // [HASLab] this.formula = formula; this.reifs = new HashMap<Object,Expression>(); this.bounds = bounds; this.options = options; } @Override public boolean hasNext() { return formula != null; } @Override public Solution next() { Solution s = go(formula,bounds,options); if (s.sat()) { Formula trns = s.instance().formulate(bounds,reifs,formula).not(); options.reporter().debug("Reified instance: "+trns); formula = formula.and(trns); } else formula = null; return s; } } /** * Effectively launches an Electrod process. Used at single solve and at * iteration, since the process is restarted. * * @param formula * @param bounds * @param options * @return a solution to the problem */ private static Solution go(Formula formula, PardinusBounds bounds, ExtendedOptions options) { Reporter rep = options.reporter(); // if not decomposed, use the amalgamated if any if (!options.decomposed() && bounds.amalgamated!=null) bounds = bounds.amalgamated(); // create a directory with the specified unique name String temp=System.getProperty("java.io.tmpdir"); File dir = new File(temp+File.separatorChar+options.uniqueName()); if (!dir.exists()) dir.mkdir(); String file = dir.toString()+File.separatorChar+String.format("%05d", bounds.integration); PrintWriter writer; try { if (!Options.isDebug()) new File(file+".elo").deleteOnExit(); writer = new PrintWriter(file+".elo"); String electrod = ElectrodPrinter.print(formula, bounds, rep); writer.println(electrod); writer.close(); rep.debug("New Electrod problem at "+dir+"."); } catch (FileNotFoundException e) { throw new AbortedException("Electrod problem generation failed.", e); } ProcessBuilder builder; List<String> args = new ArrayList<String>(); args.add(((ExternalSolver) options.solver().instance()).executable); args.addAll(Arrays.asList(((ExternalSolver) options.solver().instance()).options)); if (!options.unbounded()) { if (options.minTraceLength() != 1) throw new IllegalArgumentException("BMC trace length must start at 1."); args.add("--bmc"); args.add(options.maxTraceLength()+""); } args.add(Options.isDebug()?"-v":" args.add(file+".elo"); builder = new ProcessBuilder(args); builder.environment().put("PATH", builder.environment().get("PATH")); builder.redirectErrorStream(true); int ret = -1; final Process p; try { options.reporter().solvingCNF(-1, -1, -1); p = builder.start(); // stores the pid so that it can be correctly terminated Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { if (!System.getProperty("os.name").toLowerCase(Locale.US).startsWith("windows")) try { Field f = p.getClass().getDeclaredField("pid"); f.setAccessible(true); Runtime.getRuntime().exec("kill -SIGTERM " + f.get(p)); } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException | IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } else p.destroy(); } }); try { BufferedReader output = new BufferedReader(new InputStreamReader( p.getInputStream())); String oline = ""; while ((oline = output.readLine()) != null) rep.debug(oline); ret = p.waitFor(); } catch (InterruptedException e) { p.destroy(); throw new AbortedException("Electrod problem interrupted.", e); } } catch (IOException e1) { throw new AbortedException("Electrod problem failed.", e1); } if (ret != 0) { rep.warning("Electrod exit code: "+ret); throw new AbortedException("Electrod exit code: "+ret); } else rep.debug("Electrod ran successfully."); File xml = new File(file+".xml"); if (!Options.isDebug()) xml.deleteOnExit(); if (!xml.exists()) throw new AbortedException("XML solution file not found: "+file+".xml."); else { rep.debug(file); ElectrodReader rd = new ElectrodReader(bounds); TemporalInstance res = rd.read(xml); Statistics st = new Statistics(rd.nbvars, 0,0, rd.ctime, rd.atime); Solution sol; // ElectrodReader#read returns null if unsat if (res == null) sol = Solution.unsatisfiable(st, null); else sol = Solution.satisfiable(st, res); return sol; } } /** * {@inheritDoc} */ public void free() {} }
package logbook.internal; import java.awt.Desktop; import java.io.InputStream; import java.net.URI; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import javafx.application.Platform; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.ButtonType; import logbook.bean.AppConfig; import logbook.plugin.lifecycle.StartUp; public class CheckUpdate implements StartUp { private static final String[] CHECK_SITES = { "https://kancolle.sanaechan.net/logbook-kai.txt", "http://kancolle.sanaechan.net/logbook-kai.txt" }; @Override public void run() { if (!AppConfig.get().isCheckUpdate()) { return; } for (String checkSite : CHECK_SITES) { URI uri = URI.create(checkSite); try (InputStream in = uri.toURL().openStream()) { byte[] b = new byte[1024]; int l = in.read(b, 0, b.length); String str = new String(b, 0, l); Version newversion = new Version(str); if (Version.getCurrent().compareTo(newversion) < 0) { Platform.runLater(() -> CheckUpdate.openInfo(Version.getCurrent(), newversion)); } break; } catch (Exception e) { LoggerHolder.LOG.warn("", e); } } } private static void openInfo(Version o, Version n) { String message = "\n" + ":" + o + "\n" + ":" + n + "\n" + "※[]-[]OFF"; Alert alert = new Alert(AlertType.INFORMATION); alert.setTitle(""); alert.setHeaderText(""); alert.setContentText(message); alert.getButtonTypes().clear(); alert.getButtonTypes().addAll(ButtonType.YES, ButtonType.NO); alert.showAndWait() .filter(ButtonType.YES::equals) .ifPresent(e -> openBrowser()); } private static void openBrowser() { try { Desktop.getDesktop() .browse(URI.create("https://github.com/sanaehirotaka/logbook-kai/releases")); } catch (Exception e) { LoggerHolder.LOG.warn("", e); } } private static class LoggerHolder { private static final Logger LOG = LogManager.getLogger(CheckUpdate.class); } }
package com.rexsl.test; import com.jcabi.log.Logger; import java.net.HttpCookie; import java.net.URI; import java.util.Collections; import java.util.List; import javax.validation.constraints.NotNull; import javax.ws.rs.core.Cookie; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.NewCookie; import javax.ws.rs.core.UriBuilder; import javax.xml.namespace.NamespaceContext; import lombok.EqualsAndHashCode; import org.apache.commons.lang.StringEscapeUtils; import org.apache.commons.lang.StringUtils; import org.hamcrest.Matcher; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.w3c.dom.Node; /** * Implementation of {@link TestResponse}. * * <p>Objects of this class are mutable and thread-safe. * * @author Yegor Bugayenko (yegor@tpc2.com) * @version $Id$ * @checkstyle ClassDataAbstractionCoupling (500 lines) */ @EqualsAndHashCode(of = "fetcher") @SuppressWarnings("PMD.TooManyMethods") final class JerseyTestResponse implements TestResponse { /** * Fetcher of response (buffered). */ private final transient BufferedJerseyFetcher fetcher; /** * Decorated request. */ private final transient RequestDecor request; /** * The XML document in the body, should be loaded on demand in * {@link #getXml()}. * @see #getXml() */ private transient XmlDocument xml; /** * The Json document in the body, should be loaded on demand in * {@link #getJson()}. * @see #getJson() */ private transient JsonDocument jsonDocument; /** * Public ctor. * @param ftch Response fetcher * @param rqst Decorated request, for logging purposes */ public JerseyTestResponse(@NotNull final JerseyFetcher ftch, @NotNull final RequestDecor rqst) { this.fetcher = new BufferedJerseyFetcher(ftch); this.request = rqst; } /** * {@inheritDoc} */ @Override public String toString() { return Logger.format( "HTTP request:\n%s\nHTTP response (%d):\n%s", this.request, this.getStatus(), new ClientResponseDecor(this.fetcher.fetch(), this.getBody()) ); } /** * {@inheritDoc} */ @Override @NotNull public TestClient rel(@NotNull final String query) { final List<String> links = this.xpath(query); MatcherAssert.assertThat( Logger.format( "XPath '%s' not found in:\n%s\nHTTP request:\n%s", StringEscapeUtils.escapeJava(query), new ClientResponseDecor(this.fetcher.fetch(), this.getBody()), this.request ), links, Matchers.hasSize(1) ); return this.follow(UriBuilder.fromUri(links.get(0)).build()); } /** * {@inheritDoc} */ @Override @NotNull public TestClient follow() { return this.follow(this.fetcher.fetch().getLocation()); } /** * {@inheritDoc} */ @Override @NotNull public String getBody() { try { return this.fetcher.body(); } catch (java.io.IOException ex) { throw new AssertionError(ex); } } /** * {@inheritDoc} */ @Override public int getStatus() { return this.fetcher.fetch().getStatus(); } /** * {@inheritDoc} */ @Override @NotNull public Node node() { return this.getXml().node(); } /** * {@inheritDoc} */ @Override @NotNull public List<String> xpath(@NotNull final String query) { return this.getXml().xpath(query); } /** * {@inheritDoc} */ @Override @NotNull public String getStatusLine() { return Logger.format( "%d %s", this.fetcher.fetch().getStatus(), this.fetcher.fetch().getClientResponseStatus() ); } /** * {@inheritDoc} */ @Override @NotNull public MultivaluedMap<String, String> getHeaders() { return this.fetcher.fetch().getHeaders(); } /** * {@inheritDoc} */ @Override @NotNull @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") public Cookie cookie(@NotNull final String name) { final MultivaluedMap<String, String> headers = this.getHeaders(); MatcherAssert.assertThat( "cookies should be set in HTTP header", headers.containsKey(HttpHeaders.SET_COOKIE) ); final String header = StringUtils.join( headers.get(HttpHeaders.SET_COOKIE), ", " ); Cookie cookie = null; for (HttpCookie candidate : HttpCookie.parse(header)) { if (candidate.getName().equals(name)) { cookie = new Cookie( candidate.getName(), candidate.getValue(), candidate.getPath(), candidate.getDomain(), candidate.getVersion() ); break; } } MatcherAssert.assertThat( Logger.format( "cookie '%s' not found in Set-Cookie header: '%s'", name, header ), cookie, Matchers.notNullValue() ); return cookie; } /** * {@inheritDoc} */ @Override @NotNull public TestResponse registerNs(@NotNull final String prefix, @NotNull final Object uri) { synchronized (this.fetcher) { this.xml = this.getXml().registerNs(prefix, uri); } return this; } /** * {@inheritDoc} */ @Override @NotNull public TestResponse merge(@NotNull final NamespaceContext ctx) { synchronized (this.fetcher) { this.xml = this.getXml().merge(ctx); } return this; } /** * {@inheritDoc} */ @Override @NotNull public List<XmlDocument> nodes(@NotNull final String query) { return Collections.unmodifiableList(this.getXml().nodes(query)); } /** * {@inheritDoc} */ @Override @NotNull public TestResponse assertThat(@NotNull final AssertionPolicy assertion) { synchronized (this.fetcher) { int attempt = 0; while (true) { try { assertion.assertThat(this); break; } catch (AssertionError ex) { ++attempt; if (!assertion.isRetryNeeded(attempt)) { throw ex; } if (attempt >= JerseyTestResponse.MAX_ATTEMPTS) { this.fail( Logger.format("failed after %d attempt(s)", attempt) ); } if (assertion.getClass() .getAnnotation(AssertionPolicy.Quiet.class) == null) { Logger.warn( this, // @checkstyle LineLength (1 line) "#assertThat(%[type]s): attempt #%d failed, re-trying: %[exception]s", assertion, attempt, ex ); } else { Logger.warn( this, "#assertThat(%[type]s): attempt #%d: %s", assertion, attempt, ex.getMessage() ); } this.fetcher.reset(); } } return this; } } /** * {@inheritDoc} */ @Override @NotNull public void fail(@NotNull final String reason) { this.assertThat(new Failure(reason)); } /** * {@inheritDoc} */ @Override @NotNull public TestResponse assertStatus(final int status) { return this.assertStatus(Matchers.equalTo(status)); } /** * {@inheritDoc} */ @Override @NotNull public TestResponse assertStatus(@NotNull final Matcher<Integer> matcher) { this.assertThat(new StatusMatcher(matcher)); return this; } /** * {@inheritDoc} */ @Override @NotNull public TestResponse assertHeader(@NotNull final String name, @NotNull final Matcher<Iterable<String>> matcher) { this.assertThat(new HeaderMatcher(name, matcher)); return this; } /** * {@inheritDoc} */ @Override @NotNull public TestResponse assertBody(@NotNull final Matcher<String> matcher) { this.assertThat(new BodyMatcher(matcher)); return this; } /** * {@inheritDoc} */ @Override @NotNull public TestResponse assertXPath(@NotNull final String xpath) { this.assertThat(new XpathAssertionMatcher(this.getXml(), xpath)); return this; } /** * Get XmlDocument of the body. * * <p>It uses {@code this.fetcher} as a synchronization lock because at * the time of method execution {@code this.xml} may be {@code NULL}. * * @return The XML document */ @NotNull public XmlDocument getXml() { synchronized (this.fetcher) { if (this.xml == null) { this.xml = new LazyXml(this, new XPathContext()); } return this.xml; } } /** * Get JsonDocument of the body. * @return The Json document */ @NotNull public JsonDocument getJson() { synchronized (this.fetcher) { if (this.jsonDocument == null) { this.jsonDocument = new SimpleJson(this.getBody()); } return this.jsonDocument; } } /** * {@inheritDoc} */ @Override @NotNull public TestResponse assertJson(@NotNull final String element) { Logger.warn(this, "method #assertJson() is not implemented yet"); return this; } /** * {@inheritDoc} */ @Override @NotNull public List<String> json(@NotNull final String query) { return this.getJson().json(query); } /** * {@inheritDoc} */ @Override @NotNull public List<JsonDocument> nodesJson(@NotNull final String query) { return Collections.unmodifiableList(this.getJson().nodesJson(query)); } /** * Follow the URI provided. * @param uri The URI to follow * @return New client */ @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") private TestClient follow(final URI uri) { final TestClient client = RestTester.start(uri); for (NewCookie cookie : this.fetcher.fetch().getCookies()) { if (!cookie.getValue().isEmpty()) { client.header( HttpHeaders.COOKIE, new Cookie(cookie.getName(), cookie.getValue()).toString() ); } } return client; } }
package net.squarelabs; import com.thinkaurelius.titan.core.TitanFactory; import com.thinkaurelius.titan.core.TitanGraph; import com.thinkaurelius.titan.core.TitanVertex; import org.apache.commons.configuration.BaseConfiguration; import org.apache.commons.configuration.Configuration; import org.apache.commons.lang.StringUtils; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.net.URLEncoder; public class FindCompanies { private static TitanGraph graph; public static void main(String[] args) throws Exception { long sleepTime = Long.parseLong(args[0]); Configuration conf = new BaseConfiguration(); conf.setProperty("storage.backend", "cassandra"); conf.setProperty("storage.hostname", System.getProperty("storage.hostname")); graph = TitanFactory.open(conf); Iterable<TitanVertex> vertices = graph.query().vertices(); System.out.println("Got vertices!"); int i = 0; for (TitanVertex vert : vertices) { String type = vert.property("type").toString(); System.out.println("Vertex " + i++ + " type=" + type); if (!"member".equals(type)) continue; String name = URLEncoder.encode(vert.property("name").toString()); System.out.println(name); String url = "https: Document doc = Jsoup.connect(url) .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8") .header("Upgrade-Insecure-Requests", "1") .userAgent("Mozilla/5.0 (compatible; Googlebot/2.1; +http: Elements elements = doc.select("#ires .g .slp"); if(elements.size() == 0) { System.out.println("Elements not found!"); continue; } for (Element el : elements) { String tagline = vert.property("tagline").toString(); if (!StringUtils.isEmpty(tagline)) continue; String text = el.text(); if (!text.contains("Denver") && !text.contains("Boulder")) { vert.property("tagline", "Not found"); continue; } System.out.println(text); vert.property("tagline", text); } graph.tx().commit(); System.out.println("Saved!"); Thread.sleep(sleepTime); } } }
package com.rexsl.page; import com.jcabi.log.Logger; import javax.servlet.http.HttpServletRequest; import javax.validation.constraints.NotNull; import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.UriInfo; import javax.ws.rs.ext.Providers; /** * Base implementation of {@link Resource}. * * <p>It is recommended to use this class as a base of all your JAX-RS resource * classes and construct pages with {@link PageBuilder}, * on top of {@link BasePage}, for example: * * <pre> * &#64;Path("/") * public class MainRs extends BaseResource { * &#64;GET * &#64;Produces(MediaTypes.APPLICATION_XML) * public BasePage front() { * return new PageBuilder() * .stylesheet("/xsl/front.xsl") * .build(BasePage.class) * .init(this) * .append(new JaxbBundle("text", "Hello!")); * } * } * </pre> * * @author Yegor Bugayenko (yegor@rexsl.com) * @version $Id$ * @since 0.3.7 * @see BasePage * @see PageBuilder */ public class BaseResource implements Resource { /** * Start time of page building. */ private final transient long start = System.currentTimeMillis(); /** * List of known JAX-RS providers, injected by JAX-RS implementation. */ private transient Providers iproviders; /** * URI info, injected by JAX-RS implementation. */ private transient UriInfo iuriInfo; /** * Http headers, injected by JAX-RS implementation. */ private transient HttpHeaders ihttpHeaders; /** * HTTP servlet request, injected by JAX-RS implementation. */ private transient HttpServletRequest ihttpRequest; /** * {@inheritDoc} */ @Override public final long started() { return this.start; } /** * {@inheritDoc} */ @Override public final Providers providers() { if (this.iproviders == null) { throw new IllegalStateException( Logger.format( "%[type]s#providers was never injected by JAX-RS", this ) ); } return this.iproviders; } /** * {@inheritDoc} */ @Override public final HttpHeaders httpHeaders() { if (this.ihttpHeaders == null) { throw new IllegalStateException( Logger.format( "%[type]s#httpHeaders was never injected by JAX-RS", this ) ); } return this.ihttpHeaders; } /** * {@inheritDoc} */ @Override public final UriInfo uriInfo() { if (this.iuriInfo == null) { throw new IllegalStateException( Logger.format( "%[type]s#uriInfo was never injected by JAX-RS", this ) ); } return this.iuriInfo; } /** * {@inheritDoc} */ @Override public final HttpServletRequest httpServletRequest() { if (this.ihttpRequest == null) { throw new IllegalStateException( Logger.format( "%[type]s#httpRequest was never injected by JAX-RS", this ) ); } return this.ihttpRequest; } /** * Set URI Info. Should be called by JAX-RS implemenation * because of {@code @Context} annotation. * @param info The info to inject */ @Context public final void setUriInfo(@NotNull final UriInfo info) { this.iuriInfo = info; Logger.debug( this, "#setUriInfo(%[type]s): injected", info ); } /** * Set Providers. Should be called by JAX-RS implemenation * because of {@code @Context} annotation. * @param prov List of providers */ @Context public final void setProviders(@NotNull final Providers prov) { this.iproviders = prov; Logger.debug( this, "#setProviders(%[type]s): injected", prov ); } /** * Set HttpHeaders. Should be called by JAX-RS implemenation * because of {@code @Context} annotation. * @param hdrs List of headers */ @Context public final void setHttpHeaders(@NotNull final HttpHeaders hdrs) { this.ihttpHeaders = hdrs; Logger.debug( this, "#setHttpHeaders(%[type]s): injected", hdrs ); } /** * Set HttpServletRequest. Should be called by JAX-RS implemenation * because of {@code @Context} annotation. * @param request The request */ @Context public final void setHttpServletRequest( @NotNull final HttpServletRequest request) { this.ihttpRequest = request; Logger.debug( this, "#setHttpServletRequest(%[type]s): injected", request ); } }
package no.kdrs.grouse.model; import com.fasterxml.jackson.annotation.JsonIgnore; import javax.persistence.*; import javax.xml.bind.annotation.XmlRootElement; import java.util.Date; import java.util.List; @Entity @Table(name = "projects") @XmlRootElement public class Project { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "project_id", nullable = false, updatable = false) private Long id; /** * Acts as a secondary key for a row of information. project_number * is what you search on. Normally automatically set to a UUID */ @Column(name = "project_number") private String projectNumber; /** * Assignable descriptive name to the project e.g * 'Eksempel kommune nytt sak/arkiv system 2017' */ @Column(name = "project_name") private String projectName; /** * Name of the requirements document */ @Column(name = "file_name") private String fileName; /** * The date the project was created */ @Column(name = "created_date") @Temporal(TemporalType.TIMESTAMP) private Date createdDate; /** * Name of the organisation */ @Column(name = "organisation_name") private String organisationName; /** * The date the project was accessed */ @Column(name = "accessed_date") @Temporal(TemporalType.TIMESTAMP) private Date accessedDate; @JsonIgnore @OneToMany(mappedBy = "referenceProject", fetch = FetchType.LAZY) private List<ProjectRequirement> referenceProjectRequirement; @JsonIgnore @OneToMany(mappedBy = "referenceProject", fetch = FetchType.LAZY) private List<ProjectFunctionality> referenceProjectFunctionality; @JsonIgnore @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "username", referencedColumnName = "username") private GrouseUser referenceUser; public static long getSerialVersionUID() { return serialVersionUID; } public Long getId() { return id; } public String getProjectName() { return projectName; } public void setProjectName(String projectName) { this.projectName = projectName; } public String getOrganisationName() { return organisationName; } public void setOrganisationName(String organisationName) { this.organisationName = organisationName; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public String getProjectNumber() { return projectNumber; } public void setProjectNumber(String projectNumber) { this.projectNumber = projectNumber; } public Date getCreatedDate() { return createdDate; } public void setCreatedDate(Date createdDate) { this.createdDate = createdDate; } public Date getAccessedDate() { return accessedDate; } public void setAccessedDate(Date accessedDate) { this.accessedDate = accessedDate; } public List<ProjectRequirement> getReferenceProjectRequirement() { return referenceProjectRequirement; } public void setReferenceProjectRequirement(List<ProjectRequirement> referenceProjectRequirement) { this.referenceProjectRequirement = referenceProjectRequirement; } public GrouseUser getReferenceUser() { return referenceUser; } public void setReferenceUser(GrouseUser referenceUser) { this.referenceUser = referenceUser; } public List<ProjectFunctionality> getReferenceProjectFunctionality() { return referenceProjectFunctionality; } public void setReferenceProjectFunctionality( List<ProjectFunctionality> referenceProjectFunctionality) { this.referenceProjectFunctionality = referenceProjectFunctionality; } @Override public String toString() { return "Project{" + "id=" + id + ", projectNumber='" + projectNumber + '\'' + ", projectName='" + projectName + '\'' + ", fileName='" + fileName + '\'' + '}'; } }
package org.fxmisc.richtext; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.function.BiConsumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.function.UnaryOperator; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.collections.ObservableList; import javafx.collections.transformation.FilteredList; import javafx.geometry.Bounds; import javafx.geometry.Insets; import javafx.scene.Node; import javafx.scene.control.IndexRange; import javafx.scene.paint.Color; import javafx.scene.paint.Paint; import javafx.scene.shape.Path; import javafx.scene.shape.PathElement; import javafx.scene.shape.StrokeLineCap; import javafx.scene.shape.StrokeType; import org.fxmisc.richtext.model.Paragraph; import org.reactfx.util.Tuple2; import org.reactfx.util.Tuples; import org.reactfx.value.Val; import org.reactfx.value.Var; class ParagraphText<PS, SEG, S> extends TextFlowExt { // FIXME: changing it currently has not effect, because // Text.impl_selectionFillProperty().set(newFill) doesn't work // properly for Text node inside a TextFlow (as of JDK8-b100). private final ObjectProperty<Paint> highlightTextFill = new SimpleObjectProperty<>(Color.WHITE); public ObjectProperty<Paint> highlightTextFillProperty() { return highlightTextFill; } private final Var<Integer> caretPosition = Var.newSimpleVar(0); public Var<Integer> caretPositionProperty() { return caretPosition; } public void setCaretPosition(int pos) { caretPosition.setValue(pos); } private final Val<Integer> clampedCaretPosition; private final ObjectProperty<IndexRange> selection = new SimpleObjectProperty<>(StyledTextArea.EMPTY_RANGE); public ObjectProperty<IndexRange> selectionProperty() { return selection; } public void setSelection(IndexRange sel) { selection.set(sel); } private final Paragraph<PS, SEG, S> paragraph; private final Path caretShape = new Path(); private final Path selectionShape = new Path(); private final List<Path> backgroundShapes = new LinkedList<>(); private final List<Path> underlineShapes = new LinkedList<>(); private final List<Path> borderShapes = new LinkedList<>(); private final List<Tuple2<Paint, IndexRange>> backgroundColorRanges = new LinkedList<>(); private final List<Tuple2<UnderlineAttributes, IndexRange>> underlineRanges = new LinkedList<>(); private final List<Tuple2<BorderAttributes, IndexRange>> borderRanges = new LinkedList<>(); private final Val<Double> leftInset; private final Val<Double> topInset; // proxy for caretShape.visibleProperty() that implements unbind() correctly. // This is necessary due to a bug in BooleanPropertyBase#unbind(). private final Var<Boolean> caretVisible = Var.newSimpleVar(false); { caretShape.visibleProperty().bind(caretVisible); } ParagraphText(Paragraph<PS, SEG, S> par, Function<SEG, Node> nodeFactory) { this.paragraph = par; getStyleClass().add("paragraph-text"); int parLen = paragraph.length(); clampedCaretPosition = caretPosition.map(i -> Math.min(i, parLen)); clampedCaretPosition.addListener((obs, oldPos, newPos) -> requestLayout()); selection.addListener((obs, old, sel) -> requestLayout()); leftInset = Val.map(insetsProperty(), Insets::getLeft); topInset = Val.map(insetsProperty(), Insets::getTop); // selection highlight selectionShape.setManaged(false); selectionShape.setFill(Color.DODGERBLUE); selectionShape.setStrokeWidth(0); selectionShape.layoutXProperty().bind(leftInset); selectionShape.layoutYProperty().bind(topInset); getChildren().add(selectionShape); // caret caretShape.getStyleClass().add("caret"); caretShape.setManaged(false); caretShape.setStrokeWidth(1); caretShape.layoutXProperty().bind(leftInset); caretShape.layoutYProperty().bind(topInset); getChildren().add(caretShape); // XXX: see the note at highlightTextFill // highlightTextFill.addListener(new ChangeListener<Paint>() { // @Override // public void changed(ObservableValue<? extends Paint> observable, // Paint oldFill, Paint newFill) { // for(PumpedUpText text: textNodes()) // text.impl_selectionFillProperty().set(newFill); // populate with text nodes for(SEG segment: par.getSegments()) { // create Segment Node fxNode = nodeFactory.apply(segment); getChildren().add(fxNode); } } public Paragraph<PS, SEG, S> getParagraph() { return paragraph; } public Var<Boolean> caretVisibleProperty() { return caretVisible; } public ObjectProperty<Paint> highlightFillProperty() { return selectionShape.fillProperty(); } public double getCaretOffsetX() { layout(); // ensure layout, is a no-op if not dirty Bounds bounds = caretShape.getLayoutBounds(); return (bounds.getMinX() + bounds.getMaxX()) / 2; } public Bounds getCaretBounds() { layout(); // ensure layout, is a no-op if not dirty return caretShape.getBoundsInParent(); } public Bounds getCaretBoundsOnScreen() { layout(); // ensure layout, is a no-op if not dirty Bounds localBounds = caretShape.getBoundsInLocal(); return caretShape.localToScreen(localBounds); } public Bounds getRangeBoundsOnScreen(int from, int to) { layout(); // ensure layout, is a no-op if not dirty PathElement[] rangeShape = getRangeShape(from, to); // switch out shapes to calculate the bounds on screen // Must take a copy of the list contents, not just a reference: List<PathElement> selShape = new ArrayList<>(selectionShape.getElements()); selectionShape.getElements().setAll(rangeShape); Bounds localBounds = selectionShape.getBoundsInLocal(); Bounds rangeBoundsOnScreen = selectionShape.localToScreen(localBounds); selectionShape.getElements().setAll(selShape); return rangeBoundsOnScreen; } public Optional<Bounds> getSelectionBoundsOnScreen() { if(selection.get().getLength() == 0) { return Optional.empty(); } else { layout(); // ensure layout, is a no-op if not dirty Bounds localBounds = selectionShape.getBoundsInLocal(); return Optional.ofNullable(selectionShape.localToScreen(localBounds)); } } public int getCurrentLineStartPosition() { return getLineStartPosition(clampedCaretPosition.getValue()); } public int getCurrentLineEndPosition() { return getLineEndPosition(clampedCaretPosition.getValue()); } public int currentLineIndex() { return getLineOfCharacter(clampedCaretPosition.getValue()); } public int currentLineIndex(int position) { return getLineOfCharacter(position); } private void updateCaretShape() { PathElement[] shape = getCaretShape(clampedCaretPosition.getValue(), true); caretShape.getElements().setAll(shape); } private void updateSelectionShape() { int start = selection.get().getStart(); int end = selection.get().getEnd(); PathElement[] shape = getRangeShape(start, end); selectionShape.getElements().setAll(shape); } private void updateBackgroundShapes() { int start = 0; // calculate shared values among consecutive nodes FilteredList<Node> nodeList = getChildren().filtered(node -> node instanceof TextExt); for (Node node : nodeList) { TextExt text = (TextExt) node; int end = start + text.getText().length(); Paint backgroundColor = text.getBackgroundColor(); if (backgroundColor != null) { updateSharedShapeRange(backgroundColorRanges, backgroundColor, start, end); } BorderAttributes border = new BorderAttributes(text); if (!border.isNullValue()) { updateSharedShapeRange(borderRanges, border, start, end); } UnderlineAttributes underline = new UnderlineAttributes(text); if (!underline.isNullValue()) { updateSharedShapeRange(underlineRanges, underline, start, end); } start = end; } // now only use one shape per shared value BiConsumer<ObservableList<Node>, Path> addToBackground = (children, shape) -> children.add(0, shape); BiConsumer<ObservableList<Node>, Path> addToForeground = ObservableList::add; // | background color -> border -> text -> underline -> user's eye updateSharedShapes(borderRanges, borderShapes, addToBackground, (borderShape, tuple) -> { BorderAttributes attributes = tuple._1; borderShape.setStrokeWidth(attributes.width); borderShape.setStroke(attributes.color); if (attributes.type != null) { borderShape.setStrokeType(attributes.type); } if (attributes.dashArray != null) { borderShape.getStrokeDashArray().setAll(attributes.dashArray); } borderShape.getElements().setAll(getRangeShape(tuple._2)); }); updateSharedShapes(backgroundColorRanges, backgroundShapes, addToBackground, (colorShape, tuple) -> { colorShape.setStrokeWidth(0); colorShape.setFill(tuple._1); colorShape.getElements().setAll(getRangeShape(tuple._2)); }); updateSharedShapes(underlineRanges, underlineShapes, addToForeground, (underlineShape, tuple) -> { UnderlineAttributes attributes = tuple._1; underlineShape.setStroke(attributes.color); underlineShape.setStrokeWidth(attributes.width); underlineShape.setStrokeLineCap(attributes.cap); if (attributes.dashArray != null) { underlineShape.getStrokeDashArray().setAll(attributes.dashArray); } underlineShape.getElements().setAll(getUnderlineShape(tuple._2)); }); } /** * Calculates the range of a value (background color, underline, etc.) that is shared between multiple * consecutive {@link TextExt} nodes */ private <T> void updateSharedShapeRange(List<Tuple2<T, IndexRange>> rangeList, T value, int start, int end) { updateSharedShapeRange0( rangeList, () -> Tuples.t(value, new IndexRange(start, end)), lastRange -> { T lastShapeValue = lastRange._1; return lastShapeValue.equals(value); }, lastRange -> lastRange.map((val, range) -> Tuples.t(val, new IndexRange(range.getStart(), end))) ); } private <T> void updateSharedShapeRange0(List<T> rangeList, Supplier<T> newValueRange, Predicate<T> sharesShapeValue, UnaryOperator<T> mapper) { if (rangeList.isEmpty()) { rangeList.add(newValueRange.get()); } else { int lastIndex = rangeList.size() - 1; T lastShapeValueRange = rangeList.get(lastIndex); if (sharesShapeValue.test(lastShapeValueRange)) { rangeList.set(lastIndex, mapper.apply(lastShapeValueRange)); } else { rangeList.add(newValueRange.get()); } } } /** * Updates the shapes calculated in {@link #updateSharedShapeRange(List, Object, int, int)} and configures them * via {@code configureShape}. */ private <T> void updateSharedShapes(List<T> rangeList, List<Path> shapeList, BiConsumer<ObservableList<Node>, Path> addToChildren, BiConsumer<Path, T> configureShape) { // remove or add shapes, depending on what's needed int neededNumber = rangeList.size(); int availableNumber = shapeList.size(); if (neededNumber < availableNumber) { List<Path> unusedShapes = shapeList.subList(neededNumber, availableNumber); getChildren().removeAll(unusedShapes); unusedShapes.clear(); } else if (availableNumber < neededNumber) { for (int i = 0; i < neededNumber - availableNumber; i++) { Path shape = new Path(); shape.setManaged(false); shape.layoutXProperty().bind(leftInset); shape.layoutYProperty().bind(topInset); shapeList.add(shape); addToChildren.accept(getChildren(), shape); } } // update the shape's color and elements for (int i = 0; i < rangeList.size(); i++) { configureShape.accept(shapeList.get(i), rangeList.get(i)); } // clear, since it's no longer needed rangeList.clear(); } @Override protected void layoutChildren() { super.layoutChildren(); updateCaretShape(); updateSelectionShape(); updateBackgroundShapes(); } private static class BorderAttributes extends LineAttributesBase { final StrokeType type; BorderAttributes(TextExt text) { super(text.getBorderStrokeColor(), text.getBorderStrokeWidth(), text.getBorderStrokeDashArray()); type = text.getBorderStrokeType(); } @Override public boolean equals(Object obj) { if (obj instanceof BorderAttributes) { BorderAttributes attributes = (BorderAttributes) obj; return super.equals(attributes) && Objects.equals(type, attributes.type); } else { return false; } } @Override public String toString() { return String.format("BorderAttributes[type=%s %s]", type, getSubString()); } } private static class UnderlineAttributes extends LineAttributesBase { final StrokeLineCap cap; UnderlineAttributes(TextExt text) { super(text.getUnderlineColor(), text.getUnderlineWidth(), text.getUnderlineDashArray()); cap = text.getUnderlineCap(); } @Override public boolean equals(Object obj) { if (obj instanceof UnderlineAttributes) { UnderlineAttributes attr = (UnderlineAttributes) obj; return super.equals(attr) && Objects.equals(cap, attr.cap); } else { return false; } } @Override public String toString() { return String.format("UnderlineAttributes[cap=%s %s]", cap, getSubString()); } } private static class LineAttributesBase { final double width; final Paint color; final Double[] dashArray; public final boolean isNullValue() { return color == null || width == -1; } LineAttributesBase(Paint color, Number width, Object dashArrayProperty) { this.color = color; if (color == null || width == null || width.doubleValue() <= 0) { // null value this.width = -1; dashArray = null; } else { // real value this.width = width.doubleValue(); // get the dash array - JavaFX CSS parser seems to return either a Number[] array // or a single value, depending on whether only one or more than one value has been // specified in the CSS if (dashArrayProperty != null) { if (dashArrayProperty.getClass().isArray()) { Number[] numberArray = (Number[]) dashArrayProperty; dashArray = new Double[numberArray.length]; int idx = 0; for (Number d : numberArray) { dashArray[idx++] = (Double) d; } } else { dashArray = new Double[1]; dashArray[0] = ((Double) dashArrayProperty).doubleValue(); } } else { dashArray = null; } } } @Override public boolean equals(Object obj) { if (obj instanceof UnderlineAttributes) { UnderlineAttributes attr = (UnderlineAttributes) obj; return Objects.equals(width, attr.width) && Objects.equals(color, attr.color) && Arrays.equals(dashArray, attr.dashArray); } else { return false; } } protected final String getSubString() { return String.format("width=%s color=%s dashArray=%s", width, color, Arrays.toString(dashArray)); } } }
package org.autotune; import javafx.util.Pair; import okhttp3.OkHttpClient; import org.apache.commons.lang3.reflect.FieldUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import retrofit2.Call; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.jackson.JacksonConverterFactory; import java.io.IOException; import java.io.Serializable; import java.lang.reflect.Field; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; @TuneableParameters() public class AutoTuneDefault<T extends Serializable> extends AutoTune<T> { @NotNull final static protected Logger logger = LogManager.getLogger(AutoTuneDefault.class); @NotNull private List<Pair<List<Double>, Double>>sampledConfigurations = new ArrayList<>(10); @NotNull private List<List<Double>>cachedConfiguration = new ArrayList<>(10); @Nullable private List<Double> currentConfiguration; final private int cacheSize; final private int retryAfter; //retry configurations after x samples private int retryPhase = 0; //MOE hyper-parameter @NumericParameter(min=0.2, max=30) int lengthScaleDivider = 2; @NumericParameter(min=1, max=30) int numOptimizerMultistarts = 20; @NumericParameter(min=0.0001, max=2.0) double gaussianSignalVariance = 6.0; final private boolean useDefaultValues; private boolean initRandomSearchDone = false; final private boolean autoTimeMeasure; private OkHttpClient okHttpClient = new OkHttpClient().newBuilder() .connectTimeout(320, TimeUnit.SECONDS) .readTimeout(320, TimeUnit.SECONDS) .writeTimeout(320, TimeUnit.SECONDS) .build(); private double bestResult = Double.MAX_VALUE; @Nullable private List<Double> bestConfiguration; @Nullable private T bestConfigurationObject; @Nullable private T currentConfigurationObject; private double currentConfigurationCosts; private long startTimeStamp = Long.MIN_VALUE; private long elapsedTime = 0; @NotNull final protected List<Field> numericFields; @NotNull final protected List<Field> nominalFields; public AutoTuneDefault(T config){ super(config); logger.debug("Tuner created for configuration class " + config.getClass().getName()); //extract class information this.cacheSize = tuneSettings.cacheNextPoints(); this.autoTimeMeasure = tuneSettings.autoTimeMeasure(); this.retryAfter = tuneSettings.reftryAfter(); this.useDefaultValues = tuneSettings.sampleDefaultValues(); this.numericFields = FieldUtils.getFieldsListWithAnnotation(config.getClass(), NumericParameter.class); this.nominalFields = FieldUtils.getFieldsListWithAnnotation(config.getClass(), NominalParameter.class); } @Override public AutoTune<T> start() { /** extract numeric field information **/ //create domain info GpNextPointsRequest req = new GpNextPointsRequest( cacheSize, new GpNextPointsRequest.OptimizerInfo(numOptimizerMultistarts, "gradient_descent_optimizer"), new GpNextPointsRequest.CovarianceInfo(), new GpNextPointsRequest.BoundedDomainInfo(), new GpNextPointsRequest.GpHistoricalInfo()); req.getCovariance_info().getHyperparameters().add(gaussianSignalVariance); //add signal variance information, for the gaussian process for (Field field : numericFields){ NumericParameter numericParameterInfo = field.getAnnotation(NumericParameter.class); GpNextPointsRequest.Domain boundA = new GpNextPointsRequest.Domain(numericParameterInfo.max(), numericParameterInfo.min()); req.getDomain_info().getDomain_bounds().add(boundA); //length scale determines how closely two sample points are correlated final double lengthScale = (numericParameterInfo.max() - numericParameterInfo.min()) / lengthScaleDivider; req.getCovariance_info().getHyperparameters().add(lengthScale); } /** extract nominal field information **/ req.getCovariance_info().getHyperparameters().add(gaussianSignalVariance); //add signal variance information, for the gaussian process for (Field field : nominalFields){ NominalParameter nominalParameterInfo = field.getAnnotation(NominalParameter.class); GpNextPointsRequest.Domain boundA = new GpNextPointsRequest.Domain(nominalParameterInfo.values().length - 1, 0); req.getDomain_info().getDomain_bounds().add(boundA); //length scale for nominal value is one req.getCovariance_info().getHyperparameters().add(1.0); } final int dimension = numericFields.size() + nominalFields.size(); req.getDomain_info().updateDimension(); //random search at the begin if(!initRandomSearchDone){ final int numberOfSamples = tuneSettings.initRandomSearch(); cachedConfiguration = new ArrayList<>(numberOfSamples); logger.debug("Number of random samples: {}", numberOfSamples); //prepare cachedConfiguration for (int i = 0; i < numberOfSamples; i++) { cachedConfiguration.add(new ArrayList<>(numericFields.size())); } Random rand = new Random(); //fill cachedConfiguration with random samples by dimension for (int i = 0; i < numericFields.size(); i++) { //for numericFields NumericParameter numericParameterInfo = numericFields.get(i).getAnnotation(NumericParameter.class); final double parameterWidth = (numericParameterInfo.max() - numericParameterInfo.min()); for(int j = 0; j < numberOfSamples; j++){ cachedConfiguration.get(j).add(rand.nextDouble()*parameterWidth + numericParameterInfo.min()); } } for (int i = 0; i < nominalFields.size(); i++) { //for nominalFields NominalParameter nominalParameterInfo = nominalFields.get(i).getAnnotation(NominalParameter.class); final double parameterWidth = (double) nominalParameterInfo.values().length - 1; for(int j = 0; j < numberOfSamples; j++){ cachedConfiguration.get(j).add(rand.nextDouble()*parameterWidth); } } initRandomSearchDone = true; if(useDefaultValues) { try { //add default values for probing (numeric values) ArrayList<Double> predefinedDefaultParameters = new ArrayList<>(numericFields.size() + nominalFields.size()); for (Field field : numericFields) { predefinedDefaultParameters.add(field.getDouble(config)); } for (Field field : nominalFields) { NominalParameter nominalParameterInfo = field.getAnnotation(NominalParameter.class); String strLabel; if (field.getType().equals(boolean.class)) { strLabel = String.valueOf(field.getBoolean(config)); } else { strLabel = (String) field.get(config); } int i; for (i = 0; i < nominalParameterInfo.values().length; i++) { if (nominalParameterInfo.values()[i].equals(strLabel)) { break; } } predefinedDefaultParameters.add(new Double(i)); } cachedConfiguration.add(predefinedDefaultParameters); }catch (IllegalAccessException exc){ logger.catching(exc); throw new RuntimeException("Can't access the config object.", exc.getCause()); } } }else if(cachedConfiguration.size() == 0){ //fill cache from REST optimizer Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://127.0.0.1:6543") .client(okHttpClient) .addConverterFactory(JacksonConverterFactory.create()) .build(); MOE service = retrofit.create(MOE.class); for(Pair<List<Double>, Double> sample : sampledConfigurations){ req.getGp_historical_info().getPoints_sampled().add(new GpNextPointsRequest.SinglePoint(sample.getKey(), sample.getValue(), 0.1)); } Call<GpNextPointsResponse> nextPointsCall = service.gpNextPointsEpi(req); try { Response<GpNextPointsResponse> response = nextPointsCall.execute(); GpNextPointsResponse nextPointsResponse = response.body(); cachedConfiguration = nextPointsResponse.getPoints_to_sample(); } catch (IOException e) { e.printStackTrace(); } } //use cached configuration if (cachedConfiguration == null || cachedConfiguration.isEmpty()) { logger.warn("No new configuration found. Use best known configuration."); cachedConfiguration = new LinkedList<List<Double>>() {{ add(bestConfiguration); }}; } else { /** retry sampled configurations **/ if (retryAfter != 0 && (sampledConfigurations.size() + 1) % retryAfter == 0 && (sampledConfigurations.size() + 1) / retryAfter > retryPhase) { //add all x-1 last sampled configurations to cachedConfigurations cachedConfiguration.addAll( sampledConfigurations.subList(retryPhase*retryAfter, retryPhase*retryAfter+retryAfter-1) .stream().map(listDoublePair -> listDoublePair.getKey()).collect(Collectors.toList()) ); //add last cached configuration to the top of the list cachedConfiguration.add(cachedConfiguration.get(cachedConfiguration.size()-retryAfter)); retryPhase++; retryPhase++; } currentConfiguration = cachedConfiguration.get(cachedConfiguration.size() - 1); cachedConfiguration.remove(cachedConfiguration.size() - 1); } logger.debug("New configuration values: {}", Arrays.toString(currentConfiguration.toArray())); currentConfigurationCosts = 0; try { Iterator<Double> currentConfigurationItr = currentConfiguration.iterator(); for (Field field : numericFields) { //for numeric fields Double parameterValue = currentConfigurationItr.next(); if (field.getType().equals(long.class)) { field.setLong(config, parameterValue.longValue()); } else if (field.getType().equals(int.class)) { field.setInt(config, parameterValue.intValue()); } else { //assume it is a double parameter field.setDouble(config, parameterValue); } NumericParameter numericParameterInfo = field.getAnnotation(NumericParameter.class); currentConfigurationCosts += parameterValue * numericParameterInfo.cost(); } for (Field field : nominalFields) { //for nominal fields NominalParameter nominalParameterInfo = field.getAnnotation(NominalParameter.class); int label = currentConfigurationItr.next().intValue(); label = label < 0 ? 0 : label; label = label >= nominalParameterInfo.values().length ? nominalParameterInfo.values().length - 1 : label; String strLabel = nominalParameterInfo.values()[label]; if (field.getType().equals(boolean.class)) { field.setBoolean(config, Boolean.parseBoolean(strLabel)); } else { //assume it is a String parameter field.set(config, strLabel); } } this.currentConfigurationObject = config; }catch (IllegalAccessException exc){ logger.catching(exc); throw new RuntimeException("Can't set value into config object", exc.getCause()); } if(this.autoTimeMeasure){ this.startTimeMeasure(); } return this; } @Override public void end() { if(this.autoTimeMeasure){ this.stopTimeMeasure(); } double amount = currentConfigurationCosts; //add costs from configuration amount += elapsedTime;//add elapsed time as cost if(!Double.isFinite(amount)){ //sanitize result amount = Double.MAX_VALUE; } if(amount < this.bestResult){ //new best result this.bestResult = amount; this.bestConfiguration = currentConfiguration; this.bestConfigurationObject = currentConfigurationObject; logger.debug("New best configuration found! Cost value: {}", this.bestResult); } sampledConfigurations.add(new Pair<>(currentConfiguration, amount)); this.currentConfigurationObject = null; this.elapsedTime = 0; logger.trace("Sampled configurations as CSV \n{}", () -> { StringBuilder stringBuilder = new StringBuilder(); for (Field nField : this.numericFields) { stringBuilder.append(nField.getName()); stringBuilder.append(';'); } for (Field nField : this.nominalFields) { stringBuilder.append(nField.getName()); stringBuilder.append(';'); } stringBuilder.append("cost"); stringBuilder.append(';'); stringBuilder.append("order"); stringBuilder.append('\n'); int counter = 0; for (Pair<List<Double>, Double> conf : sampledConfigurations) { stringBuilder.append(conf.getKey().stream().map(i -> String.format(Locale.GERMAN, "%f", i)).collect(Collectors.joining(";"))); stringBuilder.append(';'); stringBuilder.append(String.format(Locale.GERMAN, "%f", (conf.getValue()))); stringBuilder.append(';'); stringBuilder.append(counter++); stringBuilder.append('\n'); } stringBuilder.deleteCharAt(stringBuilder.length() - 1); //remove last new line return stringBuilder.toString(); }); } @Override public @NotNull T getConfig(){ if(this.currentConfigurationObject == null){ throw new RuntimeException("You have to call start() first."); } return this.currentConfigurationObject; } @Override public @Nullable T getBestConfiguration() { return this.bestConfigurationObject; } @Override public List<Double> getBestConfigurationParameter() { return this.bestConfiguration; } @Override public double getBestResult() { return this.bestResult; } @Override public void startTimeMeasure() { if(this.startTimeStamp != Long.MIN_VALUE){ throw new RuntimeException("Start time measure but time measure are already started!"); } this.startTimeStamp = System.currentTimeMillis(); } @Override public void stopTimeMeasure() { if(this.startTimeStamp == Long.MIN_VALUE){ throw new RuntimeException("End time measure but time measure yet not started!"); } this.elapsedTime += System.currentTimeMillis()-this.startTimeStamp; this.startTimeStamp = Long.MIN_VALUE; logger.debug("Stop time measure. Elapsed time: {} ms", this.elapsedTime); } @Override public void addCost(double cost) { this.currentConfigurationCosts += cost; } }
package net.runelite.client; import com.google.common.base.Strings; import com.google.common.escape.Escaper; import com.google.common.escape.Escapers; import com.google.inject.Inject; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.TrayIcon; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.time.Instant; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import javax.inject.Singleton; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.UnsupportedAudioFileException; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import net.runelite.api.ChatMessageType; import net.runelite.api.Client; import net.runelite.api.Constants; import net.runelite.api.GameState; import net.runelite.client.chat.ChatColorType; import net.runelite.client.chat.ChatMessageBuilder; import net.runelite.client.chat.ChatMessageManager; import net.runelite.client.chat.QueuedMessage; import net.runelite.client.config.FlashNotification; import net.runelite.client.config.RuneLiteConfig; import net.runelite.client.eventbus.EventBus; import net.runelite.client.events.NotificationFired; import net.runelite.client.ui.ClientUI; import net.runelite.client.util.OSType; @Singleton @Slf4j public class Notifier { @Getter @RequiredArgsConstructor public enum NativeCustomOff { NATIVE("Native"), CUSTOM("Custom"), OFF("Off"); private final String name; @Override public String toString() { return name; } } // Default timeout of notification in milliseconds private static final int DEFAULT_TIMEOUT = 10000; private static final String DOUBLE_QUOTE = "\""; private static final Escaper SHELL_ESCAPE = Escapers.builder() .addEscape('"', "'") .build(); // Notifier properties private static final Color FLASH_COLOR = new Color(255, 0, 0, 70); private static final int MINIMUM_FLASH_DURATION_MILLIS = 2000; private static final int MINIMUM_FLASH_DURATION_TICKS = MINIMUM_FLASH_DURATION_MILLIS / Constants.CLIENT_TICK_LENGTH; private static final String appName = RuneLiteProperties.getTitle(); private static final File NOTIFICATION_FILE = new File(RuneLite.RUNELITE_DIR, "notification.wav"); private static final long CLIP_MTIME_UNLOADED = -2; private static final long CLIP_MTIME_BUILTIN = -1; private final Client client; private final RuneLiteConfig runeLiteConfig; private final ClientUI clientUI; private final ScheduledExecutorService executorService; private final ChatMessageManager chatMessageManager; private final EventBus eventBus; private final Path notifyIconPath; private final boolean terminalNotifierAvailable; private Instant flashStart; private long mouseLastPressedMillis; private long lastClipMTime = CLIP_MTIME_UNLOADED; private Clip clip = null; @Inject private Notifier( final ClientUI clientUI, final Client client, final RuneLiteConfig runeliteConfig, final ScheduledExecutorService executorService, final ChatMessageManager chatMessageManager, final EventBus eventBus) { this.client = client; this.clientUI = clientUI; this.runeLiteConfig = runeliteConfig; this.executorService = executorService; this.chatMessageManager = chatMessageManager; this.eventBus = eventBus; this.notifyIconPath = RuneLite.RUNELITE_DIR.toPath().resolve("icon.png"); // First check if we are running in launcher this.terminalNotifierAvailable = !Strings.isNullOrEmpty(RuneLiteProperties.getLauncherVersion()) && isTerminalNotifierAvailable(); storeIcon(); } public void notify(String message) { notify(message, TrayIcon.MessageType.NONE); } public void notify(String message, TrayIcon.MessageType type) { eventBus.post(new NotificationFired(message, type)); if (!runeLiteConfig.sendNotificationsWhenFocused() && clientUI.isFocused()) { return; } switch (runeLiteConfig.notificationRequestFocus()) { case REQUEST: clientUI.requestFocus(); break; case FORCE: clientUI.forceFocus(); break; } if (runeLiteConfig.enableTrayNotifications()) { sendNotification(appName, message, type); } switch (runeLiteConfig.notificationSound()) { case NATIVE: Toolkit.getDefaultToolkit().beep(); break; case CUSTOM: executorService.submit(this::playCustomSound); } if (runeLiteConfig.enableGameMessageNotification() && client.getGameState() == GameState.LOGGED_IN) { final String formattedMessage = new ChatMessageBuilder() .append(ChatColorType.HIGHLIGHT) .append(message) .build(); chatMessageManager.queue(QueuedMessage.builder() .type(ChatMessageType.CONSOLE) .name(appName) .runeLiteFormattedMessage(formattedMessage) .build()); } if (runeLiteConfig.flashNotification() != FlashNotification.DISABLED) { flashStart = Instant.now(); mouseLastPressedMillis = client.getMouseLastPressedMillis(); } log.debug(message); } public void processFlash(final Graphics2D graphics) { if (flashStart == null || client.getGameState() != GameState.LOGGED_IN) { flashStart = null; return; } FlashNotification flashNotification = runeLiteConfig.flashNotification(); if (Instant.now().minusMillis(MINIMUM_FLASH_DURATION_MILLIS).isAfter(flashStart)) { switch (flashNotification) { case FLASH_TWO_SECONDS: case SOLID_TWO_SECONDS: flashStart = null; return; case SOLID_UNTIL_CANCELLED: case FLASH_UNTIL_CANCELLED: // Any interaction with the client since the notification started will cancel it after the minimum duration if ((client.getMouseIdleTicks() < MINIMUM_FLASH_DURATION_TICKS || client.getKeyboardIdleTicks() < MINIMUM_FLASH_DURATION_TICKS || client.getMouseLastPressedMillis() > mouseLastPressedMillis) && clientUI.isFocused()) { flashStart = null; return; } break; } } if (client.getGameCycle() % 40 >= 20 // For solid colour, fall through every time. && (flashNotification == FlashNotification.FLASH_TWO_SECONDS || flashNotification == FlashNotification.FLASH_UNTIL_CANCELLED)) { return; } final Color color = graphics.getColor(); graphics.setColor(FLASH_COLOR); graphics.fill(new Rectangle(client.getCanvas().getSize())); graphics.setColor(color); } private void sendNotification( final String title, final String message, final TrayIcon.MessageType type) { final String escapedTitle = SHELL_ESCAPE.escape(title); final String escapedMessage = SHELL_ESCAPE.escape(message); switch (OSType.getOSType()) { case Linux: sendLinuxNotification(escapedTitle, escapedMessage, type); break; case MacOS: sendMacNotification(escapedTitle, escapedMessage); break; default: sendTrayNotification(title, message, type); } } private void sendTrayNotification( final String title, final String message, final TrayIcon.MessageType type) { if (clientUI.getTrayIcon() != null) { clientUI.getTrayIcon().displayMessage(title, message, type); } } private void sendLinuxNotification( final String title, final String message, final TrayIcon.MessageType type) { final List<String> commands = new ArrayList<>(); commands.add("notify-send"); commands.add(title); commands.add(message); commands.add("-i"); commands.add(SHELL_ESCAPE.escape(notifyIconPath.toAbsolutePath().toString())); commands.add("-u"); commands.add(toUrgency(type)); commands.add("-t"); commands.add(String.valueOf(DEFAULT_TIMEOUT)); executorService.submit(() -> { try { Process notificationProcess = sendCommand(commands); boolean exited = notificationProcess.waitFor(500, TimeUnit.MILLISECONDS); if (exited && notificationProcess.exitValue() == 0) { return; } } catch (IOException | InterruptedException ex) { log.debug("error sending notification", ex); } // fall back to tray notification sendTrayNotification(title, message, type); }); } private void sendMacNotification(final String title, final String message) { final List<String> commands = new ArrayList<>(); if (terminalNotifierAvailable) { commands.add("terminal-notifier"); commands.add("-group"); commands.add("net.runelite.launcher"); commands.add("-sender"); commands.add("net.runelite.launcher"); commands.add("-message"); commands.add(DOUBLE_QUOTE + message + DOUBLE_QUOTE); commands.add("-title"); commands.add(DOUBLE_QUOTE + title + DOUBLE_QUOTE); } else { commands.add("osascript"); commands.add("-e"); final String script = "display notification " + DOUBLE_QUOTE + message + DOUBLE_QUOTE + " with title " + DOUBLE_QUOTE + title + DOUBLE_QUOTE; commands.add(script); } try { sendCommand(commands); } catch (IOException ex) { log.warn("error sending notification", ex); } } private static Process sendCommand(final List<String> commands) throws IOException { return new ProcessBuilder(commands.toArray(new String[commands.size()])) .redirectErrorStream(true) .start(); } private void storeIcon() { if (OSType.getOSType() == OSType.Linux && !Files.exists(notifyIconPath)) { try (InputStream stream = Notifier.class.getResourceAsStream("/runelite.png")) { Files.copy(stream, notifyIconPath); } catch (IOException ex) { log.warn(null, ex); } } } private boolean isTerminalNotifierAvailable() { if (OSType.getOSType() == OSType.MacOS) { try { final Process exec = Runtime.getRuntime().exec(new String[]{"terminal-notifier", "-help"}); exec.waitFor(); return exec.exitValue() == 0; } catch (IOException | InterruptedException e) { return false; } } return false; } private static String toUrgency(TrayIcon.MessageType type) { switch (type) { case WARNING: case ERROR: return "critical"; default: return "normal"; } } private synchronized void playCustomSound() { long currentMTime = NOTIFICATION_FILE.exists() ? NOTIFICATION_FILE.lastModified() : CLIP_MTIME_BUILTIN; if (clip == null || currentMTime != lastClipMTime || !clip.isOpen()) { if (clip != null) { clip.close(); } try { clip = AudioSystem.getClip(); } catch (LineUnavailableException e) { lastClipMTime = CLIP_MTIME_UNLOADED; log.warn("Unable to play notification", e); Toolkit.getDefaultToolkit().beep(); return; } lastClipMTime = currentMTime; if (!tryLoadNotification()) { Toolkit.getDefaultToolkit().beep(); return; } } // Using loop instead of start + setFramePosition prevents a the clip // from not being played sometimes, presumably a race condition in the // underlying line driver clip.loop(1); } private boolean tryLoadNotification() { if (NOTIFICATION_FILE.exists()) { try { InputStream fileStream = new BufferedInputStream(new FileInputStream(NOTIFICATION_FILE)); try (AudioInputStream sound = AudioSystem.getAudioInputStream(fileStream)) { clip.open(sound); return true; } } catch (UnsupportedAudioFileException | IOException | LineUnavailableException e) { log.warn("Unable to load notification sound", e); } } // Otherwise load from the classpath InputStream fileStream = new BufferedInputStream(Notifier.class.getResourceAsStream("notification.wav")); try (AudioInputStream sound = AudioSystem.getAudioInputStream(fileStream)) { clip.open(sound); return true; } catch (UnsupportedAudioFileException | IOException | LineUnavailableException e) { log.warn("Unable to load builtin notification sound", e); } return false; } }