answer
stringlengths
17
10.2M
package com.imap4j.hbase; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.io.RowResult; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class HBaseConnector { public static Map retrievePost(String postId) throws IOException { final HTable table = new HTable(new HBaseConfiguration(), "blogposts"); final Map<String, String> post = new HashMap<String, String>(); final RowResult result = table.getRow(postId); for (byte[] column : result.keySet()) post.put(new String(column), new String(result.get(column).getValue())); return post; } public static void main(String[] args) throws IOException { Map blogpost = HBaseConnector.retrievePost("post1"); for (int i = 0; i < 10000; i++) System.out.println(blogpost.get("post:title") + " - " + blogpost.get("post:author")); } }
package com.jaku.core; public enum KeypressKeyValues { HOME("Home"), REV("Rev"), FWD("Fwd"), PLAY("Play"), SELECT("Select"), LEFT("Left"), RIGHT("Right"), DOWN("Down"), UP("Up"), BACK("Back"), INTANT_REPLAY("IntantReplay"), INFO("Info"), BACKSPACE("Backspace"), SEARCH("Search"), ENTER("Enter"), FIND_REMOTE("FindRemote"), VOLUME_DOWN("VolumeDown"), VOLUME_MUTE("VolumeMute"), VOLUME_UP("VolumeUp"), POWER_OFF("PowerOff"), POWER_ON("PowerOn"), CHANNELUP("ChannelUp"), CHANNELDOWN("ChannelDown"), INPUTTUNER("InputTuner"), INPUTHDMI1("InputHDMI1"), INPUTHDMI2("InputHDMI2"), INPUTHDMI3("InputHDMI3"), INPUTHDMI4("InputHDMI4"), INPUTAV1("InputAV1"), LIT_("Lit_"); private final String method; KeypressKeyValues(String method) { this.method = method; } public String getValue() { return method; } }
package com.mikesamuel.cil.ast; import javax.annotation.Nullable; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.mikesamuel.cil.parser.SourcePosition; /** * A node in a Java AST. */ public abstract class BaseNode { private final NodeVariant variant; private final ImmutableList<BaseNode> children; private final @Nullable String literalValue; private @Nullable SourcePosition sourcePosition; BaseNode( NodeVariant variant, Iterable<? extends BaseNode> children, @Nullable String literalValue) { this.variant = Preconditions.checkNotNull(variant); NodeType type = variant.getNodeType(); Preconditions.checkState(type.getNodeBaseType().isInstance(this)); this.children = ImmutableList.copyOf(children); this.literalValue = literalValue; } /** The particular variant within the production. */ public NodeVariant getVariant() { return variant; } /** Child nodes. */ public final ImmutableList<BaseNode> getChildren() { return children; } /** The value if any. */ public final @Nullable String getValue() { return literalValue; } /** The source position. Non-normative. */ public final @Nullable SourcePosition getSourcePosition() { return sourcePosition; } /** * @see #getSourcePosition() */ public final void setSourcePosition(SourcePosition newSourcePosition) { this.sourcePosition = newSourcePosition; } @Override public final String toString() { StringBuilder sb = new StringBuilder(); appendToStringBuilder(sb); return sb.toString(); } protected void appendToStringBuilder(StringBuilder sb) { sb.append('('); sb.append(variant); if (literalValue != null) { sb.append(" `").append(literalValue).append('`'); } for (BaseNode child : children) { sb.append(' '); child.appendToStringBuilder(sb); } sb.append(')'); } /** * Allows building nodes. */ public static abstract class Builder<N extends BaseNode, V extends NodeVariant> { private final V newNodeVariant; private final ImmutableList.Builder<BaseNode> newNodeChildren = ImmutableList.builder(); private Optional<String> newLiteralValue = Optional.absent(); protected Builder(V variant) { this.newNodeVariant = variant; } protected V getVariant() { return newNodeVariant; } protected ImmutableList<BaseNode> getChildren() { return newNodeChildren.build(); } protected String getLiteralValue() { return newLiteralValue.orNull(); } /** Adds a child node. */ public Builder<N, V> add(BaseNode child) { this.newNodeChildren.add(child); return this; } /** Specifies the value. */ public Builder<N, V> leaf(String leafLiteralValue) { this.newLiteralValue = Optional.of(leafLiteralValue); return this; } /** Builds a complete node. */ public abstract N build(); } @Override public final int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((children == null) ? 0 : children.hashCode()); result = prime * result + ((literalValue == null) ? 0 : literalValue.hashCode()); result = prime * result + ((variant == null) ? 0 : variant.hashCode()); return result; } @Override public final boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } BaseNode other = (BaseNode) obj; if (children == null) { if (other.children != null) { return false; } } else if (!children.equals(other.children)) { return false; } if (literalValue == null) { if (other.literalValue != null) { return false; } } else if (!literalValue.equals(other.literalValue)) { return false; } if (variant == null) { if (other.variant != null) { return false; } } else if (!variant.equals(other.variant)) { return false; } return true; } }
package com.oneliang.util.file; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.Queue; import java.util.Set; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.CopyOnWriteArrayList; import java.util.zip.ZipEntry; import java.util.zip.ZipException; import java.util.zip.ZipFile; import java.util.zip.ZipOutputStream; import com.oneliang.Constant; import com.oneliang.util.common.Generator; import com.oneliang.util.common.ObjectUtil; import com.oneliang.util.common.StringUtil; /** * @author Dandelion * @since 2008-06-17 file operate * File.list()String[],D,File.listFile()File[] * File.getPath(),getAbsolutePath() * FileInputStreamFileOutputStream,,,, */ public final class FileUtil { private static final FileCopyProcessor DEFAULT_FILE_COPY_PROCESSOR = new DefaultFileCopyProcessor(); private FileUtil() { } /** * is file exist,include directory or file * * @param path * directory or file * @return boolean */ public static boolean isExist(String path) { File file = new File(path); return file.exists(); } /** * is has file from directory * * @param directory * @param fileSuffix * @return boolean */ public static boolean isHasFile(String directory, String fileSuffix) { boolean result = false; File directoryFile = new File(directory); Queue<File> queue = new ConcurrentLinkedQueue<File>(); queue.add(directoryFile); while (!queue.isEmpty()) { File file = queue.poll(); if (file.isDirectory()) { File[] fileArray = file.listFiles(); if (fileArray != null) { queue.addAll(Arrays.asList(fileArray)); } } else if (file.isFile()) { if (file.getName().toLowerCase().endsWith(fileSuffix.toLowerCase())) { result = true; break; } } } return result; } /** * create directory * * @param directoryPath */ public static void createDirectory(final String directoryPath) { File file = new File(directoryPath); if (!file.exists()) { file.setReadable(true, false); file.setWritable(true, true); file.mkdirs(); } } /** * create file,full filename,signle empty file. * * @param fullFilename * @return boolean */ public static boolean createFile(final String fullFilename) { boolean result = false; File file = new File(fullFilename); createDirectory(file.getParent()); try { file.setReadable(true, false); file.setWritable(true, true); result = file.createNewFile(); } catch (Exception e) { throw new FileUtilException(e); } return result; } /** * delete all file * * @param directory */ public static void deleteAllFile(String directory) { List<File> fileList = new ArrayList<File>(); File directoryFile = new File(directory); Queue<File> queue = new ConcurrentLinkedQueue<File>(); queue.add(directoryFile); while (!queue.isEmpty()) { File file = queue.poll(); if (file.isDirectory()) { File[] fileArray = file.listFiles(); if (fileArray != null) { queue.addAll(Arrays.asList(fileArray)); } } fileList.add(file); } for (int i = fileList.size() - 1; i >= 0; i fileList.get(i).delete(); } } /** * copy file,default path to path * * @param from * @param to */ public static void copyFile(final String from, final String to) { copyFile(from, to, FileCopyType.PATH_TO_PATH, DEFAULT_FILE_COPY_PROCESSOR); } /** * copy file * * @param from * @param to * @param fileCopyType */ public static void copyFile(final String from, final String to, final FileCopyType fileCopyType) { copyFile(from, to, fileCopyType, DEFAULT_FILE_COPY_PROCESSOR); } /** * copy file * * @param from * @param to * @param fileCopyType * @param fileCopyProcessor */ public static void copyFile(final String from, final String to, final FileCopyType fileCopyType, FileCopyProcessor fileCopyProcessor) { switch (fileCopyType) { case FILE_TO_PATH: copyFileToPath(from, to, fileCopyProcessor); break; case FILE_TO_FILE: copyFileToFile(from, to, fileCopyProcessor); break; case PATH_TO_PATH: default: copyPathToPath(from, to, fileCopyProcessor); break; } } /** * copy path to path,copy process include directory copy * * @param fromPath * @param toPath * @param fileCopyProcessor */ public static void copyPathToPath(final String fromPath, final String toPath, FileCopyProcessor fileCopyProcessor) { File fromDirectoryFile = new File(fromPath); File toDirectoryFile = new File(toPath); String fromDirectoryPath = fromDirectoryFile.getAbsolutePath(); String toDirectoryPath = toDirectoryFile.getAbsolutePath(); if (fromDirectoryPath.equals(toDirectoryPath)) { toDirectoryPath = toDirectoryPath + "_copy"; } Queue<File> queue = new ConcurrentLinkedQueue<File>(); queue.add(fromDirectoryFile); while (!queue.isEmpty()) { File file = queue.poll(); String fromFilePath = file.getAbsolutePath(); String toFilePath = toDirectoryPath + fromFilePath.substring(fromDirectoryPath.length()); if (file.isDirectory()) { boolean result = true; if (fileCopyProcessor != null) { result = fileCopyProcessor.copyFileToFileProcess(fromFilePath, toFilePath, false); } if (result) { File[] fileArray = file.listFiles(); if (fileArray != null) { queue.addAll(Arrays.asList(fileArray)); } } } else if (file.isFile()) { if (fileCopyProcessor != null) { fileCopyProcessor.copyFileToFileProcess(fromFilePath, toFilePath, true); } } } } /** * @param fromFile * @param toPath * @param fileCopyProcessor */ private static void copyFileToPath(final String fromFile, final String toPath, final FileCopyProcessor fileCopyProcessor) { File from = new File(fromFile); File to = new File(toPath); if (from.exists() && from.isFile()) { createDirectory(toPath); String tempFromFile = from.getAbsolutePath(); String tempToFile = to.getAbsolutePath() + File.separator + from.getName(); copyFileToFile(tempFromFile, tempToFile, fileCopyProcessor); } } /** * unzip * * @param zipFullFilename * @param outputDirectory * @return List<String> */ public static List<String> unzip(String zipFullFilename, String outputDirectory) { return unzip(zipFullFilename, outputDirectory, null); } /** * unzip * * @param zipFullFilename * @param outputDirectory * @param zipEntryNameList,if * it is null or empty,will unzip all * @return List<String> */ public static List<String> unzip(String zipFullFilename, String outputDirectory, List<String> zipEntryNameList) { if (outputDirectory == null) { throw new NullPointerException("out put directory can not be null."); } createDirectory(outputDirectory); List<String> storeFileList = null; ZipFile zipFile = null; try { storeFileList = new ArrayList<String>(); zipFile = new ZipFile(zipFullFilename); String outputDirectoryAbsolutePath = new File(outputDirectory).getAbsolutePath(); Enumeration<? extends ZipEntry> enumeration = zipFile.entries(); while (enumeration.hasMoreElements()) { ZipEntry zipEntry = enumeration.nextElement(); String zipEntryName = zipEntry.getName(); boolean contains = false; if (zipEntryNameList == null || zipEntryNameList.isEmpty()) { contains = true; } else { if (zipEntryNameList.contains(zipEntryName)) { contains = true; } } if (contains) { InputStream inputStream = zipFile.getInputStream(zipEntry); String outputFullFilename = outputDirectoryAbsolutePath + Constant.Symbol.SLASH_LEFT + zipEntryName; if (zipEntry.isDirectory()) { createDirectory(outputFullFilename); } else { createFile(outputFullFilename); OutputStream outputStream = new FileOutputStream(outputFullFilename); try { byte[] buffer = new byte[Constant.Capacity.BYTES_PER_KB]; int length = -1; while ((length = inputStream.read(buffer, 0, buffer.length)) != -1) { outputStream.write(buffer, 0, length); outputStream.flush(); } } finally { if (inputStream != null) { inputStream.close(); } if (outputStream != null) { outputStream.close(); } } storeFileList.add(outputFullFilename); } } } } catch (Exception e) { throw new FileUtilException(e); } finally { try { if (zipFile != null) { zipFile.close(); } } catch (Exception e) { e.printStackTrace(); } } return storeFileList; } /** * zip * * @param outputZipFullFilename * @param directory */ public static void zip(String outputZipFullFilename, String directory) { zip(outputZipFullFilename, directory, StringUtil.BLANK); } /** * zip * * @param outputZipFullFilename * @param directory * @param fileSuffix */ public static void zip(String outputZipFullFilename, String directory, String fileSuffix) { zip(outputZipFullFilename, directory, fileSuffix, null); } /** * zip * * @param outputZipFullFilename * @param directory * @param fileSuffix * @param zipProcessor */ public static void zip(String outputZipFullFilename, String directory, String fileSuffix, ZipProcessor zipProcessor) { MatchOption matchOption=new MatchOption(directory); matchOption.fileSuffix=fileSuffix; List<String> fileList = FileUtil.findMatchFile(matchOption); if (fileList != null && !fileList.isEmpty()) { List<ZipEntryPath> zipEntryPathList = new ArrayList<ZipEntryPath>(); int outputFullFilenameLength = new File(directory).getAbsolutePath().length() + 1; for (String file : fileList) { String zipEntryName = file.substring(outputFullFilenameLength, file.length()); zipEntryName = zipEntryName.replace(Constant.Symbol.SLASH_RIGHT, Constant.Symbol.SLASH_LEFT); zipEntryPathList.add(new ZipEntryPath(file, new ZipEntry(zipEntryName), true)); } zip(outputZipFullFilename, null, zipEntryPathList, zipProcessor); } } /** * zip * * @param outputZipFullFilename * @param zipEntryPathList */ public static void zip(String outputZipFullFilename, List<ZipEntryPath> zipEntryPathList) { zip(outputZipFullFilename, null, zipEntryPathList); } /** * zip * * @param outputZipFullFilename * @param inputZipFullFilename,can * null,the entry will not from the input file * @param zipEntryPathList */ public static void zip(String outputZipFullFilename, String inputZipFullFilename, List<ZipEntryPath> zipEntryPathList) { zip(outputZipFullFilename, inputZipFullFilename, zipEntryPathList, null); } /** * zip * * @param outputZipFullFilename * @param inputZipFullFilename,can * null,the entry will not from the input file * @param zipProcessor */ public static void zip(String outputZipFullFilename, String inputZipFullFilename, ZipProcessor zipProcessor) { zip(outputZipFullFilename, inputZipFullFilename, (List<ZipEntryPath>)null, zipProcessor); } /** * zip * * @param outputZipFullFilename * @param inputZipFullFilename,can * null,the entry will not from the input file * @param zipEntryPathList * @param zipProcessor */ public static void zip(String outputZipFullFilename, String inputZipFullFilename, List<ZipEntryPath> zipEntryPathList, ZipProcessor zipProcessor) { ZipOutputStream zipOutputStream = null; ZipFile zipFile = null; Map<String, ZipEntryPath> zipEntryPathMap = new HashMap<String, ZipEntryPath>(); List<String> needToAddEntryNameList = new CopyOnWriteArrayList<String>(); if (zipEntryPathList != null) { for (ZipEntryPath zipEntryPath : zipEntryPathList) { zipEntryPathMap.put(zipEntryPath.zipEntry.getName(), zipEntryPath); needToAddEntryNameList.add(zipEntryPath.zipEntry.getName()); } } try { createFile(outputZipFullFilename); zipOutputStream = new ZipOutputStream(new FileOutputStream(outputZipFullFilename)); if (inputZipFullFilename != null) { zipFile = new ZipFile(inputZipFullFilename); Enumeration<? extends ZipEntry> enumeration = zipFile.entries(); while (enumeration.hasMoreElements()) { ZipEntry zipEntry = enumeration.nextElement(); String zipEntryName = zipEntry.getName(); InputStream inputStream = null; InputStream newInputStream = null; if (zipEntryPathMap.containsKey(zipEntryName)) { ZipEntryPath zipEntryPath = zipEntryPathMap.get(zipEntryName); needToAddEntryNameList.remove(zipEntryName); if (zipEntryPath.replace) { zipEntry = zipEntryPath.zipEntry; inputStream = new FileInputStream(zipEntryPath.fullFilename); } } if (inputStream == null) { inputStream = zipFile.getInputStream(zipEntry); if(zipProcessor!=null){ newInputStream = zipProcessor.zipEntryProcess(zipEntryName, inputStream); if(newInputStream!=null&&!newInputStream.equals(inputStream)){ inputStream.close(); } }else{ newInputStream = inputStream; } } ZipEntry newZipEntry=new ZipEntry(zipEntryName); addZipEntry(zipOutputStream, newZipEntry, newInputStream); } } for (String zipEntryName : needToAddEntryNameList) { ZipEntryPath zipEntryPath = zipEntryPathMap.get(zipEntryName); ZipEntry zipEntry = zipEntryPath.zipEntry; InputStream inputStream = new FileInputStream(zipEntryPath.fullFilename); InputStream newInputStream = null; if(zipProcessor!=null){ newInputStream = zipProcessor.zipEntryProcess(zipEntry.getName(), inputStream); if(newInputStream!=null&&!newInputStream.equals(inputStream)){ inputStream.close(); } }else{ newInputStream = inputStream; } addZipEntry(zipOutputStream, zipEntry, newInputStream); } } catch (Exception e) { throw new FileUtilException(e); } finally { try { if (zipOutputStream != null) { zipOutputStream.finish(); zipOutputStream.flush(); zipOutputStream.close(); } if (zipFile != null) { zipFile.close(); } } catch (Exception e) { throw new FileUtilException(e); } } } /** * merge zip file * * @param zipOutputFullFilename * @param mergeZipFullFilenameList */ public static void mergeZip(String zipOutputFullFilename, List<String> mergeZipFullFilenameList) { FileUtil.createFile(zipOutputFullFilename); ZipOutputStream zipOutputStream = null; try { zipOutputStream = new ZipOutputStream(new FileOutputStream(zipOutputFullFilename)); if (mergeZipFullFilenameList != null) { for (String zipFullFilename : mergeZipFullFilenameList) { if (isExist(zipFullFilename)) { ZipFile zipFile = new ZipFile(zipFullFilename); Enumeration<? extends ZipEntry> enumeration = zipFile.entries(); while (enumeration.hasMoreElements()) { ZipEntry zipEntry = enumeration.nextElement(); InputStream inputStream = zipFile.getInputStream(zipEntry); ZipEntry newZipEntry=new ZipEntry(zipEntry.getName()); addZipEntry(zipOutputStream, newZipEntry, inputStream); } zipFile.close(); } } } } catch (Exception e) { throw new FileUtilException(e); } finally { try { if (zipOutputStream != null) { zipOutputStream.close(); } } catch (Exception e) { throw new FileUtilException(e); } } } /** * add zip entry * * @param zipOutputStream * @param zipEntry * @param inputStream * @throws Exception */ public static void addZipEntry(ZipOutputStream zipOutputStream, ZipEntry zipEntry, InputStream inputStream) throws Exception { if (zipOutputStream == null || inputStream == null) { return; } try { zipOutputStream.putNextEntry(zipEntry); byte[] buffer = new byte[Constant.Capacity.BYTES_PER_KB]; int length = -1; while ((length = inputStream.read(buffer, 0, buffer.length)) != -1) { zipOutputStream.write(buffer, 0, length); zipOutputStream.flush(); } } catch (ZipException e) { // do nothing } finally { if (inputStream != null) { inputStream.close(); } zipOutputStream.closeEntry(); } } /** * read file * * @param fullFilename * @return byte[] */ public static byte[] readFile(String fullFilename) { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); InputStream inputStream = null; try { inputStream = new FileInputStream(fullFilename); copyStream(inputStream, byteArrayOutputStream); } catch (FileNotFoundException e) { throw new FileUtilException(e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { throw new FileUtilException(e); } } if (byteArrayOutputStream != null) { try { byteArrayOutputStream.close(); } catch (IOException e) { throw new FileUtilException(e); } } } return byteArrayOutputStream.toByteArray(); } /** * write file * * @param outputFullFilename * @param byteArray */ public static void writeFile(String outputFullFilename, byte[] byteArray) { InputStream inputStream = new ByteArrayInputStream(byteArray); FileUtil.createFile(outputFullFilename); OutputStream outputStream = null; try { outputStream = new FileOutputStream(outputFullFilename); copyStream(inputStream, outputStream); } catch (FileNotFoundException e) { throw new FileUtilException(e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { throw new FileUtilException(e); } } if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { throw new FileUtilException(e); } } } } /** * read file content ignore line * @param fullFilename * @return String */ public static String readFileContentIgnoreLine(String fullFilename) { StringBuilder stringBuilder = new StringBuilder(); BufferedReader bufferedReader = null; try { bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(fullFilename))); String line = null; while ((line = bufferedReader.readLine()) != null) { stringBuilder.append(line.trim()); } } catch (Exception e) { throw new FileUtilException(e); } finally { if (bufferedReader != null) { try { bufferedReader.close(); } catch (Exception e) { throw new FileUtilException(e); } } } return stringBuilder.toString(); } /** * copy stream , from input to output,it don't close * * @param inputStream * @param outputStream */ public static void copyStream(InputStream inputStream, OutputStream outputStream) { if (inputStream != null && outputStream != null) { try { int length = -1; byte[] buffer = new byte[Constant.Capacity.BYTES_PER_MB]; while ((length = inputStream.read(buffer, 0, buffer.length)) != -1) { outputStream.write(buffer, 0, length); outputStream.flush(); } } catch (Exception e) { throw new FileUtilException(e); } } } /** * merge file * * @param outputFullFilename * @param fullFilenameList */ public static void mergeFile(String outputFullFilename, List<String> fullFilenameList) { if (fullFilenameList != null && outputFullFilename != null) { OutputStream outputStream = null; try { outputStream = new FileOutputStream(outputFullFilename); for (String fullFilename : fullFilenameList) { InputStream inputStream = null; try { inputStream = new FileInputStream(fullFilename); copyStream(inputStream, outputStream); } catch (Exception e) { throw new FileUtilException(e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { throw new FileUtilException(e); } } } } } catch (Exception e) { throw new FileUtilException(e); } finally { if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { throw new FileUtilException(e); } } } } } /** * find match file directory * * @param matchOption * @return List<String> */ public static List<String> findMatchFileDirectory(MatchOption matchOption) { ObjectUtil.checkNotNull(matchOption, "matchOption can not be null."); matchOption.findFile=false; return findMatchFileOrMatchFileDirectory(matchOption); } /** * find match file * * @param matchOption * @return List<String> */ public static List<String> findMatchFile(MatchOption matchOption) { ObjectUtil.checkNotNull(matchOption, "matchOption can not be null."); matchOption.findFile=true; return findMatchFileOrMatchFileDirectory(matchOption); } /** * find match file or match file directory * @param matchOption * @return List<String> */ private static List<String> findMatchFileOrMatchFileDirectory(MatchOption matchOption) { String fileSuffix = StringUtil.nullToBlank(matchOption.fileSuffix); List<String> list = new ArrayList<String>(); Queue<File> queue = new ConcurrentLinkedQueue<File>(); if(matchOption.directory!=null){ File directoryFile = new File(matchOption.directory); queue.add(directoryFile); } while (!queue.isEmpty()) { File file = queue.poll(); if(!file.exists()){ continue; } boolean result = false; if (!file.isHidden() || matchOption.includeHidden) { result = true; } if (result) { if (file.isDirectory()) { File[] fileArray = file.listFiles(); if (fileArray != null) { queue.addAll(Arrays.asList(fileArray)); } } else if (file.isFile()) { if (file.getName().toLowerCase().endsWith(fileSuffix.toLowerCase())) { if (matchOption.findFile) { String fullFilename=null; if(matchOption.processor!=null){ fullFilename=matchOption.processor.onMatch(file); }else{ fullFilename=file.getAbsolutePath(); } //ignore when null if(fullFilename!=null){ list.add(fullFilename); } } else { String parentFullFilename=null; if(matchOption.processor!=null){ parentFullFilename=matchOption.processor.onMatch(file.getParentFile()); }else{ parentFullFilename=file.getParentFile().getAbsolutePath(); } //ignore when null if (parentFullFilename!=null&&!list.contains(parentFullFilename)) { list.add(parentFullFilename); } } } } } } return list; } /** * get zip entry map * * @param zipFullFilename * @return Map<String, String> */ private static Map<String, String> getZipEntryMap(String zipFullFilename) { ZipFile zipFile = null; Map<String, String> map = new HashMap<String, String>(); try { zipFile = new ZipFile(zipFullFilename); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry zipEntry = (ZipEntry) entries.nextElement(); if (!zipEntry.isDirectory()) { String key = zipEntry.getName(); String value = zipEntry.getCrc() + Constant.Symbol.DOT + zipEntry.getSize(); map.put(key, value); } } } catch (Exception e) { throw new FileUtilException(e); } finally { if (zipFile != null) { try { zipFile.close(); } catch (IOException e) { throw new FileUtilException(e); } } } return map; } /** * differ zip * * @param differentOutputFullFilename * @param oldZipFullFilename * @param newZipFullFilename */ public static void differZip(String differentOutputFullFilename, String oldZipFullFilename, String newZipFullFilename) { differZip(differentOutputFullFilename, oldZipFullFilename, newZipFullFilename, null); } /** * differ zip * * @param differentOutputFullFilename * @param oldZipFullFilename * @param newZipFullFilename * @param differZipProcessor */ public static void differZip(String differentOutputFullFilename, String oldZipFullFilename, String newZipFullFilename, DifferZipProcessor differZipProcessor) { Map<String, String> map = getZipEntryMap(oldZipFullFilename); ZipFile newZipFile = null; ZipOutputStream zipOutputStream = null; try { newZipFile = new ZipFile(newZipFullFilename); Enumeration<? extends ZipEntry> entries = newZipFile.entries(); FileUtil.createFile(differentOutputFullFilename); zipOutputStream = new ZipOutputStream(new FileOutputStream(differentOutputFullFilename)); while (entries.hasMoreElements()) { ZipEntry zipEntry = entries.nextElement(); if (!zipEntry.isDirectory()) { String zipEntryName = zipEntry.getName(); String oldZipEntryHash = map.get(zipEntryName); String newZipEntryHash = zipEntry.getCrc() + Constant.Symbol.DOT + zipEntry.getSize(); // old zip entry hash not exist is a new zip entry,if exist // is a modified zip entry if (oldZipEntryHash == null) { if (differZipProcessor != null) { differZipProcessor.addZipEntryProcess(zipEntryName); } System.out.println(String.format("found added entry, key=%s(%s/%s)", new Object[] { zipEntryName, oldZipEntryHash, newZipEntryHash })); ZipEntry newZipEntry = new ZipEntry(zipEntryName); addZipEntry(zipOutputStream, newZipEntry, newZipFile.getInputStream(zipEntry)); } else if (!newZipEntryHash.equals(oldZipEntryHash)) { if (differZipProcessor != null) { differZipProcessor.modifyZipEntryProcess(zipEntryName); } System.out.println(String.format("found modified entry, key=%s(%s/%s)", new Object[] { zipEntryName, oldZipEntryHash, newZipEntryHash })); ZipEntry newZipEntry = new ZipEntry(zipEntryName); addZipEntry(zipOutputStream, newZipEntry, newZipFile.getInputStream(zipEntry)); } map.remove(zipEntryName); } } Set<String> deleteKeySet = map.keySet(); for (String deleteKey : deleteKeySet) { if (differZipProcessor != null) { differZipProcessor.deleteZipEntryProcess(deleteKey); } } } catch (Exception e) { throw new FileUtilException(e); } finally { if (newZipFile != null) { try { newZipFile.close(); } catch (IOException e) { throw new FileUtilException(e); } } if (zipOutputStream != null) { try { zipOutputStream.finish(); } catch (IOException e) { throw new FileUtilException(e); } } } } /** * differ directory * @param differenOutputDirectory * @param oldDirectory * @param newDirectory */ public static void differDirectory(String differenOutputDirectory, String oldDirectory, String newDirectory){ List<String> oldFileList=FileUtil.findMatchFile(new MatchOption(oldDirectory)); String oldDirectoryAbsolutePath=new File(oldDirectory).getAbsolutePath(); Map<String,String> oldFileMD5Map=new HashMap<String,String>(); differenOutputDirectory=new File(differenOutputDirectory).getAbsolutePath(); for(String oldFile:oldFileList){ String key=new File(oldFile).getAbsolutePath().substring(oldDirectoryAbsolutePath.length()+1); key=key.replace(Constant.Symbol.SLASH_RIGHT, Constant.Symbol.SLASH_LEFT); String value=Generator.MD5File(oldFile); oldFileMD5Map.put(key, value); } List<String> newFileList=FileUtil.findMatchFile(new MatchOption(newDirectory)); String newDirectoryAbsolutePath=new File(newDirectory).getAbsolutePath(); for(String newFile:newFileList){ String key=new File(newFile).getAbsolutePath().substring(newDirectoryAbsolutePath.length()+1); key=key.replace(Constant.Symbol.SLASH_RIGHT, Constant.Symbol.SLASH_LEFT); String value=Generator.MD5File(newFile); String oldValue=oldFileMD5Map.get(key); if (oldValue == null || (!oldValue.equals(value))) { String toFile=differenOutputDirectory+Constant.Symbol.SLASH_LEFT+key; System.out.println("key:"+key+",oldValue:"+oldValue+",value:"+value); copyFile(newFile, toFile, FileCopyType.FILE_TO_FILE); } } } /** * generate simple file * * @param templateFullFilename * @param outputFullFilename * @param valueMap */ public static void generateSimpleFile(String templateFullFilename, String outputFullFilename, Map<String, String> valueMap) { InputStream inputStream = null; try { inputStream = new FileInputStream(templateFullFilename); generateSimpleFile(inputStream, outputFullFilename, valueMap); } catch (Exception e) { throw new FileUtilException(e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { throw new FileUtilException(e); } } } } /** * generate simple file * * @param templateInputStream * @param outputFullFilename * @param valueMap */ public static void generateSimpleFile(InputStream templateInputStream, String outputFullFilename, Map<String, String> valueMap) { BufferedReader bufferedReader = null; OutputStream outputStream = null; try { bufferedReader = new BufferedReader(new InputStreamReader(templateInputStream, Constant.Encoding.UTF8)); StringBuilder content = new StringBuilder(); String line = null; Set<Entry<String, String>> entrySet = valueMap.entrySet(); while ((line = bufferedReader.readLine()) != null) { for (Entry<String, String> entry : entrySet) { String key = entry.getKey(); String value = entry.getValue(); line = line.replace(key, value); } content.append(line); content.append(StringUtil.CRLF_STRING); } createFile(outputFullFilename); outputStream = new FileOutputStream(outputFullFilename); outputStream.write(content.toString().getBytes(Constant.Encoding.UTF8)); outputStream.flush(); } catch (Exception e) { throw new FileUtilException(e); } finally { if (bufferedReader != null) { try { bufferedReader.close(); } catch (IOException e) { throw new FileUtilException(e); } } if (outputStream != null) { try { outputStream.close(); } catch (Exception e) { throw new FileUtilException(e); } } } } /** * find file list with cache * @param directoryList * @param cacheProperties * @param fileSuffix,file suffix it will search file in source directory list * @param isFile if true the return list is source file else is the source directory * @return List<String> */ public static List<String> findFileListWithCache(List<String> directoryList,Properties cacheProperties,String fileSuffix,boolean isFile){ return findFileListWithCache(directoryList, cacheProperties, fileSuffix, isFile, null); } /** * find file list with cache * @param directoryList * @param cacheProperties * @param fileSuffix * @param isFile * @param cacheProcessor * @return List<String> */ public static List<String> findFileListWithCache(List<String> directoryList,Properties cacheProperties,String fileSuffix,boolean isFile,CacheProcessor cacheProcessor){ return findFileListWithCache(directoryList, cacheProperties, fileSuffix, isFile, false, cacheProcessor); } /** * find file list with cache * @param directoryList * @param cacheProperties * @param fileSuffix,file suffix it will search file in source directory list * @param findFile if true the return list is source file else is the source directory * @param includeHidden * @return List<String> */ public static List<String> findFileListWithCache(List<String> directoryList,Properties cacheProperties,String fileSuffix,boolean findFile,boolean includeHidden,CacheProcessor cacheProcessor){ List<String> sourceList=new ArrayList<String>(); //no cache if(cacheProperties==null){ if(directoryList!=null&&!directoryList.isEmpty()){ for(String directory:directoryList){ MatchOption matchOption=new MatchOption(directory); matchOption.fileSuffix=fileSuffix; matchOption.includeHidden=includeHidden; matchOption.findFile=findFile; sourceList.addAll(findMatchFileOrMatchFileDirectory(matchOption)); } } }else if(cacheProperties.isEmpty()){ List<String> fileList=new ArrayList<String>(); if(directoryList!=null&&!directoryList.isEmpty()){ for(String directory:directoryList){ MatchOption matchOption=new MatchOption(directory); matchOption.fileSuffix=fileSuffix; matchOption.includeHidden=includeHidden; fileList.addAll(FileUtil.findMatchFile(matchOption)); } } for(String fullFilename:fileList){ String cacheKey=fullFilename; if(cacheProcessor!=null){ cacheKey=cacheProcessor.keyProcess(cacheKey); } cacheProperties.setProperty(cacheKey, Generator.MD5File(fullFilename)); } if(findFile){ sourceList.addAll(fileList); }else{ if(directoryList!=null&&!directoryList.isEmpty()){ for(String directory:directoryList){ MatchOption matchOption=new MatchOption(directory); matchOption.fileSuffix=fileSuffix; matchOption.includeHidden=includeHidden; sourceList.addAll(findMatchFileDirectory(matchOption)); } } } }else{//with cache List<String> fileList=new ArrayList<String>(); if(directoryList!=null&&!directoryList.isEmpty()){ for(String directory:directoryList){ MatchOption matchOption=new MatchOption(directory); matchOption.fileSuffix=fileSuffix; matchOption.includeHidden=includeHidden; fileList.addAll(findMatchFile(matchOption)); } } for(String fullFilename:fileList){ String cacheKey=fullFilename; if(cacheProcessor!=null){ cacheKey=cacheProcessor.keyProcess(cacheKey); } String sourceFileMd5=Generator.MD5File(fullFilename); if(cacheProperties.containsKey(cacheKey)){ String md5=cacheProperties.getProperty(cacheKey); if(!sourceFileMd5.equals(md5)){ sourceList.add(fullFilename); cacheProperties.setProperty(cacheKey, sourceFileMd5); } }else{ sourceList.add(fullFilename); cacheProperties.setProperty(cacheKey, sourceFileMd5); } } } return sourceList; } /** * deal with file cache * @param propertiesFileMappingFullFilename * @param noCacheFileFinder * @param noCacheFileProcessor * @return List<String> */ public static List<String> dealWithFileCache(String propertiesFileMappingFullFilename, NoCacheFileFinder noCacheFileFinder, NoCacheFileProcessor noCacheFileProcessor){ Properties propertiesFileMapping=getPropertiesAutoCreate(propertiesFileMappingFullFilename); List<String> noCacheFileList=null; if(noCacheFileFinder==null){ throw new NullPointerException("noCacheFileFinder can not be null."); } noCacheFileList=noCacheFileFinder.findNoCacheFileList(propertiesFileMapping); boolean saveCache=false; if(noCacheFileProcessor!=null){ saveCache=noCacheFileProcessor.process(noCacheFileList); } if(saveCache){ saveProperties(propertiesFileMapping, propertiesFileMappingFullFilename); } return noCacheFileList; } /** * get properties,if is not exist will auto create * @param propertiesFullFilename * @return Properties */ public static Properties getPropertiesAutoCreate(String propertiesFullFilename){ if(!FileUtil.isExist(propertiesFullFilename)){ FileUtil.createFile(propertiesFullFilename); } return getProperties(propertiesFullFilename); } /** * get properties * @param propertiesFullFilename * @return Properties */ public static Properties getProperties(String propertiesFullFilename){ Properties properties=null; if(propertiesFullFilename!=null){ InputStream inputStream=null; try{ inputStream=new FileInputStream(propertiesFullFilename); properties=new Properties(); properties.load(inputStream); }catch(Exception e){ throw new FileUtilException(e); }finally{ if(inputStream!=null){ try { inputStream.close(); } catch (Exception e) { throw new FileUtilException(e); } } } } return properties; } /** * get properties from properties file,will auto create * @param file * @return Properties * @throws IOException */ public static final Properties getProperties(File file){ Properties properties=null; if(file!=null){ properties=getProperties(file.getAbsolutePath()); } return properties; } /** * save properties * @param properties * @param outputFullFilename */ public static void saveProperties(Properties properties, String outputFullFilename){ if(properties!=null&&outputFullFilename!=null){ OutputStream outputStream=null; try { outputStream=new FileOutputStream(outputFullFilename); properties.store(outputStream, null); } catch (Exception e) { throw new FileUtilException(e); } finally { if(outputStream!=null){ try{ outputStream.flush(); outputStream.close(); }catch (Exception e) { throw new FileUtilException(e); } } } } } public static class ZipEntryPath { private String fullFilename = null; private ZipEntry zipEntry = null; private boolean replace = false; public ZipEntryPath(String fullFilename, ZipEntry zipEntry) { this(fullFilename, zipEntry, false); } public ZipEntryPath(String fullFilename, ZipEntry zipEntry, boolean replace) { this.fullFilename = fullFilename; this.zipEntry = zipEntry; this.replace = replace; } } public static class FileUtilException extends RuntimeException { private static final long serialVersionUID = 3884649425767533205L; public FileUtilException(Throwable cause) { super(cause); } } /** * @param fromFile * @param toFile * @param fileCopyProcessor */ private static void copyFileToFile(final String fromFile, final String toFile, FileCopyProcessor fileCopyProcessor) { if (fileCopyProcessor != null) { createFile(toFile); fileCopyProcessor.copyFileToFileProcess(fromFile, toFile, true); } } public static enum FileCopyType { PATH_TO_PATH, FILE_TO_PATH, FILE_TO_FILE } public static interface FileCopyProcessor { /** * copyFileToFileProcess * * @param from,maybe * directory * @param to,maybe * directory * @param isFile,maybe * directory or file * @return boolean,if true keep going copy,only active in directory so * far */ public abstract boolean copyFileToFileProcess(final String from, final String to, final boolean isFile); } public static interface ZipProcessor{ /** * zip entry process * @param zipEntryName * @param inputStream * @return InputStream */ public abstract InputStream zipEntryProcess(final String zipEntryName,InputStream inputStream); } public static abstract interface CacheProcessor{ /** * key process,can change key to save cache * @param cacheKey * @return String */ public abstract String keyProcess(final String key); } public static abstract interface NoCacheFileProcessor{ /** * process * @param uncachedFileList * @return boolean,true is save cache else false */ public abstract boolean process(List<String> uncachedFileList); } public static abstract interface NoCacheFileFinder{ /** * find no cache file list * @param cacheFileMapping * @return List<String> */ public abstract List<String> findNoCacheFileList(Properties cacheFileMapping); } /** * match option */ public static class MatchOption{ public final String directory; public String fileSuffix=null; public boolean findFile=true; public boolean includeHidden=false; public Processor processor=null; public MatchOption(String directory) { this.directory=directory; } public static interface Processor{ /** * on match * @param file * @return String,return null then ignore the match file */ public abstract String onMatch(File file); } } public static abstract interface DifferZipProcessor { /** * add zip entry process * @param zipEntryName */ public abstract void addZipEntryProcess(String zipEntryName); /** * modify zip entry process * @param zipEntryName */ public abstract void modifyZipEntryProcess(String zipEntryName); /** * delete zip entry process * @param zipEntryName */ public abstract void deleteZipEntryProcess(String zipEntryName); } }
package com.pardot.rhombus; import com.datastax.driver.core.*; import com.datastax.driver.core.exceptions.AlreadyExistsException; import com.datastax.driver.core.utils.UUIDs; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.pardot.rhombus.cobject.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Date; import java.util.List; import java.util.Map; import java.util.UUID; public class ObjectMapper { private static Logger logger = LoggerFactory.getLogger(ObjectMapper.class); private static final int reasonableStatementLimit = 20; private boolean logCql = false; private Map<String,BoundStatement> boundStatementCache; private Session session; private CKeyspaceDefinition keyspaceDefinition; private CObjectCQLGenerator cqlGenerator; public ObjectMapper(Session session, CKeyspaceDefinition keyspaceDefinition) { this.boundStatementCache = Maps.newConcurrentMap(); this.session = session; this.keyspaceDefinition = keyspaceDefinition; this.cqlGenerator = new CObjectCQLGenerator(keyspaceDefinition.getDefinitions(),null); } /** * Build the tables contained in the keyspace definition. * This method assumes that its keyspace exists and * does not contain any tables. */ public void buildKeyspace(Boolean forceRebuild) { //we are about to rework the the keyspaces, so lets clear the bounded query cache this.boundStatementCache.clear(); //First build the shard index CQLStatement cql = CObjectCQLGenerator.makeCQLforShardIndexTableCreate(); try { executeCql(cql); } catch(Exception e) { if(forceRebuild) { CQLStatement dropCql = CObjectCQLGenerator.makeCQLforShardIndexTableDrop(); logger.debug("Attempting to drop table with cql {}", dropCql); executeCql(dropCql); executeCql(cql); } else { logger.debug("Not dropping shard index table"); } } //Now build the tables for each object if the definition contains tables if(keyspaceDefinition.getDefinitions() != null) { for(CDefinition definition : keyspaceDefinition.getDefinitions().values()) { CQLStatementIterator statementIterator = cqlGenerator.makeCQLforCreate(definition.getName()); CQLStatementIterator dropStatementIterator = cqlGenerator.makeCQLforDrop(definition.getName()); while(statementIterator.hasNext()) { cql = statementIterator.next(); CQLStatement dropCql = dropStatementIterator.next(); try { executeCql(cql); } catch (AlreadyExistsException e) { if(forceRebuild) { logger.debug("ForceRebuild is on, dropping table"); executeCql(dropCql); executeCql(cql); } else { logger.warn("Table already exists and will not be updated"); } } } } } } /** * This should never be used outside of testing * @param cql String of cql to execute */ public ResultSet executeCql(CQLStatement cql) { if(logCql) { logger.debug("Executing CQL: {}", cql.getQuery()); //TODO: log values } if(cql.isPreparable()){ //Do prepared statement BoundStatement bs = boundStatementCache.get(cql.getQuery()); if(bs == null){ PreparedStatement statement = session.prepare(cql.getQuery()); bs = new BoundStatement(statement); if(cql.isCacheable()){ boundStatementCache.put(cql.getQuery(),bs); } } return session.execute(bs.bind(cql.getValues())); } else{ //just run a normal execute without a prepared statement return session.execute(cql.getQuery()); } } /** * Insert a new object with values and key * @param objectType Type of object to insert * @param values Values to insert * @param key Time UUID to use as key * @return * @throws CQLGenerationException */ public UUID insert(String objectType, Map<String, Object> values, UUID key) throws CQLGenerationException { logger.debug("Insert {}", objectType); if(key == null) { key = UUIDs.timeBased(); } long timestamp = System.currentTimeMillis(); CQLStatementIterator statementIterator = cqlGenerator.makeCQLforInsert(objectType, values, key, timestamp); while(statementIterator.hasNext()) { CQLStatement cql = statementIterator.next(); executeCql(cql); } return key; } /** * Insert a new objectType with values * @param objectType Type of object to insert * @param values Values to insert * @return UUID of inserted object * @throws CQLGenerationException */ public UUID insert(String objectType, Map<String, Object> values) throws CQLGenerationException { return insert(objectType, values, (UUID)null); } /** * Used to insert an object with a UUID based on the provided timestamp * Best used for testing, as time resolution collisions are not accounted for * @param objectType Type of object to insert * @param values Values to insert * @param timestamp Timestamp to use to create the object UUID * @return the UUID of the newly inserted object */ public UUID insert(String objectType, Map<String, Object> values, Long timestamp) throws CQLGenerationException { UUID uuid = UUIDs.startOf(timestamp); return insert(objectType, values, uuid); } /** * Delete Object of type with id key * @param objectType Type of object to delete * @param key Key of object to delete */ public void delete(String objectType, UUID key) { CDefinition def = keyspaceDefinition.getDefinitions().get(objectType); Map<String, Object> values = getByKey(objectType, key); CQLStatementIterator statementIterator = cqlGenerator.makeCQLforDelete(objectType, key, values, null); mapResults(statementIterator, def, 0L); } /** * Update objectType with key using values * @param objectType Type of object to update * @param key Key of object to update * @param values Values to update * @return new UUID of the object * @throws CQLGenerationException */ public UUID update(String objectType, UUID key, Map<String, Object> values) throws CQLGenerationException { //Make a new key UUID newKey = UUIDs.startOf(UUIDs.unixTimestamp(key)); //Delete delete(objectType, key); //Insert return insert(objectType, values, newKey); } /** * * @param objectType Type of object to get * @param key Key of object to get * @return Object of type with key or null if it does not exist */ public Map<String, Object> getByKey(String objectType, UUID key) { CDefinition def = keyspaceDefinition.getDefinitions().get(objectType); CQLStatementIterator statementIterator = cqlGenerator.makeCQLforGet(objectType, key); List<Map<String, Object>> results = mapResults(statementIterator, def, 1L); if(results.size() > 0) { return results.get(0); } else { return null; } } /** * @param objectType Type of object to query * @param criteria Criteria to query by * @return List of objects that match the specified type and criteria * @throws CQLGenerationException */ public List<Map<String, Object>> list(String objectType, Criteria criteria) throws CQLGenerationException { CDefinition def = keyspaceDefinition.getDefinitions().get(objectType); CQLStatementIterator statementIterator = cqlGenerator.makeCQLforGet(objectType, criteria); return mapResults(statementIterator, def, criteria.getLimit()); } /** * Iterates through cql statements executing them in sequence and mapping the results until limit is reached * @param statementIterator Statement iterator to execute * @param definition definition to execute the statements against * @return Ordered resultset concatenating results from statements in statement iterator. */ private List<Map<String, Object>> mapResults(CQLStatementIterator statementIterator, CDefinition definition, Long limit) { List<Map<String, Object>> results = Lists.newArrayList(); int statementNumber = 0; int resultNumber = 0; while(statementIterator.hasNext(resultNumber) ) { CQLStatement cql = statementIterator.next(); logger.debug("Executing CQL: " + cql); ResultSet resultSet = executeCql(cql); for(Row row : resultSet) { Map<String, Object> result = mapResult(row, definition); results.add(result); resultNumber++; } statementNumber++; if((limit > 0 && resultNumber >= limit) || statementNumber > reasonableStatementLimit) { logger.debug("Breaking from mapping results"); break; } } return results; } /** * @param row The row to map * @param definition The definition to map the row on to * @return Data contained in a row mapped to the object described in definition. */ private Map<String, Object> mapResult(Row row, CDefinition definition) { Map<String, Object> result = Maps.newHashMap(); result.put("id", row.getUUID("id").toString()); for(CField field : definition.getFields().values()) { result.put(field.getName(), getFieldValue(row, field)); } return result; } private Object getFieldValue(Row row, CField field) { Object fieldValue; switch(field.getType()) { case ASCII: case VARCHAR: case TEXT: fieldValue = row.getString(field.getName()); break; case BIGINT: case COUNTER: fieldValue = row.getLong(field.getName()); break; case BLOB: fieldValue = row.getBytes(field.getName()); break; case BOOLEAN: fieldValue = row.getBool(field.getName()); break; case DECIMAL: fieldValue = row.getDecimal(field.getName()); break; case DOUBLE: fieldValue = row.getDouble(field.getName()); break; case FLOAT: fieldValue = row.getFloat(field.getName()); break; case INT: fieldValue = row.getInt(field.getName()); break; case TIMESTAMP: fieldValue = row.getDate(field.getName()); break; case UUID: case TIMEUUID: fieldValue = row.getUUID(field.getName()); break; case VARINT: fieldValue = row.getVarint(field.getName()); break; default: fieldValue = null; } return (fieldValue == null ? null : fieldValue); } public void setLogCql(boolean logCql) { this.logCql = logCql; } public void teardown() { session.shutdown(); } }
package com.smart.framework; import com.smart.framework.util.CastUtil; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class DataContext { private static final ThreadLocal<DataContext> dataContextContainer = new ThreadLocal<DataContext>(); private HttpServletRequest request; private HttpServletResponse response; public static void init(HttpServletRequest request, HttpServletResponse response) { DataContext dataContext = new DataContext(); dataContext.request = request; dataContext.response = response; dataContextContainer.set(dataContext); } public static void destroy() { dataContextContainer.remove(); } // Request private static HttpServletRequest getRequest() { return dataContextContainer.get().request; } // Response private static HttpServletResponse getResponse() { return dataContextContainer.get().response; } // Session private static HttpSession getSession() { return getRequest().getSession(); } // Servlet Context private static ServletContext getServletContext() { return getRequest().getServletContext(); } // Request public static class Request { // Request public static void put(String key, Object value) { getRequest().setAttribute(key, value); } // Request @SuppressWarnings("unchecked") public static <T> T get(String key) { return (T) getRequest().getAttribute(key); } // Request public static void remove(String key) { getRequest().removeAttribute(key); } // Request public static Map<String, Object> getAll() { Map<String, Object> map = new HashMap<String, Object>(); Enumeration<String> names = getRequest().getAttributeNames(); while (names.hasMoreElements()) { String name = names.nextElement(); map.put(name, getRequest().getAttribute(name)); } return map; } } // Response public static class Response { // Response public static void put(String key, Object value) { getResponse().setHeader(key, CastUtil.castString(value)); } // Response @SuppressWarnings("unchecked") public static <T> T get(String key) { return (T) getResponse().getHeader(key); } // Response public static Map<String, Object> getAll() { Map<String, Object> map = new HashMap<String, Object>(); for (String name : getResponse().getHeaderNames()) { map.put(name, getResponse().getHeader(name)); } return map; } } // Session public static class Session { // Session public static void put(String key, Object value) { getSession().setAttribute(key, value); } // Session @SuppressWarnings("unchecked") public static <T> T get(String key) { return (T) getSession().getAttribute(key); } // Session public static void remove(String key) { getSession().removeAttribute(key); } // Session public static Map<String, Object> getAll() { Map<String, Object> map = new HashMap<String, Object>(); Enumeration<String> names = getSession().getAttributeNames(); while (names.hasMoreElements()) { String name = names.nextElement(); map.put(name, getSession().getAttribute(name)); } return map; } // Session public static void removeAll() { getSession().invalidate(); } } // ServletContext public static class Context { // ServletContext public static void put(String key, Object value) { getServletContext().setAttribute(key, value); } // ServletContext @SuppressWarnings("unchecked") public static <T> T get(String key) { return (T) getServletContext().getAttribute(key); } // ServletContext public static void remove(String key) { getServletContext().removeAttribute(key); } // ServletContext public static Map<String, Object> getAll() { Map<String, Object> map = new HashMap<String, Object>(); Enumeration<String> names = getServletContext().getAttributeNames(); while (names.hasMoreElements()) { String name = names.nextElement(); map.put(name, getServletContext().getAttribute(name)); } return map; } } }
package com.timgroup.tucker.info; public final class Report { private static final Object NO_VALUE = new Object(); public static Status worstStatus(Iterable<Report> reports) { Status worst = Status.OK; for (Report report : reports) { worst = worst.or(report.getStatus()); } return worst; } private final Status status; private final Object value; public Report(Status status, Object value) { this.status = status; this.value = (value == null) ? NO_VALUE : value; } public Report(Status status) { this(status, NO_VALUE); } public Report(Throwable e) { this(Status.CRITICAL, e); } public Status getStatus() { return status; } public boolean hasValue() { return value != NO_VALUE; } public boolean isSuccessful() { return !(value instanceof Throwable); } public Object getValue() { return value; } public Throwable getException() { return (Throwable) value; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((status == null) ? 0 : status.hashCode()); result = prime * result + ((value == null) ? 0 : value.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; Report other = (Report) obj; if (status != other.status) return false; if (value == null) { if (other.value != null) return false; } else if (!value.equals(other.value)) return false; return true; } }
package de.ailis.usb4java.libusb; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URISyntaxException; import java.net.URL; /** * Utility class to load native libraries from classpath. * * @author Klaus Reimer (k@ailis.de) */ public final class Loader { /** Buffer size used for copying data. */ private static final int BUFFER_SIZE = 8192; /** Constant for Mac OS X operating system. */ private static final String OS_MACOSX = "macosx"; /** Constant for Linux operating system. */ private static final String OS_LINUX = "linux"; /** Constant for Windows operating system. */ private static final String OS_WINDOWS = "windows"; /** Constant for FreeBSD operating system. */ private static final String OS_FREEBSD = "freebsd"; /** Constant for SunOS operating system. */ private static final String OS_SUNOS = "sunos"; /** Constant for i386 architecture. */ private static final String ARCH_I386 = "i386"; /** Constant for x86 architecture. */ private static final String ARCH_X86 = "x86"; /** Constant for x86_64 architecture. */ private static final String ARCH_X86_64 = "x86_64"; /** Constant for amd64 architecture. */ private static final String ARCH_AMD64 = "amd64"; /** Constant for so file extension. */ private static final String EXT_SO = "so"; /** Constant for dll file extension. */ private static final String EXT_DLL = "dll"; /** Constant for dylib file extension. */ private static final String EXT_DYLIB = "dylib"; /** The temporary directory for native libraries. */ private static File tmp; /** If library is already loaded. */ private static boolean loaded = false; /** * Private constructor to prevent instantiation. */ private Loader() { // Nothing to do here } /** * Returns the operating system name. This could be "linux", "windows" or * "macosx" or (for any other non-supported platform) the value of the * "os.name" property converted to lower case and with removed space * characters. * * @return The operating system name. */ private static String getOS() { final String os = System.getProperty("os.name"); if (os.toLowerCase().contains(OS_WINDOWS)) return OS_WINDOWS; return os.toLowerCase().replace(" ", ""); } /** * Returns the CPU architecture. This will be "x86" or "x86_64" (Platform * names i386 und amd64 are converted accordingly) or (when platform is * unsupported) the value of os.arch converted to lower-case and with * removed space characters. * * @return The CPU architecture */ private static String getArch() { final String arch = System.getProperty("os.arch"); if (arch.equals(ARCH_I386)) return ARCH_X86; if (arch.equals(ARCH_AMD64)) return ARCH_X86_64; return arch.toLowerCase().replace(" ", ""); } /** * Returns the shared library extension name. * * @return The shared library extension name. */ private static String getExt() { final String os = getOS(); final String key = "usb4java.libext." + getOS(); final String ext = System.getProperty(key); if (ext != null) return ext; if (os.equals(OS_LINUX) || os.equals(OS_FREEBSD) || os.equals(OS_SUNOS)) return EXT_SO; if (os.equals(OS_WINDOWS)) return EXT_DLL; if (os.equals(OS_MACOSX)) return EXT_DYLIB; throw new LoaderException("Unable to determine the shared library " + "file extension for operating system '" + os + "'. Please specify Java parameter -D" + key + "=<FILE-EXTENSION>"); } /** * Creates the temporary directory used for unpacking the native libraries. * This directory is marked for deletion on exit. * * @return The temporary directory for native libraries. */ private static File createTempDirectory() { // Return cached tmp directory when already created if (tmp != null) return tmp; try { tmp = File.createTempFile("usb4java", null); if (!tmp.delete()) throw new IOException("Unable to delete temporary file " + tmp); if (!tmp.mkdirs()) throw new IOException("Unable to create temporary directory " + tmp); tmp.deleteOnExit(); return tmp; } catch (final IOException e) { throw new LoaderException("Unable to create temporary directory " + "for usb4java natives: " + e, e); } } /** * Returns the platform name. This could be for example "linux-x86" or * "windows-x86_64". * * @return The architecture name. Never null. */ private static String getPlatform() { return getOS() + "-" + getArch(); } /** * Returns the name of the usb4java native library. This could be * "libusb4java.dll" for example. * * @return The usb4java native library name. Never null. */ private static String getLibName() { return "libusb4java." + getExt(); } /** * Returns the name of the libusb native library. This could be * "libusb0.dll" for example or null if this library is not needed on the * current platform (Because it is provided by the operating system). * * @return The libusb native library name or null if not needed. */ private static String getExtraLibName() { final String os = getOS(); if (os.equals(OS_WINDOWS)) return "libusb-1.0." + EXT_DLL; return null; } /** * Copies the specified input stream to the specified output file. * * @param input * The input stream. * @param output * The output file. * @throws IOException * If copying failed. */ private static void copy(final InputStream input, final File output) throws IOException { final byte[] buffer = new byte[BUFFER_SIZE]; final FileOutputStream stream = new FileOutputStream(output); try { int read; while ((read = input.read(buffer)) != -1) { stream.write(buffer, 0, read); } } finally { stream.close(); } } /** * Extracts a single library. * * @param platform * The platform name (For example "linux-x86") * @param lib * The library name to extract (For example "libusb0.dll") * @return The absolute path to the extracted library. */ private static String extractLibrary(final String platform, final String lib) { // Extract the usb4java library final String source = '/' + Loader.class.getPackage().getName().replace('.', '/') + '/' + platform + "/" + lib; // Check if native library is present final URL url = Loader.class.getResource(source); if (url == null) throw new LoaderException( "Native library not found in classpath: " + source); // If native library was found in an already extracted form then // return this one without extracting it if ("file".equals(url.getProtocol())) { try { return new File(url.toURI()).getAbsolutePath(); } catch (final URISyntaxException e) { // Can't happen because we are not constructing the URI // manually. But even when it happens then we fall back to // extracting the library. throw new LoaderException(e.toString(), e); } } // Extract the library and return the path to the extracted file. final File dest = new File(createTempDirectory(), lib); try { final InputStream stream = Loader.class.getResourceAsStream(source); if (stream == null) throw new LoaderException("Unable to find " + source + " in the classpath"); try { copy(stream, dest); } finally { stream.close(); } } catch (final IOException e) { throw new LoaderException( "Unable to extract native library " + source + " to " + dest + ": " + e, e); } // Mark usb4java library for deletion dest.deleteOnExit(); return dest.getAbsolutePath(); } /** * Loads the libusbx native wrapper library. Can be safely called multiple * times. Duplicate calls are ignored. This method is automatically called * when the {@link LibUsb} class is loaded. When you need to do it earlier * (To catch exceptions for example) then simply call this method manually. * * @throws LoaderException * When loading the native wrapper libraries failed. */ public static void load() { if (loaded) return; final String platform = getPlatform(); final String lib = getLibName(); final String extraLib = getExtraLibName(); if (extraLib != null) System.load(extractLibrary(platform, extraLib)); System.load(extractLibrary(platform, lib)); loaded = true; } }
package de.prob2.ui.menu; import com.google.inject.Inject; import com.google.inject.Singleton; import de.prob2.ui.prob2fx.CurrentStage; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.web.WebEngine; import javafx.scene.web.WebView; import javafx.stage.Stage; @Singleton public class ReportBugStage extends Stage { @Inject public ReportBugStage(FXMLLoader loader, CurrentStage currentStage) { WebView webView = new WebView(); WebEngine webEnging = webView.getEngine(); webEnging.setJavaScriptEnabled(true); webEnging.load("https://probjira.atlassian.net/secure/RapidBoard.jspa?rapidView=8"); Scene scene = new Scene(webView); scene.getStylesheets().add("prob.css"); this.setTitle("Report Bug"); this.setScene(scene); currentStage.register(this); } }
package de.retest.recheck.ignore; import de.retest.recheck.ui.descriptors.Element; import de.retest.recheck.ui.descriptors.IdentifyingAttributes; import de.retest.recheck.ui.diff.AttributeDifference; public interface Filter { /** * Returns <code>true</code> if the element <em>and all of its child elements</em>, so essentially the whole subtree * this element is the root of, should be completely filtered (all attributes of all elements, whether elements are * added or removed). * * @param element * The element in question. * @return <code>true</code> if the given element should be completely filtered. */ boolean matches( final Element element ); /** * Returns <code>true</code> if the given attribute difference as specified by the triple (attribute-key, * expectedValue, actualValue) should be filtered for the given element as specified by its * {@link IdentifyingAttributes}. * * Note that for some elements all values of a given attribute key could be filtered, or an attribute key for all * elements. But sometimes one wants to specify that a certain difference is meaningless, such as * <code>Times Roman</code> vs. <code>Times New Roman</code> for font-family or a 5px difference for outline. * * If {@link #matches(Element)} returns <code>true</code>, this method must always return <code>true</code>. Can * return any value only if {@link #matches(Element)} returns <code>false</code>. * * @param element * The element in question. * @param attributeDifference * The attribute difference for the given element. * @return <code>true</code> if the given attribute difference should be filtered. */ default boolean matches( final Element element, final AttributeDifference attributeDifference ) { return matches( element ); } public static final Filter FILTER_NOTHING = new Filter() { @Override public boolean matches( final Element element ) { return false; } @Override public boolean matches( final Element element, final AttributeDifference attributeDifference ) { return false; } }; }
package edu.jhu.prim.util.math; import edu.jhu.prim.util.SafeCast; public class FastMath { public static final double LOG2 = log(2); //@Opt(hasArg = true, description = "Whether to use a log-add table or log-add exact.") public static boolean useLogAddTable = false; public static int factorial(int n) { if( n <= 1 ) { return 1; } else { return n * factorial(n - 1); } } /** * Adds two probabilities that are stored as log probabilities. * @param x log(p) * @param y log(q) * @return log(p + q) = log(exp(x) + exp(y)) */ public static double logAdd(double x, double y) { if (FastMath.useLogAddTable) { return LogAddTable.logAdd(x,y); } else { return FastMath.logAddExact(x,y); } } public static double logSubtract(double x, double y) { if (FastMath.useLogAddTable) { return LogAddTable.logSubtract(x,y); } else { return FastMath.logSubtractExact(x,y); } } public static double logAddExact(double x, double y) { // p = 0 or q = 0, where x = log(p), y = log(q) if (Double.NEGATIVE_INFINITY == x) { return y; } else if (Double.NEGATIVE_INFINITY == y) { return x; } // p != 0 && q != 0 if (y <= x) { return x + Math.log1p(FastMath.exp(y - x)); } else { return y + Math.log1p(FastMath.exp(x - y)); } } public static double logSubtractExact(double x, double y) { if (x < y) { throw new IllegalStateException("x must be >= y. x=" + x + " y=" + y); } // p = 0 or q = 0, where x = log(p), y = log(q) if (Double.NEGATIVE_INFINITY == y) { return x; } else if (Double.NEGATIVE_INFINITY == x) { return y; } // p != 0 && q != 0 return x + Math.log1p(-FastMath.exp(y - x)); } public static double log(double d) { return Math.log(d); } public static double exp(double d) { return Math.exp(d); } public static double log2(double d) { return log(d) / FastMath.LOG2; } public static double logForIlp(double weight) { if (weight == 0.0 || weight == -0.0) { // CPLEX doesn't accept exponents larger than 37 -- it seems to be // cutting off at something close to the 32-bit float limit of // 3.4E38. // Before, we used -1E25 since we could add 1 trillion of these // together and stay in in the coefficient limit. // Now, we use -1E10 because -1E25 causes numerical stability issues // for the simplex algorithm return -1E10; } return log(weight); } public static double sqrt(double value) { // TODO: Switch to a fast implementation is this gets used more heavily. return Math.sqrt(value); } public static float log(float d) { return SafeCast.safeDoubleToFloat(Math.log((double) d)); } public static float exp(float d) { return SafeCast.safeDoubleToFloat(Math.exp((double) d)); } public static float log2(float d) { return SafeCast.safeDoubleToFloat(log2((double) d)); } public static float logForIlp(float d) { return SafeCast.safeDoubleToFloat(logForIlp((double) d)); } public static float logAdd(float x, float y) { return SafeCast.safeDoubleToFloat(logAdd((double) x, (double) y)); } public static float logSubtract(float x, float y) { return SafeCast.safeDoubleToFloat(logSubtract((double) x, (double) y)); } public static float sqrt(float value) { return SafeCast.safeDoubleToFloat(sqrt((double) value)); } /** * Modulo operator where all numbers evaluate to a positive remainder. * * @param val The value to mod. * @param mod The mod. * @return val modulo mod */ public static int mod(int val, int mod) { val = val % mod; if (val < 0) { val += mod; } return val; } }
package hprose.server; import hprose.common.HproseContext; import hprose.common.HproseMethods; import hprose.io.ByteBufferStream; import java.io.IOException; import java.lang.reflect.Type; import java.util.HashMap; import javax.servlet.AsyncContext; import javax.servlet.AsyncEvent; import javax.servlet.AsyncListener; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class HproseHttpService extends HproseService { private boolean crossDomainEnabled = false; private boolean p3pEnabled = false; private boolean getEnabled = true; private long timeout = 30000; private final HashMap<String, Boolean> origins = new HashMap<String, Boolean>(); private final static ThreadLocal<HttpContext> currentContext = new ThreadLocal<HttpContext>(); public static HttpContext getCurrentContext() { return currentContext.get(); } @Override public HproseMethods getGlobalMethods() { if (globalMethods == null) { globalMethods = new HproseHttpMethods(); } return globalMethods; } @Override public void setGlobalMethods(HproseMethods methods) { if (methods instanceof HproseHttpMethods) { this.globalMethods = methods; } else { throw new ClassCastException("methods must be a HproseHttpMethods instance"); } } public boolean isCrossDomainEnabled() { return crossDomainEnabled; } public void setCrossDomainEnabled(boolean enabled) { crossDomainEnabled = enabled; } public boolean isP3pEnabled() { return p3pEnabled; } public void setP3pEnabled(boolean enabled) { p3pEnabled = enabled; } public boolean isGetEnabled() { return getEnabled; } public void setGetEnabled(boolean enabled) { getEnabled = enabled; } public void addAccessControlAllowOrigin(String origin) { origins.put(origin, true); } public void removeAccessControlAllowOrigin(String origin) { origins.remove(origin); } public void setTimeout(long value) { timeout = value; } public long getTimeout() { return timeout; } @Override protected Object[] fixArguments(Type[] argumentTypes, Object[] arguments, HproseContext context) { int count = arguments.length; HttpContext httpContext = (HttpContext)context; if (argumentTypes.length != count) { Object[] args = new Object[argumentTypes.length]; System.arraycopy(arguments, 0, args, 0, count); Class<?> argType = (Class<?>) argumentTypes[count]; if (argType.equals(HproseContext.class)) { args[count] = context; } else if (argType.equals(HttpContext.class)) { args[count] = httpContext; } else if (argType.equals(HttpServletRequest.class)) { args[count] = httpContext.getRequest(); } else if (argType.equals(HttpServletResponse.class)) { args[count] = httpContext.getResponse(); } else if (argType.equals(HttpSession.class)) { args[count] = httpContext.getSession(); } else if (argType.equals(ServletContext.class)) { args[count] = httpContext.getApplication(); } else if (argType.equals(ServletConfig.class)) { args[count] = httpContext.getConfig(); } return args; } return arguments; } protected void sendHeader(HttpContext httpContext) throws IOException { if (event != null && HproseHttpServiceEvent.class.isInstance(event)) { ((HproseHttpServiceEvent)event).onSendHeader(httpContext); } HttpServletRequest request = httpContext.getRequest(); HttpServletResponse response = httpContext.getResponse(); response.setContentType("text/plain"); if (p3pEnabled) { response.setHeader("P3P", "CP=\"CAO DSP COR CUR ADM DEV TAI PSA PSD " + "IVAi IVDi CONi TELo OTPi OUR DELi SAMi " + "OTRi UNRi PUBi IND PHY ONL UNI PUR FIN " + "COM NAV INT DEM CNT STA POL HEA PRE GOV\""); } if (crossDomainEnabled) { String origin = request.getHeader("Origin"); if (origin != null && !origin.equals("null")) { if (origins.isEmpty() || origins.containsKey(origin)) { response.setHeader("Access-Control-Allow-Origin", origin); response.setHeader("Access-Control-Allow-Credentials", "true"); } } else { response.setHeader("Access-Control-Allow-Origin", "*"); } } } public void handle(HttpContext httpContext) throws IOException { handle(httpContext, null); } public void handle(HttpContext httpContext, HproseHttpMethods methods) throws IOException { sendHeader(httpContext); String method = httpContext.getRequest().getMethod(); if (method.equals("GET")) { if (getEnabled) { ByteBufferStream ostream = null; try { ostream = doFunctionList(methods, httpContext); httpContext.getResponse().setContentLength(ostream.available()); ostream.writeTo(httpContext.getResponse().getOutputStream()); } catch (IOException ex) { fireErrorEvent(ex, httpContext); } finally { if (ostream != null) { ostream.close(); } } } else { httpContext.getResponse().sendError(HttpServletResponse.SC_FORBIDDEN); } } else if (method.equals("POST")) { if (httpContext.getRequest().isAsyncSupported()) { asyncHandle(httpContext, methods); } else { syncHandle(httpContext, methods); } } } private void asyncHandle(final HttpContext httpContext, final HproseHttpMethods methods) { final AsyncContext async = httpContext.getRequest().startAsync(); async.setTimeout(timeout); async.addListener(new AsyncListener() { public void onComplete(AsyncEvent ae) throws IOException { } public void onTimeout(AsyncEvent ae) throws IOException { ByteBufferStream ostream = sendError(ae.getThrowable(), httpContext); ae.getSuppliedResponse().setContentLength(ostream.available()); ostream.writeTo(ae.getSuppliedResponse().getOutputStream()); } public void onError(AsyncEvent ae) throws IOException { } public void onStartAsync(AsyncEvent ae) throws IOException { } }); async.start(new Runnable() { public void run() { ByteBufferStream istream = null; ByteBufferStream ostream = null; try { currentContext.set(httpContext); istream = new ByteBufferStream(); istream.readFrom(async.getRequest().getInputStream()); ostream = handle(istream, methods, httpContext); async.getResponse().setContentLength(ostream.available()); ostream.writeTo(async.getResponse().getOutputStream()); } catch (IOException ex) { fireErrorEvent(ex, httpContext); } finally { currentContext.remove(); if (istream != null) { istream.close(); } if (ostream != null) { ostream.close(); } async.complete(); } } }); } private void syncHandle(HttpContext httpContext, HproseHttpMethods methods) throws IOException { ByteBufferStream istream = null; ByteBufferStream ostream = null; try { currentContext.set(httpContext); istream = new ByteBufferStream(); istream.readFrom(httpContext.getRequest().getInputStream()); ostream = handle(istream, methods, httpContext); httpContext.getResponse().setContentLength(ostream.available()); ostream.writeTo(httpContext.getResponse().getOutputStream()); } catch (IOException ex) { fireErrorEvent(ex, httpContext); } finally { currentContext.remove(); if (istream != null) { istream.close(); } if (ostream != null) { ostream.close(); } } } }
package info.bowkett.joxy; import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; public class RequestParser { public Request parseRequest(String request) { final Map<String, String> values = new HashMap<String, String>(); final String lines [] = request.split("\n"); for (String line : lines) { parseLine(values, line); } return new Request(values.get("HOST"), values.get("PROXY-CONNECTION"), values.get("CACHE-CONTROL"), values.get("ACCEPT"), values.get("USER-AGENT"), values.get("ACCEPT-ENCODING"), values.get("ACCEPT-LANGUAGE"), values.get("COOKIE")); } private void parseLine(Map<String, String> values, String line) { final int firstSpaceIndex = line.indexOf(' '); if(firstSpaceIndex > -1){ final String key = line.substring(0, firstSpaceIndex); final String value = line.substring(firstSpaceIndex +1); values.put(clean(key), value); } } /** * removes extraneous spaces or colons in the key * @param key * @return */ private String clean(String key) { return key.replaceAll(" |:", "").toUpperCase(); } }
package lambdasinaction.chap4; import java.util.stream.*; import java.util.*; import static java.util.stream.Collectors.toList; import static lambdasinaction.chap4.Dish.menu; public class Filtering{ public static void main(String...args){ // Filtering with predicate List<Dish> vegetarianMenu = menu.stream() .filter(Dish::isVegetarian) .collect(toList()); vegetarianMenu.forEach(System.out::println); // Filtering unique elements List<Integer> numbers = Arrays.asList(1, 2, 1, 3, 3, 2, 4); numbers.stream() .filter(i -> i % 2 == 0) .distinct() .forEach(System.out::println); // Truncating a stream List<Dish> dishesLimit3 = menu.stream() .filter(d -> d.getCalories() > 300) .limit(3) .collect(toList()); dishesLimit3.forEach(System.out::println); // Skipping elements List<Dish> dishesSkip2 = menu.stream() .filter(d -> d.getCalories() > 300) .skip(2) .collect(toList()); dishesSkip2.forEach(System.out::println); } }
package me.academeg.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore; import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore; import javax.sql.DataSource; @Configuration public class OAuth2Config { @Configuration @EnableResourceServer protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter { @Override public void configure(HttpSecurity http) throws Exception { http .exceptionHandling() .and() .authorizeRequests() .anyRequest().authenticated(); } } @Configuration @EnableAuthorizationServer protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter { @Autowired @Qualifier("authenticationManagerBean") private AuthenticationManager authenticationManager; @Autowired private DataSource dataSource; @Override public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception { oauthServer .tokenKeyAccess("permitAll()") .checkTokenAccess("isAuthenticated()"); } @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.inMemory() .withClient("web_app") .secret("secret_key") .authorizedGrantTypes("password", "refresh_token") .scopes("read", "write") .autoApprove(true); } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints .tokenStore(tokenStoreBean()) .authenticationManager(authenticationManager); } @Bean public TokenStore tokenStoreBean() { return new JdbcTokenStore(dataSource); } } }
package net.sf.jabref; import java.awt.Color; import java.awt.Toolkit; import java.awt.event.InputEvent; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.StringReader; import java.util.*; import java.util.prefs.BackingStoreException; import java.util.prefs.InvalidPreferencesFormatException; import java.util.prefs.Preferences; import java.net.InetAddress; import java.net.UnknownHostException; import javax.swing.*; import net.sf.jabref.gui.*; import net.sf.jabref.gui.actions.CleanUpAction; import net.sf.jabref.gui.entryeditor.EntryEditorTabList; import net.sf.jabref.gui.keyboard.KeyBinds; import net.sf.jabref.gui.preftabs.ImportSettingsTab; import net.sf.jabref.importer.fileformat.ImportFormat; import net.sf.jabref.logic.l10n.Localization; import net.sf.jabref.logic.labelPattern.GlobalLabelPattern; import net.sf.jabref.logic.util.OS; import net.sf.jabref.model.entry.CustomEntryType; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import net.sf.jabref.exporter.CustomExportList; import net.sf.jabref.exporter.ExportComparator; import net.sf.jabref.external.DroppedFileHandler; import net.sf.jabref.external.ExternalFileType; import net.sf.jabref.external.UnknownExternalFileType; import net.sf.jabref.importer.CustomImportList; import net.sf.jabref.logic.remote.RemotePreferences; import net.sf.jabref.specialfields.SpecialFieldsUtils; import net.sf.jabref.logic.util.strings.StringUtil; public class JabRefPreferences { private static final Log LOGGER = LogFactory.getLog(JabRefPreferences.class); /** * HashMap that contains all preferences which are set by default */ public final HashMap<String, Object> defaults = new HashMap<String, Object>(); /* contents of the defaults HashMap that are defined in this class. * There are more default parameters in this map which belong to separate preference classes. */ public static final String EMACS_PATH = "emacsPath"; public static final String EMACS_ADDITIONAL_PARAMETERS = "emacsParameters"; public static final String EMACS_23 = "emacsUseV23InsertString"; public static final String FONT_FAMILY = "fontFamily"; public static final String WIN_LOOK_AND_FEEL = "lookAndFeel"; public static final String LATEX_EDITOR_PATH = "latexEditorPath"; public static final String TEXSTUDIO_PATH = "TeXstudioPath"; public static final String WIN_EDT_PATH = "winEdtPath"; public static final String TEXMAKER_PATH = "texmakerPath"; public static final String LANGUAGE = "language"; public static final String NAMES_LAST_ONLY = "namesLastOnly"; public static final String ABBR_AUTHOR_NAMES = "abbrAuthorNames"; public static final String NAMES_NATBIB = "namesNatbib"; public static final String NAMES_FIRST_LAST = "namesFf"; public static final String NAMES_AS_IS = "namesAsIs"; public static final String TABLE_COLOR_CODES_ON = "tableColorCodesOn"; public static final String ENTRY_EDITOR_HEIGHT = "entryEditorHeight"; public static final String PREVIEW_PANEL_HEIGHT = "previewPanelHeight"; public static final String AUTO_RESIZE_MODE = "autoResizeMode"; public static final String WINDOW_MAXIMISED = "windowMaximised"; public static final String SIZE_Y = "sizeY"; public static final String SIZE_X = "sizeX"; public static final String POS_Y = "posY"; public static final String POS_X = "posX"; public static final String VIM_SERVER = "vimServer"; public static final String VIM = "vim"; public static final String LYXPIPE = "lyxpipe"; public static final String USE_DEFAULT_LOOK_AND_FEEL = "useDefaultLookAndFeel"; public static final String PROXY_PORT = "proxyPort"; public static final String PROXY_HOSTNAME = "proxyHostname"; public static final String USE_PROXY = "useProxy"; public static final String TABLE_PRIMARY_SORT_FIELD = "priSort"; public static final String TABLE_PRIMARY_SORT_DESCENDING = "priDescending"; public static final String TABLE_SECONDARY_SORT_FIELD = "secSort"; public static final String TABLE_SECONDARY_SORT_DESCENDING = "secDescending"; public static final String TABLE_TERTIARY_SORT_FIELD = "terSort"; public static final String TABLE_TERTIARY_SORT_DESCENDING = "terDescending"; public static final String SAVE_IN_ORIGINAL_ORDER = "saveInOriginalOrder"; public static final String SAVE_IN_SPECIFIED_ORDER = "saveInSpecifiedOrder"; public static final String SAVE_PRIMARY_SORT_FIELD = "savePriSort"; public static final String SAVE_PRIMARY_SORT_DESCENDING = "savePriDescending"; public static final String SAVE_SECONDARY_SORT_FIELD = "saveSecSort"; public static final String SAVE_SECONDARY_SORT_DESCENDING = "saveSecDescending"; public static final String SAVE_TERTIARY_SORT_FIELD = "saveTerSort"; public static final String SAVE_TERTIARY_SORT_DESCENDING = "saveTerDescending"; public static final String EXPORT_IN_ORIGINAL_ORDER = "exportInOriginalOrder"; public static final String EXPORT_IN_SPECIFIED_ORDER = "exportInSpecifiedOrder"; public static final String EXPORT_PRIMARY_SORT_FIELD = "exportPriSort"; public static final String EXPORT_PRIMARY_SORT_DESCENDING = "exportPriDescending"; public static final String EXPORT_SECONDARY_SORT_FIELD = "exportSecSort"; public static final String EXPORT_SECONDARY_SORT_DESCENDING = "exportSecDescending"; public static final String EXPORT_TERTIARY_SORT_FIELD = "exportTerSort"; public static final String EXPORT_TERTIARY_SORT_DESCENDING = "exportTerDescending"; public static final String NEWLINE = "newline"; public static final String COLUMN_WIDTHS = "columnWidths"; public static final String COLUMN_NAMES = "columnNames"; public static final String SIDE_PANE_COMPONENT_PREFERRED_POSITIONS = "sidePaneComponentPreferredPositions"; public static final String SIDE_PANE_COMPONENT_NAMES = "sidePaneComponentNames"; public static final String XMP_PRIVACY_FILTERS = "xmpPrivacyFilters"; public static final String USE_XMP_PRIVACY_FILTER = "useXmpPrivacyFilter"; public static final String SEARCH_AUTO_COMPLETE = "searchAutoComplete"; public static final String INCREMENT_S = "incrementS"; public static final String SEARCH_ALL = "searchAll"; public static final String SEARCH_GEN = "searchGen"; public static final String SEARCH_OPT = "searchOpt"; public static final String SEARCH_REQ = "searchReq"; public static final String CASE_SENSITIVE_SEARCH = "caseSensitiveSearch"; public static final String DEFAULT_AUTO_SORT = "defaultAutoSort"; public static final String SHOW_SOURCE = "showSource"; public static final String DEFAULT_SHOW_SOURCE = "defaultShowSource"; public static final String STRINGS_SIZE_Y = "stringsSizeY"; public static final String STRINGS_SIZE_X = "stringsSizeX"; public static final String STRINGS_POS_Y = "stringsPosY"; public static final String STRINGS_POS_X = "stringsPosX"; public static final String LAST_EDITED = "lastEdited"; public static final String OPEN_LAST_EDITED = "openLastEdited"; public static final String BACKUP = "backup"; public static final String ENTRY_TYPE_FORM_WIDTH = "entryTypeFormWidth"; public static final String ENTRY_TYPE_FORM_HEIGHT_FACTOR = "entryTypeFormHeightFactor"; public static final String AUTO_OPEN_FORM = "autoOpenForm"; public static final String FILE_WORKING_DIRECTORY = "fileWorkingDirectory"; public static final String IMPORT_WORKING_DIRECTORY = "importWorkingDirectory"; public static final String EXPORT_WORKING_DIRECTORY = "exportWorkingDirectory"; public static final String WORKING_DIRECTORY = "workingDirectory"; public static final String NUMBER_COL_WIDTH = "numberColWidth"; public static final String SHORTEST_TO_COMPLETE = "shortestToComplete"; public static final String AUTOCOMPLETE_FIRSTNAME_MODE = "autoCompFirstNameMode"; public static final String AUTOCOMPLETE_FIRSTNAME_MODE_BOTH = "both"; // here are the possible values for _MODE: public static final String AUTO_COMP_LAST_FIRST = "autoCompLF"; public static final String AUTO_COMP_FIRST_LAST = "autoCompFF"; public static final String AUTO_COMPLETE_FIELDS = "autoCompleteFields"; public static final String AUTO_COMPLETE = "autoComplete"; public static final String HIGH_LIGHT_WORDS = "highLightWords"; public static final String REG_EXP_SEARCH = "regExpSearch"; public static final String SELECT_S = "selectS"; public static final String EDITOR_EMACS_KEYBINDINGS = "editorEMACSkeyBindings"; public static final String EDITOR_EMACS_KEYBINDINGS_REBIND_CA = "editorEMACSkeyBindingsRebindCA"; public static final String EDITOR_EMACS_KEYBINDINGS_REBIND_CF = "editorEMACSkeyBindingsRebindCF"; public static final String GROUP_SHOW_NUMBER_OF_ELEMENTS = "groupShowNumberOfElements"; public static final String GROUP_AUTO_HIDE = "groupAutoHide"; public static final String GROUP_AUTO_SHOW = "groupAutoShow"; public static final String GROUP_EXPAND_TREE = "groupExpandTree"; public static final String GROUP_SHOW_DYNAMIC = "groupShowDynamic"; public static final String GROUP_SHOW_ICONS = "groupShowIcons"; public static final String GROUPS_DEFAULT_FIELD = "groupsDefaultField"; public static final String GROUP_SELECT_MATCHES = "groupSelectMatches"; public static final String GROUP_SHOW_OVERLAPPING = "groupShowOverlapping"; public static final String GROUP_INVERT_SELECTIONS = "groupInvertSelections"; public static final String GROUP_INTERSECT_SELECTIONS = "groupIntersectSelections"; public static final String GROUP_FLOAT_SELECTIONS = "groupFloatSelections"; public static final String GROUP_SELECTOR_VISIBLE = "groupSelectorVisible"; public static final String EDIT_GROUP_MEMBERSHIP_MODE = "groupEditGroupMembershipMode"; public static final String GROUP_KEYWORD_SEPARATOR = "groupKeywordSeparator"; public static final String AUTO_ASSIGN_GROUP = "autoAssignGroup"; public static final String LIST_OF_FILE_COLUMNS = "listOfFileColumns"; public static final String EXTRA_FILE_COLUMNS = "extraFileColumns"; public static final String ARXIV_COLUMN = "arxivColumn"; public static final String FILE_COLUMN = "fileColumn"; public static final String PREFER_URL_DOI = "preferUrlDoi"; public static final String URL_COLUMN = "urlColumn"; public static final String PDF_COLUMN = "pdfColumn"; public static final String DISABLE_ON_MULTIPLE_SELECTION = "disableOnMultipleSelection"; public static final String CTRL_CLICK = "ctrlClick"; public static final String ANTIALIAS = "antialias"; public static final String INCOMPLETE_ENTRY_BACKGROUND = "incompleteEntryBackground"; public static final String FIELD_EDITOR_TEXT_COLOR = "fieldEditorTextColor"; public static final String ACTIVE_FIELD_EDITOR_BACKGROUND_COLOR = "activeFieldEditorBackgroundColor"; public static final String INVALID_FIELD_BACKGROUND_COLOR = "invalidFieldBackgroundColor"; public static final String VALID_FIELD_BACKGROUND_COLOR = "validFieldBackgroundColor"; public static final String MARKED_ENTRY_BACKGROUND5 = "markedEntryBackground5"; public static final String MARKED_ENTRY_BACKGROUND4 = "markedEntryBackground4"; public static final String MARKED_ENTRY_BACKGROUND3 = "markedEntryBackground3"; public static final String MARKED_ENTRY_BACKGROUND2 = "markedEntryBackground2"; public static final String MARKED_ENTRY_BACKGROUND1 = "markedEntryBackground1"; public static final String MARKED_ENTRY_BACKGROUND0 = "markedEntryBackground0"; public static final String VERY_GRAYED_OUT_TEXT = "veryGrayedOutText"; public static final String VERY_GRAYED_OUT_BACKGROUND = "veryGrayedOutBackground"; public static final String GRAYED_OUT_TEXT = "grayedOutText"; public static final String GRAYED_OUT_BACKGROUND = "grayedOutBackground"; public static final String GRID_COLOR = "gridColor"; public static final String TABLE_TEXT = "tableText"; public static final String TABLE_OPT_FIELD_BACKGROUND = "tableOptFieldBackground"; public static final String TABLE_REQ_FIELD_BACKGROUND = "tableReqFieldBackground"; public static final String TABLE_BACKGROUND = "tableBackground"; public static final String TABLE_SHOW_GRID = "tableShowGrid"; public static final String TABLE_ROW_PADDING = "tableRowPadding"; public static final String MENU_FONT_SIZE = "menuFontSize"; public static final String MENU_FONT_STYLE = "menuFontStyle"; public static final String MENU_FONT_FAMILY = "menuFontFamily"; public static final String OVERRIDE_DEFAULT_FONTS = "overrideDefaultFonts"; public static final String FONT_SIZE = "fontSize"; public static final String FONT_STYLE = "fontStyle"; public static final String HISTORY_SIZE = "historySize"; public static final String GENERAL_FIELDS = "generalFields"; public static final String RENAME_ON_MOVE_FILE_TO_FILE_DIR = "renameOnMoveFileToFileDir"; public static final String MEMORY_STICK_MODE = "memoryStickMode"; public static final String PRESERVE_FIELD_FORMATTING = "preserveFieldFormatting"; public static final String DEFAULT_OWNER = "defaultOwner"; public static final String GROUPS_VISIBLE_ROWS = "groupsVisibleRows"; public static final String DEFAULT_ENCODING = "defaultEncoding"; public static final String SEARCH_PANEL_VISIBLE = "searchPanelVisible"; public static final String TOOLBAR_VISIBLE = "toolbarVisible"; public static final String HIGHLIGHT_GROUPS_MATCHING_ALL = "highlightGroupsMatchingAll"; public static final String HIGHLIGHT_GROUPS_MATCHING_ANY = "highlightGroupsMatchingAny"; public static final String SHOW_ONE_LETTER_HEADING_FOR_ICON_COLUMNS = "showOneLetterHeadingForIconColumns"; public static final String UPDATE_TIMESTAMP = "updateTimestamp"; public static final String TIME_STAMP_FIELD = "timeStampField"; public static final String TIME_STAMP_FORMAT = "timeStampFormat"; public static final String OVERWRITE_TIME_STAMP = "overwriteTimeStamp"; public static final String USE_TIME_STAMP = "useTimeStamp"; public static final String WARN_ABOUT_DUPLICATES_IN_INSPECTION = "warnAboutDuplicatesInInspection"; public static final String UNMARK_ALL_ENTRIES_BEFORE_IMPORTING = "unmarkAllEntriesBeforeImporting"; public static final String MARK_IMPORTED_ENTRIES = "markImportedEntries"; public static final String GENERATE_KEYS_AFTER_INSPECTION = "generateKeysAfterInspection"; public static final String USE_IMPORT_INSPECTION_DIALOG_FOR_SINGLE = "useImportInspectionDialogForSingle"; public static final String USE_IMPORT_INSPECTION_DIALOG = "useImportInspectionDialog"; public static final String NON_WRAPPABLE_FIELDS = "nonWrappableFields"; public static final String PUT_BRACES_AROUND_CAPITALS = "putBracesAroundCapitals"; public static final String RESOLVE_STRINGS_ALL_FIELDS = "resolveStringsAllFields"; public static final String DO_NOT_RESOLVE_STRINGS_FOR = "doNotResolveStringsFor"; public static final String AUTO_DOUBLE_BRACES = "autoDoubleBraces"; public static final String PREVIEW_PRINT_BUTTON = "previewPrintButton"; public static final String PREVIEW_1 = "preview1"; public static final String PREVIEW_0 = "preview0"; public static final String ACTIVE_PREVIEW = "activePreview"; public static final String PREVIEW_ENABLED = "previewEnabled"; // Currently, it is not possible to specify defaults for specific entry types // When this should be made possible, the code to inspect is net.sf.jabref.gui.preftabs.LabelPatternPrefTab.storeSettings() -> LabelPattern keypatterns = getLabelPattern(); etc public static final String DEFAULT_LABEL_PATTERN = "defaultLabelPattern"; public static final String SEARCH_ALL_BASES = "searchAllBases"; public static final String SHOW_SEARCH_IN_DIALOG = "showSearchInDialog"; public static final String FLOAT_SEARCH = "floatSearch"; public static final String GRAY_OUT_NON_HITS = "grayOutNonHits"; public static final String CONFIRM_DELETE = "confirmDelete"; public static final String WARN_BEFORE_OVERWRITING_KEY = "warnBeforeOverwritingKey"; public static final String AVOID_OVERWRITING_KEY = "avoidOverwritingKey"; public static final String DISPLAY_KEY_WARNING_DIALOG_AT_STARTUP = "displayKeyWarningDialogAtStartup"; public static final String DIALOG_WARNING_FOR_EMPTY_KEY = "dialogWarningForEmptyKey"; public static final String DIALOG_WARNING_FOR_DUPLICATE_KEY = "dialogWarningForDuplicateKey"; public static final String ALLOW_TABLE_EDITING = "allowTableEditing"; public static final String OVERWRITE_OWNER = "overwriteOwner"; public static final String USE_OWNER = "useOwner"; public static final String WRITEFIELD_ADDSPACES = "writeFieldAddSpaces"; public static final String WRITEFIELD_CAMELCASENAME = "writeFieldCamelCase"; public static final String WRITEFIELD_SORTSTYLE = "writefieldSortStyle"; public static final String WRITEFIELD_USERDEFINEDORDER = "writefieldUserdefinedOrder"; public static final String WRITEFIELD_WRAPFIELD = "wrapFieldLine"; public static final String AUTOLINK_EXACT_KEY_ONLY = "autolinkExactKeyOnly"; public static final String SHOW_FILE_LINKS_UPGRADE_WARNING = "showFileLinksUpgradeWarning"; public static final String SEARCH_DIALOG_HEIGHT = "searchDialogHeight"; public static final String SEARCH_DIALOG_WIDTH = "searchDialogWidth"; public static final String IMPORT_INSPECTION_DIALOG_HEIGHT = "importInspectionDialogHeight"; public static final String IMPORT_INSPECTION_DIALOG_WIDTH = "importInspectionDialogWidth"; public static final String SIDE_PANE_WIDTH = "sidePaneWidth"; public static final String LAST_USED_EXPORT = "lastUsedExport"; public static final String FILECHOOSER_DISABLE_RENAME = "filechooserDisableRename"; public static final String USE_NATIVE_FILE_DIALOG_ON_MAC = "useNativeFileDialogOnMac"; public static final String FLOAT_MARKED_ENTRIES = "floatMarkedEntries"; public static final String CITE_COMMAND = "citeCommand"; public static final String EXTERNAL_JOURNAL_LISTS = "externalJournalLists"; public static final String PERSONAL_JOURNAL_LIST = "personalJournalList"; public static final String GENERATE_KEYS_BEFORE_SAVING = "generateKeysBeforeSaving"; public static final String EMAIL_SUBJECT = "emailSubject"; public static final String OPEN_FOLDERS_OF_ATTACHED_FILES = "openFoldersOfAttachedFiles"; public static final String KEY_GEN_ALWAYS_ADD_LETTER = "keyGenAlwaysAddLetter"; public static final String KEY_GEN_FIRST_LETTER_A = "keyGenFirstLetterA"; public static final String INCLUDE_EMPTY_FIELDS = "includeEmptyFields"; public static final String VALUE_DELIMITERS2 = "valueDelimiters"; public static final String BIBLATEX_MODE = "biblatexMode"; public static final String ENFORCE_LEGAL_BIBTEX_KEY = "enforceLegalBibtexKey"; public static final String PROMPT_BEFORE_USING_AUTOSAVE = "promptBeforeUsingAutosave"; public static final String AUTO_SAVE_INTERVAL = "autoSaveInterval"; public static final String AUTO_SAVE = "autoSave"; public static final String USE_LOCK_FILES = "useLockFiles"; public static final String RUN_AUTOMATIC_FILE_SEARCH = "runAutomaticFileSearch"; public static final String NUMERIC_FIELDS = "numericFields"; public static final String DEFAULT_REG_EXP_SEARCH_EXPRESSION_KEY = "defaultRegExpSearchExpression"; public static final String REG_EXP_SEARCH_EXPRESSION_KEY = "regExpSearchExpression"; public static final String AUTOLINK_USE_REG_EXP_SEARCH_KEY = "useRegExpSearch"; public static final String DB_CONNECT_USERNAME = "dbConnectUsername"; public static final String DB_CONNECT_DATABASE = "dbConnectDatabase"; public static final String DB_CONNECT_HOSTNAME = "dbConnectHostname"; public static final String DB_CONNECT_SERVER_TYPE = "dbConnectServerType"; public static final String BIB_LOC_AS_PRIMARY_DIR = "bibLocAsPrimaryDir"; public static final String BIB_LOCATION_AS_FILE_DIR = "bibLocationAsFileDir"; public static final String SELECTED_FETCHER_INDEX = "selectedFetcherIndex"; public static final String WEB_SEARCH_VISIBLE = "webSearchVisible"; public static final String ALLOW_FILE_AUTO_OPEN_BROWSE = "allowFileAutoOpenBrowse"; public static final String CUSTOM_TAB_NAME = "customTabName_"; public static final String CUSTOM_TAB_FIELDS = "customTabFields_"; public static final String USER_FILE_DIR_INDIVIDUAL = "userFileDirIndividual"; public static final String USER_FILE_DIR_IND_LEGACY = "userFileDirInd_Legacy"; public static final String USER_FILE_DIR = "userFileDir"; public static final String USE_UNIT_FORMATTER_ON_SEARCH = "useUnitFormatterOnSearch"; public static final String USE_CASE_KEEPER_ON_SEARCH = "useCaseKeeperOnSearch"; public static final String USE_CONVERT_TO_EQUATION = "useConvertToEquation"; public static final String USE_IEEE_ABRV = "useIEEEAbrv"; //non-default preferences private static final String CUSTOM_TYPE_NAME = "customTypeName_"; private static final String CUSTOM_TYPE_REQ = "customTypeReq_"; private static final String CUSTOM_TYPE_OPT = "customTypeOpt_"; private static final String CUSTOM_TYPE_PRIOPT = "customTypePriOpt_"; public static final String PDF_PREVIEW = "pdfPreview"; public static final String AUTOCOMPLETE_FIRSTNAME_MODE_ONLY_FULL = "fullOnly"; public static final String AUTOCOMPLETE_FIRSTNAME_MODE_ONLY_ABBR = "abbrOnly"; // This String is used in the encoded list in prefs of external file type // modifications, in order to indicate a removed default file type: private static final String FILE_TYPE_REMOVED_FLAG = "REMOVED"; private static final char[][] VALUE_DELIMITERS = new char[][] { {'"', '"'}, {'{', '}'}}; public String WRAPPED_USERNAME; public final String MARKING_WITH_NUMBER_PATTERN; private int SHORTCUT_MASK = -1; private final Preferences prefs; private KeyBinds keyBinds = new KeyBinds(); private KeyBinds defaultKeyBinds = new KeyBinds(); private final HashSet<String> putBracesAroundCapitalsFields = new HashSet<String>(4); private final HashSet<String> nonWrappableFields = new HashSet<String>(5); private static GlobalLabelPattern keyPattern; // Object containing custom export formats: public final CustomExportList customExports; /** * Set with all custom {@link ImportFormat}s */ public final CustomImportList customImports; // Object containing info about customized entry editor tabs. private EntryEditorTabList tabList; // Map containing all registered external file types: private final TreeSet<ExternalFileType> externalFileTypes = new TreeSet<ExternalFileType>(); private final ExternalFileType HTML_FALLBACK_TYPE = new ExternalFileType("URL", "html", "text/html", "", "www", IconTheme.getImage("www")); // The following field is used as a global variable during the export of a database. // By setting this field to the path of the database's default file directory, formatters // that should resolve external file paths can access this field. This is an ugly hack // to solve the problem of formatters not having access to any context except for the // string to be formatted and possible formatter arguments. public String[] fileDirForDatabase; // Similarly to the previous variable, this is a global that can be used during // the export of a database if the database filename should be output. If a database // is tied to a file on disk, this variable is set to that file before export starts: public File databaseFile; // The following field is used as a global variable during the export of a database. // It is used to hold custom name formatters defined by a custom export filter. // It is set before the export starts: public HashMap<String, String> customExportNameFormatters; // The only instance of this class: private static JabRefPreferences singleton; public static JabRefPreferences getInstance() { if (JabRefPreferences.singleton == null) { JabRefPreferences.singleton = new JabRefPreferences(); } return JabRefPreferences.singleton; } // The constructor is made private to enforce this as a singleton class: private JabRefPreferences() { try { if (new File("jabref.xml").exists()) { importPreferences("jabref.xml"); } } catch (IOException e) { LOGGER.info("Could not import preferences from jabref.xml:" + e.getLocalizedMessage(), e); } // load user preferences prefs = Preferences.userNodeForPackage(JabRef.class); defaults.put(TEXMAKER_PATH, OS.guessProgramPath("texmaker", "Texmaker")); defaults.put(WIN_EDT_PATH, OS.guessProgramPath("WinEdt", "WinEdt Team\\WinEdt")); defaults.put(LATEX_EDITOR_PATH, OS.guessProgramPath("LEd", "LEd")); defaults.put(TEXSTUDIO_PATH, OS.guessProgramPath("texstudio", "TeXstudio")); if (OS.OS_X) { //defaults.put("pdfviewer", "/Applications/Preview.app"); //defaults.put("psviewer", "/Applications/Preview.app"); //defaults.put("htmlviewer", "/Applications/Safari.app"); defaults.put(EMACS_PATH, "emacsclient"); defaults.put(EMACS_23, true); defaults.put(EMACS_ADDITIONAL_PARAMETERS, "-n -e"); defaults.put(FONT_FAMILY, "SansSerif"); defaults.put(WIN_LOOK_AND_FEEL, UIManager.getSystemLookAndFeelClassName()); } else if (OS.WINDOWS) { //defaults.put("pdfviewer", "cmd.exe /c start /b"); //defaults.put("psviewer", "cmd.exe /c start /b"); //defaults.put("htmlviewer", "cmd.exe /c start /b"); defaults.put(WIN_LOOK_AND_FEEL, "com.jgoodies.looks.windows.WindowsLookAndFeel"); defaults.put(EMACS_PATH, "emacsclient.exe"); defaults.put(EMACS_23, true); defaults.put(EMACS_ADDITIONAL_PARAMETERS, "-n -e"); defaults.put(FONT_FAMILY, "Arial"); } else { //defaults.put("pdfviewer", "evince"); //defaults.put("psviewer", "gv"); //defaults.put("htmlviewer", "firefox"); defaults.put(WIN_LOOK_AND_FEEL, "com.jgoodies.plaf.plastic.Plastic3DLookAndFeel"); defaults.put(FONT_FAMILY, "SansSerif"); // linux defaults.put(EMACS_PATH, "gnuclient"); defaults.put(EMACS_23, false); defaults.put(EMACS_ADDITIONAL_PARAMETERS, "-batch -eval"); } defaults.put(USE_PROXY, Boolean.FALSE); defaults.put(PROXY_HOSTNAME, "my proxy host"); defaults.put(PROXY_PORT, "my proxy port"); defaults.put(PDF_PREVIEW, Boolean.FALSE); defaults.put(USE_DEFAULT_LOOK_AND_FEEL, Boolean.TRUE); defaults.put(LYXPIPE, System.getProperty("user.home") + File.separator + ".lyx/lyxpipe"); defaults.put(VIM, "vim"); defaults.put(VIM_SERVER, "vim"); defaults.put(POS_X, 0); defaults.put(POS_Y, 0); defaults.put(SIZE_X, 840); defaults.put(SIZE_Y, 680); defaults.put(WINDOW_MAXIMISED, Boolean.FALSE); defaults.put(AUTO_RESIZE_MODE, JTable.AUTO_RESIZE_ALL_COLUMNS); defaults.put(PREVIEW_PANEL_HEIGHT, 200); defaults.put(ENTRY_EDITOR_HEIGHT, 400); defaults.put(TABLE_COLOR_CODES_ON, Boolean.FALSE); defaults.put(NAMES_AS_IS, Boolean.FALSE); // "Show names unchanged" defaults.put(NAMES_FIRST_LAST, Boolean.FALSE); // "Show 'Firstname Lastname'" defaults.put(NAMES_NATBIB, Boolean.TRUE); // "Natbib style" defaults.put(ABBR_AUTHOR_NAMES, Boolean.TRUE); // "Abbreviate names" defaults.put(NAMES_LAST_ONLY, Boolean.TRUE); // "Show last names only" // system locale as default defaults.put(LANGUAGE, Locale.getDefault().getLanguage()); // Sorting preferences defaults.put(TABLE_PRIMARY_SORT_FIELD, "author"); defaults.put(TABLE_PRIMARY_SORT_DESCENDING, Boolean.FALSE); defaults.put(TABLE_SECONDARY_SORT_FIELD, "year"); defaults.put(TABLE_SECONDARY_SORT_DESCENDING, Boolean.TRUE); defaults.put(TABLE_TERTIARY_SORT_FIELD, "title"); defaults.put(TABLE_TERTIARY_SORT_DESCENDING, Boolean.FALSE); // if both are false, then the entries are saved in table order defaults.put(SAVE_IN_ORIGINAL_ORDER, Boolean.FALSE); defaults.put(SAVE_IN_SPECIFIED_ORDER, Boolean.TRUE); // save order: if SAVE_IN_SPECIFIED_ORDER, then use following criteria defaults.put(SAVE_PRIMARY_SORT_FIELD, "bibtexkey"); defaults.put(SAVE_PRIMARY_SORT_DESCENDING, Boolean.FALSE); defaults.put(SAVE_SECONDARY_SORT_FIELD, "author"); defaults.put(SAVE_SECONDARY_SORT_DESCENDING, Boolean.FALSE); defaults.put(SAVE_TERTIARY_SORT_FIELD, "title"); defaults.put(SAVE_TERTIARY_SORT_DESCENDING, Boolean.FALSE); // export order defaults.put(EXPORT_IN_ORIGINAL_ORDER, Boolean.FALSE); defaults.put(EXPORT_IN_SPECIFIED_ORDER, Boolean.FALSE); // export order: if EXPORT_IN_SPECIFIED_ORDER, then use following criteria defaults.put(EXPORT_PRIMARY_SORT_FIELD, "bibtexkey"); defaults.put(EXPORT_PRIMARY_SORT_DESCENDING, Boolean.FALSE); defaults.put(EXPORT_SECONDARY_SORT_FIELD, "author"); defaults.put(EXPORT_SECONDARY_SORT_DESCENDING, Boolean.FALSE); defaults.put(EXPORT_TERTIARY_SORT_FIELD, "title"); defaults.put(EXPORT_TERTIARY_SORT_DESCENDING, Boolean.TRUE); defaults.put(NEWLINE, System.lineSeparator()); defaults.put(SIDE_PANE_COMPONENT_NAMES, ""); defaults.put(SIDE_PANE_COMPONENT_PREFERRED_POSITIONS, ""); defaults.put(COLUMN_NAMES, "entrytype;author;title;year;journal;bibtexkey"); defaults.put(COLUMN_WIDTHS, "75;300;470;60;130;100"); defaults.put(PersistenceTableColumnListener.ACTIVATE_PREF_KEY, PersistenceTableColumnListener.DEFAULT_ENABLED); defaults.put(XMP_PRIVACY_FILTERS, "pdf;timestamp;keywords;owner;note;review"); defaults.put(USE_XMP_PRIVACY_FILTER, Boolean.FALSE); defaults.put(NUMBER_COL_WIDTH, GUIGlobals.NUMBER_COL_LENGTH); defaults.put(WORKING_DIRECTORY, System.getProperty("user.home")); defaults.put(EXPORT_WORKING_DIRECTORY, System.getProperty("user.home")); defaults.put(IMPORT_WORKING_DIRECTORY, System.getProperty("user.home")); defaults.put(FILE_WORKING_DIRECTORY, System.getProperty("user.home")); defaults.put(AUTO_OPEN_FORM, Boolean.TRUE); defaults.put(ENTRY_TYPE_FORM_HEIGHT_FACTOR, 1); defaults.put(ENTRY_TYPE_FORM_WIDTH, 1); defaults.put(BACKUP, Boolean.TRUE); defaults.put(OPEN_LAST_EDITED, Boolean.TRUE); defaults.put(LAST_EDITED, null); defaults.put(STRINGS_POS_X, 0); defaults.put(STRINGS_POS_Y, 0); defaults.put(STRINGS_SIZE_X, 600); defaults.put(STRINGS_SIZE_Y, 400); defaults.put(DEFAULT_SHOW_SOURCE, Boolean.FALSE); defaults.put(SHOW_SOURCE, Boolean.TRUE); defaults.put(DEFAULT_AUTO_SORT, Boolean.FALSE); defaults.put(CASE_SENSITIVE_SEARCH, Boolean.FALSE); defaults.put(SEARCH_REQ, Boolean.TRUE); defaults.put(SEARCH_OPT, Boolean.TRUE); defaults.put(SEARCH_GEN, Boolean.TRUE); defaults.put(SEARCH_ALL, Boolean.FALSE); defaults.put(INCREMENT_S, Boolean.FALSE); defaults.put(SEARCH_AUTO_COMPLETE, Boolean.TRUE); defaults.put(SELECT_S, Boolean.FALSE); defaults.put(REG_EXP_SEARCH, Boolean.TRUE); defaults.put(HIGH_LIGHT_WORDS, Boolean.TRUE); defaults.put(EDITOR_EMACS_KEYBINDINGS, Boolean.FALSE); defaults.put(EDITOR_EMACS_KEYBINDINGS_REBIND_CA, Boolean.TRUE); defaults.put(EDITOR_EMACS_KEYBINDINGS_REBIND_CF, Boolean.TRUE); defaults.put(AUTO_COMPLETE, Boolean.TRUE); defaults.put(AUTO_COMPLETE_FIELDS, "author;editor;title;journal;publisher;keywords;crossref"); defaults.put(AUTO_COMP_FIRST_LAST, Boolean.FALSE); // "Autocomplete names in 'Firstname Lastname' format only" defaults.put(AUTO_COMP_LAST_FIRST, Boolean.FALSE); // "Autocomplete names in 'Lastname, Firstname' format only" defaults.put(SHORTEST_TO_COMPLETE, 2); defaults.put(AUTOCOMPLETE_FIRSTNAME_MODE, JabRefPreferences.AUTOCOMPLETE_FIRSTNAME_MODE_BOTH); defaults.put(GROUP_SELECTOR_VISIBLE, Boolean.TRUE); defaults.put(GROUP_FLOAT_SELECTIONS, Boolean.TRUE); defaults.put(GROUP_INTERSECT_SELECTIONS, Boolean.TRUE); defaults.put(GROUP_INVERT_SELECTIONS, Boolean.FALSE); defaults.put(GROUP_SHOW_OVERLAPPING, Boolean.FALSE); defaults.put(GROUP_SELECT_MATCHES, Boolean.FALSE); defaults.put(GROUPS_DEFAULT_FIELD, "keywords"); defaults.put(GROUP_SHOW_ICONS, Boolean.TRUE); defaults.put(GROUP_SHOW_DYNAMIC, Boolean.TRUE); defaults.put(GROUP_EXPAND_TREE, Boolean.TRUE); defaults.put(GROUP_AUTO_SHOW, Boolean.TRUE); defaults.put(GROUP_AUTO_HIDE, Boolean.TRUE); defaults.put(GROUP_SHOW_NUMBER_OF_ELEMENTS, Boolean.FALSE); defaults.put(AUTO_ASSIGN_GROUP, Boolean.TRUE); defaults.put(GROUP_KEYWORD_SEPARATOR, ", "); defaults.put(EDIT_GROUP_MEMBERSHIP_MODE, Boolean.FALSE); defaults.put(HIGHLIGHT_GROUPS_MATCHING_ANY, Boolean.FALSE); defaults.put(HIGHLIGHT_GROUPS_MATCHING_ALL, Boolean.FALSE); defaults.put(TOOLBAR_VISIBLE, Boolean.TRUE); defaults.put(SEARCH_PANEL_VISIBLE, Boolean.FALSE); defaults.put(DEFAULT_ENCODING, "UTF-8"); defaults.put(GROUPS_VISIBLE_ROWS, 8); defaults.put(DEFAULT_OWNER, System.getProperty("user.name")); defaults.put(PRESERVE_FIELD_FORMATTING, Boolean.FALSE); defaults.put(MEMORY_STICK_MODE, Boolean.FALSE); defaults.put(RENAME_ON_MOVE_FILE_TO_FILE_DIR, Boolean.TRUE); // The general fields stuff is made obsolete by the CUSTOM_TAB_... entries. defaults.put(GENERAL_FIELDS, "crossref;keywords;file;doi;url;urldate;" + "pdf;comment;owner"); defaults.put(HISTORY_SIZE, 8); defaults.put(FONT_STYLE, java.awt.Font.PLAIN); defaults.put(FONT_SIZE, 12); defaults.put(OVERRIDE_DEFAULT_FONTS, Boolean.FALSE); defaults.put(MENU_FONT_FAMILY, "Times"); defaults.put(MENU_FONT_STYLE, java.awt.Font.PLAIN); defaults.put(MENU_FONT_SIZE, 11); defaults.put(TABLE_ROW_PADDING, GUIGlobals.TABLE_ROW_PADDING); defaults.put(TABLE_SHOW_GRID, Boolean.FALSE); // Main table color settings: defaults.put(TABLE_BACKGROUND, "255:255:255"); defaults.put(TABLE_REQ_FIELD_BACKGROUND, "230:235:255"); defaults.put(TABLE_OPT_FIELD_BACKGROUND, "230:255:230"); defaults.put(TABLE_TEXT, "0:0:0"); defaults.put(GRID_COLOR, "210:210:210"); defaults.put(GRAYED_OUT_BACKGROUND, "210:210:210"); defaults.put(GRAYED_OUT_TEXT, "40:40:40"); defaults.put(VERY_GRAYED_OUT_BACKGROUND, "180:180:180"); defaults.put(VERY_GRAYED_OUT_TEXT, "40:40:40"); defaults.put(MARKED_ENTRY_BACKGROUND0, "255:255:180"); defaults.put(MARKED_ENTRY_BACKGROUND1, "255:220:180"); defaults.put(MARKED_ENTRY_BACKGROUND2, "255:180:160"); defaults.put(MARKED_ENTRY_BACKGROUND3, "255:120:120"); defaults.put(MARKED_ENTRY_BACKGROUND4, "255:75:75"); defaults.put(MARKED_ENTRY_BACKGROUND5, "220:255:220"); defaults.put(VALID_FIELD_BACKGROUND_COLOR, "255:255:255"); defaults.put(INVALID_FIELD_BACKGROUND_COLOR, "255:0:0"); defaults.put(ACTIVE_FIELD_EDITOR_BACKGROUND_COLOR, "220:220:255"); defaults.put(FIELD_EDITOR_TEXT_COLOR, "0:0:0"); defaults.put(INCOMPLETE_ENTRY_BACKGROUND, "250:175:175"); defaults.put(ANTIALIAS, Boolean.FALSE); defaults.put(CTRL_CLICK, Boolean.FALSE); defaults.put(DISABLE_ON_MULTIPLE_SELECTION, Boolean.FALSE); defaults.put(PDF_COLUMN, Boolean.FALSE); defaults.put(URL_COLUMN, Boolean.TRUE); defaults.put(PREFER_URL_DOI, Boolean.FALSE); defaults.put(FILE_COLUMN, Boolean.TRUE); defaults.put(ARXIV_COLUMN, Boolean.FALSE); defaults.put(EXTRA_FILE_COLUMNS, Boolean.FALSE); defaults.put(LIST_OF_FILE_COLUMNS, ""); defaults.put(SpecialFieldsUtils.PREF_SPECIALFIELDSENABLED, SpecialFieldsUtils.PREF_SPECIALFIELDSENABLED_DEFAULT); defaults.put(SpecialFieldsUtils.PREF_SHOWCOLUMN_PRIORITY, SpecialFieldsUtils.PREF_SHOWCOLUMN_PRIORITY_DEFAULT); defaults.put(SpecialFieldsUtils.PREF_SHOWCOLUMN_QUALITY, SpecialFieldsUtils.PREF_SHOWCOLUMN_QUALITY_DEFAULT); defaults.put(SpecialFieldsUtils.PREF_SHOWCOLUMN_RANKING, SpecialFieldsUtils.PREF_SHOWCOLUMN_RANKING_DEFAULT); defaults.put(SpecialFieldsUtils.PREF_SHOWCOLUMN_RELEVANCE, SpecialFieldsUtils.PREF_SHOWCOLUMN_RELEVANCE_DEFAULT); defaults.put(SpecialFieldsUtils.PREF_SHOWCOLUMN_PRINTED, SpecialFieldsUtils.PREF_SHOWCOLUMN_PRINTED_DEFAULT); defaults.put(SpecialFieldsUtils.PREF_SHOWCOLUMN_READ, SpecialFieldsUtils.PREF_SHOWCOLUMN_READ_DEFAULT); defaults.put(SpecialFieldsUtils.PREF_AUTOSYNCSPECIALFIELDSTOKEYWORDS, SpecialFieldsUtils.PREF_AUTOSYNCSPECIALFIELDSTOKEYWORDS_DEFAULT); defaults.put(SpecialFieldsUtils.PREF_SERIALIZESPECIALFIELDS, SpecialFieldsUtils.PREF_SERIALIZESPECIALFIELDS_DEFAULT); defaults.put(SHOW_ONE_LETTER_HEADING_FOR_ICON_COLUMNS, Boolean.FALSE); defaults.put(USE_OWNER, Boolean.FALSE); defaults.put(OVERWRITE_OWNER, Boolean.FALSE); defaults.put(ALLOW_TABLE_EDITING, Boolean.FALSE); defaults.put(DIALOG_WARNING_FOR_DUPLICATE_KEY, Boolean.TRUE); defaults.put(DIALOG_WARNING_FOR_EMPTY_KEY, Boolean.TRUE); defaults.put(DISPLAY_KEY_WARNING_DIALOG_AT_STARTUP, Boolean.TRUE); defaults.put(AVOID_OVERWRITING_KEY, Boolean.FALSE); defaults.put(WARN_BEFORE_OVERWRITING_KEY, Boolean.TRUE); defaults.put(CONFIRM_DELETE, Boolean.TRUE); defaults.put(GRAY_OUT_NON_HITS, Boolean.TRUE); defaults.put(FLOAT_SEARCH, Boolean.TRUE); defaults.put(SHOW_SEARCH_IN_DIALOG, Boolean.FALSE); defaults.put(SEARCH_ALL_BASES, Boolean.FALSE); defaults.put(DEFAULT_LABEL_PATTERN, "[authors3][year]"); defaults.put(PREVIEW_ENABLED, Boolean.TRUE); defaults.put(ACTIVE_PREVIEW, 0); defaults.put(PREVIEW_0, "<font face=\"arial\">" + "<b><i>\\bibtextype</i><a name=\"\\bibtexkey\">\\begin{bibtexkey} (\\bibtexkey)</a>" + "\\end{bibtexkey}</b><br>__NEWLINE__" + "\\begin{author} \\format[Authors(LastFirst,Initials,Semicolon,Amp),HTMLChars]{\\author}<BR>\\end{author}__NEWLINE__" + "\\begin{editor} \\format[Authors(LastFirst,Initials,Semicolon,Amp),HTMLChars]{\\editor} " + "<i>(\\format[IfPlural(Eds.,Ed.)]{\\editor})</i><BR>\\end{editor}__NEWLINE__" + "\\begin{title} \\format[HTMLChars]{\\title} \\end{title}<BR>__NEWLINE__" + "\\begin{chapter} \\format[HTMLChars]{\\chapter}<BR>\\end{chapter}__NEWLINE__" + "\\begin{journal} <em>\\format[HTMLChars]{\\journal}, </em>\\end{journal}__NEWLINE__" // Include the booktitle field for @inproceedings, @proceedings, etc. + "\\begin{booktitle} <em>\\format[HTMLChars]{\\booktitle}, </em>\\end{booktitle}__NEWLINE__" + "\\begin{school} <em>\\format[HTMLChars]{\\school}, </em>\\end{school}__NEWLINE__" + "\\begin{institution} <em>\\format[HTMLChars]{\\institution}, </em>\\end{institution}__NEWLINE__" + "\\begin{publisher} <em>\\format[HTMLChars]{\\publisher}, </em>\\end{publisher}__NEWLINE__" + "\\begin{year}<b>\\year</b>\\end{year}\\begin{volume}<i>, \\volume</i>\\end{volume}" + "\\begin{pages}, \\format[FormatPagesForHTML]{\\pages} \\end{pages}__NEWLINE__" + "\\begin{abstract}<BR><BR><b>Abstract: </b> \\format[HTMLChars]{\\abstract} \\end{abstract}__NEWLINE__" + "\\begin{review}<BR><BR><b>Review: </b> \\format[HTMLChars]{\\review} \\end{review}" + "</dd>__NEWLINE__<p></p></font>"); defaults.put(PREVIEW_1, "<font face=\"arial\">" + "<b><i>\\bibtextype</i><a name=\"\\bibtexkey\">\\begin{bibtexkey} (\\bibtexkey)</a>" + "\\end{bibtexkey}</b><br>__NEWLINE__" + "\\begin{author} \\format[Authors(LastFirst,Initials,Semicolon,Amp),HTMLChars]{\\author}<BR>\\end{author}__NEWLINE__" + "\\begin{editor} \\format[Authors(LastFirst,Initials,Semicolon,Amp),HTMLChars]{\\editor} " + "<i>(\\format[IfPlural(Eds.,Ed.)]{\\editor})</i><BR>\\end{editor}__NEWLINE__" + "\\begin{title} \\format[HTMLChars]{\\title} \\end{title}<BR>__NEWLINE__" + "\\begin{chapter} \\format[HTMLChars]{\\chapter}<BR>\\end{chapter}__NEWLINE__" + "\\begin{journal} <em>\\format[HTMLChars]{\\journal}, </em>\\end{journal}__NEWLINE__" // Include the booktitle field for @inproceedings, @proceedings, etc. + "\\begin{booktitle} <em>\\format[HTMLChars]{\\booktitle}, </em>\\end{booktitle}__NEWLINE__" + "\\begin{school} <em>\\format[HTMLChars]{\\school}, </em>\\end{school}__NEWLINE__" + "\\begin{institution} <em>\\format[HTMLChars]{\\institution}, </em>\\end{institution}__NEWLINE__" + "\\begin{publisher} <em>\\format[HTMLChars]{\\publisher}, </em>\\end{publisher}__NEWLINE__" + "\\begin{year}<b>\\year</b>\\end{year}\\begin{volume}<i>, \\volume</i>\\end{volume}" + "\\begin{pages}, \\format[FormatPagesForHTML]{\\pages} \\end{pages}" + "</dd>__NEWLINE__<p></p></font>"); // TODO: Currently not possible to edit this setting: defaults.put(PREVIEW_PRINT_BUTTON, Boolean.FALSE); defaults.put(AUTO_DOUBLE_BRACES, Boolean.FALSE); defaults.put(DO_NOT_RESOLVE_STRINGS_FOR, "url"); defaults.put(RESOLVE_STRINGS_ALL_FIELDS, Boolean.FALSE); defaults.put(PUT_BRACES_AROUND_CAPITALS, "");//"title;journal;booktitle;review;abstract"); defaults.put(NON_WRAPPABLE_FIELDS, "pdf;ps;url;doi;file"); defaults.put(USE_IMPORT_INSPECTION_DIALOG, Boolean.TRUE); defaults.put(USE_IMPORT_INSPECTION_DIALOG_FOR_SINGLE, Boolean.TRUE); defaults.put(GENERATE_KEYS_AFTER_INSPECTION, Boolean.TRUE); defaults.put(MARK_IMPORTED_ENTRIES, Boolean.TRUE); defaults.put(UNMARK_ALL_ENTRIES_BEFORE_IMPORTING, Boolean.TRUE); defaults.put(WARN_ABOUT_DUPLICATES_IN_INSPECTION, Boolean.TRUE); defaults.put(USE_TIME_STAMP, Boolean.FALSE); defaults.put(OVERWRITE_TIME_STAMP, Boolean.FALSE); defaults.put(TIME_STAMP_FORMAT, "yyyy-MM-dd"); defaults.put(TIME_STAMP_FIELD, BibtexFields.TIMESTAMP); defaults.put(UPDATE_TIMESTAMP, Boolean.FALSE); defaults.put(GENERATE_KEYS_BEFORE_SAVING, Boolean.FALSE); // behavior of JabRef before 2.10: both: false defaults.put(WRITEFIELD_ADDSPACES, Boolean.TRUE); defaults.put(WRITEFIELD_CAMELCASENAME, Boolean.TRUE); //behavior of JabRef before LWang_AdjustableFieldOrder 1 //0 sorted order (2.10 default), 1 unsorted order (2.9.2 default), 2 user defined defaults.put(WRITEFIELD_SORTSTYLE, 0); defaults.put(WRITEFIELD_USERDEFINEDORDER, "author;title;journal;year;volume;number;pages;month;note;volume;pages;part;eid"); defaults.put(WRITEFIELD_WRAPFIELD, Boolean.FALSE); defaults.put(RemotePreferences.USE_REMOTE_SERVER, Boolean.FALSE); defaults.put(RemotePreferences.REMOTE_SERVER_PORT, 6050); defaults.put(PERSONAL_JOURNAL_LIST, null); defaults.put(EXTERNAL_JOURNAL_LISTS, null); defaults.put(CITE_COMMAND, "\\cite"); // obsoleted by the app-specific ones (not any more?) defaults.put(FLOAT_MARKED_ENTRIES, Boolean.TRUE); defaults.put(USE_NATIVE_FILE_DIALOG_ON_MAC, Boolean.FALSE); defaults.put(FILECHOOSER_DISABLE_RENAME, Boolean.TRUE); defaults.put(LAST_USED_EXPORT, null); defaults.put(SIDE_PANE_WIDTH, -1); defaults.put(IMPORT_INSPECTION_DIALOG_WIDTH, 650); defaults.put(IMPORT_INSPECTION_DIALOG_HEIGHT, 650); defaults.put(SEARCH_DIALOG_WIDTH, 650); defaults.put(SEARCH_DIALOG_HEIGHT, 500); defaults.put(SHOW_FILE_LINKS_UPGRADE_WARNING, Boolean.TRUE); defaults.put(AUTOLINK_EXACT_KEY_ONLY, Boolean.FALSE); defaults.put(NUMERIC_FIELDS, "mittnum;author"); defaults.put(RUN_AUTOMATIC_FILE_SEARCH, Boolean.FALSE); defaults.put(USE_LOCK_FILES, Boolean.TRUE); defaults.put(AUTO_SAVE, Boolean.TRUE); defaults.put(AUTO_SAVE_INTERVAL, 5); defaults.put(PROMPT_BEFORE_USING_AUTOSAVE, Boolean.TRUE); defaults.put(ENFORCE_LEGAL_BIBTEX_KEY, Boolean.TRUE); defaults.put(BIBLATEX_MODE, Boolean.FALSE); // Curly brackets ({}) are the default delimiters, not quotes (") as these cause trouble when they appear within the field value: // Currently, JabRef does not escape them defaults.put(VALUE_DELIMITERS2, 1); defaults.put(INCLUDE_EMPTY_FIELDS, Boolean.FALSE); defaults.put(KEY_GEN_FIRST_LETTER_A, Boolean.TRUE); defaults.put(KEY_GEN_ALWAYS_ADD_LETTER, Boolean.FALSE); defaults.put(EMAIL_SUBJECT, Localization.lang("References")); defaults.put(OPEN_FOLDERS_OF_ATTACHED_FILES, Boolean.FALSE); defaults.put(ALLOW_FILE_AUTO_OPEN_BROWSE, Boolean.TRUE); defaults.put(WEB_SEARCH_VISIBLE, Boolean.FALSE); defaults.put(SELECTED_FETCHER_INDEX, 0); defaults.put(BIB_LOCATION_AS_FILE_DIR, Boolean.TRUE); defaults.put(BIB_LOC_AS_PRIMARY_DIR, Boolean.FALSE); defaults.put(DB_CONNECT_SERVER_TYPE, "MySQL"); defaults.put(DB_CONNECT_HOSTNAME, "localhost"); defaults.put(DB_CONNECT_DATABASE, "jabref"); defaults.put(DB_CONNECT_USERNAME, "root"); CleanUpAction.putDefaults(defaults); // defaults for DroppedFileHandler UI defaults.put(DroppedFileHandler.DFH_LEAVE, Boolean.FALSE); defaults.put(DroppedFileHandler.DFH_COPY, Boolean.TRUE); defaults.put(DroppedFileHandler.DFH_MOVE, Boolean.FALSE); defaults.put(DroppedFileHandler.DFH_RENAME, Boolean.FALSE); //defaults.put("lastAutodetectedImport", ""); //defaults.put("autoRemoveExactDuplicates", Boolean.FALSE); //defaults.put("confirmAutoRemoveExactDuplicates", Boolean.TRUE); //defaults.put("tempDir", System.getProperty("java.io.tmpdir")); //Util.pr(System.getProperty("java.io.tempdir")); //defaults.put("keyPattern", new LabelPattern(KEY_PATTERN)); defaults.put(ImportSettingsTab.PREF_IMPORT_ALWAYSUSE, Boolean.FALSE); defaults.put(ImportSettingsTab.PREF_IMPORT_DEFAULT_PDF_IMPORT_STYLE, ImportSettingsTab.DEFAULT_STYLE); // use BibTeX key appended with filename as default pattern defaults.put(ImportSettingsTab.PREF_IMPORT_FILENAMEPATTERN, ImportSettingsTab.DEFAULT_FILENAMEPATTERNS[1]); restoreKeyBindings(); customExports = new CustomExportList(new ExportComparator()); customImports = new CustomImportList(this); //defaults.put("oooWarning", Boolean.TRUE); updateSpecialFieldHandling(); WRAPPED_USERNAME = '[' + get(DEFAULT_OWNER) + ']'; MARKING_WITH_NUMBER_PATTERN = "\\[" + get(DEFAULT_OWNER).replaceAll("\\\\", "\\\\\\\\") + ":(\\d+)\\]"; String defaultExpression = "**/.*[bibtexkey].*\\\\.[extension]"; defaults.put(DEFAULT_REG_EXP_SEARCH_EXPRESSION_KEY, defaultExpression); defaults.put(REG_EXP_SEARCH_EXPRESSION_KEY, defaultExpression); defaults.put(AUTOLINK_USE_REG_EXP_SEARCH_KEY, Boolean.FALSE); defaults.put(USE_IEEE_ABRV, Boolean.FALSE); defaults.put(USE_CONVERT_TO_EQUATION, Boolean.FALSE); defaults.put(USE_CASE_KEEPER_ON_SEARCH, Boolean.TRUE); defaults.put(USE_UNIT_FORMATTER_ON_SEARCH, Boolean.TRUE); defaults.put(USER_FILE_DIR, Globals.FILE_FIELD + "Directory"); try { defaults.put(USER_FILE_DIR_IND_LEGACY, Globals.FILE_FIELD + "Directory" + '-' + get(DEFAULT_OWNER) + '@' + InetAddress.getLocalHost().getHostName()); // Legacy setting name - was a bug: @ not allowed inside BibTeX comment text. Retained for backward comp. defaults.put(USER_FILE_DIR_INDIVIDUAL, Globals.FILE_FIELD + "Directory" + '-' + get(DEFAULT_OWNER) + '-' + InetAddress.getLocalHost().getHostName()); // Valid setting name } catch (UnknownHostException ex) { LOGGER.info("Hostname not found.", ex); defaults.put(USER_FILE_DIR_IND_LEGACY, Globals.FILE_FIELD + "Directory" + '-' + get(DEFAULT_OWNER)); defaults.put(USER_FILE_DIR_INDIVIDUAL, Globals.FILE_FIELD + "Directory" + '-' + get(DEFAULT_OWNER)); } } public void setLanguageDependentDefaultValues() { // Entry editor tab 0: defaults.put(CUSTOM_TAB_NAME + "_def0", Localization.lang("General")); defaults.put(CUSTOM_TAB_FIELDS + "_def0", "crossref;keywords;file;doi;url;" + "comment;owner;timestamp"); // Entry editor tab 1: defaults.put(CUSTOM_TAB_FIELDS + "_def1", "abstract"); defaults.put(CUSTOM_TAB_NAME + "_def1", Localization.lang("Abstract")); // Entry editor tab 2: Review Field - used for research comments, etc. defaults.put(CUSTOM_TAB_FIELDS + "_def2", "review"); defaults.put(CUSTOM_TAB_NAME + "_def2", Localization.lang("Review")); } public boolean putBracesAroundCapitals(String fieldName) { return putBracesAroundCapitalsFields.contains(fieldName); } public void updateSpecialFieldHandling() { putBracesAroundCapitalsFields.clear(); String fieldString = get(PUT_BRACES_AROUND_CAPITALS); if (!fieldString.isEmpty()) { String[] fields = fieldString.split(";"); for (String field : fields) { putBracesAroundCapitalsFields.add(field.trim()); } } nonWrappableFields.clear(); fieldString = get(NON_WRAPPABLE_FIELDS); if (!fieldString.isEmpty()) { String[] fields = fieldString.split(";"); for (String field : fields) { nonWrappableFields.add(field.trim()); } } } public char getValueDelimiters(int index) { return getValueDelimiters()[index]; } private char[] getValueDelimiters() { return JabRefPreferences.VALUE_DELIMITERS[getInt(VALUE_DELIMITERS2)]; } /** * Check whether a key is set (differently from null). * * @param key The key to check. * @return true if the key is set, false otherwise. */ public boolean hasKey(String key) { return prefs.get(key, null) != null; } public String get(String key) { return prefs.get(key, (String) defaults.get(key)); } public String get(String key, String def) { return prefs.get(key, def); } public boolean getBoolean(String key) { return prefs.getBoolean(key, getBooleanDefault(key)); } public boolean getBoolean(String key, boolean def) { return prefs.getBoolean(key, def); } private boolean getBooleanDefault(String key) { return (Boolean) defaults.get(key); } public double getDouble(String key) { return prefs.getDouble(key, getDoubleDefault(key)); } private double getDoubleDefault(String key) { return (Double) defaults.get(key); } public int getInt(String key) { return prefs.getInt(key, getIntDefault(key)); } public int getIntDefault(String key) { return (Integer) defaults.get(key); } public byte[] getByteArray(String key) { return prefs.getByteArray(key, getByteArrayDefault(key)); } private byte[] getByteArrayDefault(String key) { return (byte[]) defaults.get(key); } public void put(String key, String value) { prefs.put(key, value); } public void putBoolean(String key, boolean value) { prefs.putBoolean(key, value); } public void putDouble(String key, double value) { prefs.putDouble(key, value); } public void putInt(String key, int value) { prefs.putInt(key, value); } public void putByteArray(String key, byte[] value) { prefs.putByteArray(key, value); } public void remove(String key) { prefs.remove(key); } /** * Puts a string array into the Preferences, by linking its elements with ';' into a single string. Escape * characters make the process transparent even if strings contain ';'. */ public void putStringArray(String key, String[] value) { if (value == null) { remove(key); return; } if (value.length > 0) { StringBuilder linked = new StringBuilder(); for (int i = 0; i < value.length - 1; i++) { linked.append(makeEscape(value[i])); linked.append(';'); } linked.append(makeEscape(value[value.length - 1])); put(key, linked.toString()); } else { put(key, ""); } } /** * Returns a String[] containing the chosen columns. */ public String[] getStringArray(String key) { String names = get(key); if (names == null) { return null; } StringReader rd = new StringReader(names); Vector<String> arr = new Vector<String>(); String rs; try { while ((rs = getNextUnit(rd)) != null) { arr.add(rs); } } catch (IOException ignored) { } String[] res = new String[arr.size()]; for (int i = 0; i < res.length; i++) { res[i] = arr.elementAt(i); } return res; } /** * Looks up a color definition in preferences, and returns the Color object. * * @param key The key for this setting. * @return The color corresponding to the setting. */ public Color getColor(String key) { String value = get(key); int[] rgb = getRgb(value); return new Color(rgb[0], rgb[1], rgb[2]); } public Color getDefaultColor(String key) { String value = (String) defaults.get(key); int[] rgb = getRgb(value); return new Color(rgb[0], rgb[1], rgb[2]); } /** * Set the default value for a key. This is useful for plugins that need to add default values for the prefs keys * they use. * * @param key The preferences key. * @param value The default value. */ public void putDefaultValue(String key, Object value) { defaults.put(key, value); } /** * Stores a color in preferences. * * @param key The key for this setting. * @param color The Color to store. */ public void putColor(String key, Color color) { String rgb = String.valueOf(color.getRed()) + ':' + String.valueOf(color.getGreen()) + ':' + String.valueOf(color.getBlue()); put(key, rgb); } /** * Looks up a color definition in preferences, and returns an array containing the RGB values. * * @param value The key for this setting. * @return The RGB values corresponding to this color setting. */ private int[] getRgb(String value) { String[] elements = value.split(":"); int[] values = new int[3]; values[0] = Integer.parseInt(elements[0]); values[1] = Integer.parseInt(elements[1]); values[2] = Integer.parseInt(elements[2]); return values; } /** * Returns the KeyStroke for this binding, as defined by the defaults, or in the Preferences. */ public KeyStroke getKey(String bindName) { String s = keyBinds.get(bindName); // If the current key bindings don't contain the one asked for, // we fall back on the default. This should only happen when a // user has his own set in Preferences, and has upgraded to a // new version where new bindings have been introduced. if (s == null) { s = defaultKeyBinds.get(bindName); if (s == null) { // there isn't even a default value // Output error LOGGER.info("Could not get key binding for \"" + bindName + '"'); // fall back to a default value s = "Not associated"; } // So, if there is no configured key binding, we add the fallback value to the current // hashmap, so this doesn't happen again, and so this binding // will appear in the KeyBindingsDialog. keyBinds.put(bindName, s); } if (OS.OS_X) { return getKeyForMac(KeyStroke.getKeyStroke(s)); } else { return KeyStroke.getKeyStroke(s); } } /** * Returns the KeyStroke for this binding, as defined by the defaults, or in the Preferences, but adapted for Mac * users, with the Command key preferred instead of Control. * TODO: Move to OS.java? Or replace with portable Java key codes, i.e. KeyEvent */ private KeyStroke getKeyForMac(KeyStroke ks) { if (ks == null) { return null; } int keyCode = ks.getKeyCode(); if ((ks.getModifiers() & InputEvent.CTRL_MASK) == 0) { return ks; } else { int modifiers = 0; if ((ks.getModifiers() & InputEvent.SHIFT_MASK) != 0) { modifiers = modifiers | InputEvent.SHIFT_MASK; } if ((ks.getModifiers() & InputEvent.ALT_MASK) != 0) { modifiers = modifiers | InputEvent.ALT_MASK; } if (SHORTCUT_MASK == -1) { try { SHORTCUT_MASK = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); } catch (Throwable ignored) { } } return KeyStroke.getKeyStroke(keyCode, SHORTCUT_MASK + modifiers); } } /** * Returns the HashMap containing all key bindings. */ public HashMap<String, String> getKeyBindings() { return keyBinds.getKeyBindings(); } /** * Returns the HashMap containing default key bindings. */ public HashMap<String, String> getDefaultKeys() { return defaultKeyBinds.getKeyBindings(); } /** * Clear all preferences. * * @throws BackingStoreException */ public void clear() throws BackingStoreException { prefs.clear(); } public void clear(String key) { prefs.remove(key); } /** * Calling this method will write all preferences into the preference store. */ public void flush() { if (getBoolean(MEMORY_STICK_MODE)) { try { exportPreferences("jabref.xml"); } catch (IOException e) { LOGGER.info("Could not save preferences for memory stick mode: " + e.getLocalizedMessage(), e); } } try { prefs.flush(); } catch (BackingStoreException ex) { ex.printStackTrace(); } } /** * Stores new key bindings into Preferences, provided they actually differ from the old ones. */ public void setNewKeyBindings(HashMap<String, String> newBindings) { if (!newBindings.equals(keyBinds)) { // This confirms that the bindings have actually changed. String[] bindNames = new String[newBindings.size()]; String[] bindings = new String[newBindings.size()]; int index = 0; for (String nm : newBindings.keySet()) { String bnd = newBindings.get(nm); bindNames[index] = nm; bindings[index] = bnd; index++; } putStringArray("bindNames", bindNames); putStringArray("bindings", bindings); keyBinds.overwriteBindings(newBindings); } } /** * Fetches key patterns from preferences. * The implementation doesn't cache the results * * @return LabelPattern containing all keys. Returned LabelPattern has no parent */ public GlobalLabelPattern getKeyPattern() { JabRefPreferences.keyPattern = new GlobalLabelPattern(); Preferences pre = Preferences.userNodeForPackage(GlobalLabelPattern.class); try { String[] keys = pre.keys(); if (keys.length > 0) { for (String key : keys) { JabRefPreferences.keyPattern.addLabelPattern(key, pre.get(key, null)); } } } catch (BackingStoreException ex) { LOGGER.info("BackingStoreException in JabRefPreferences.getKeyPattern", ex); } return JabRefPreferences.keyPattern; } /** * Adds the given key pattern to the preferences * * @param pattern the pattern to store */ public void putKeyPattern(GlobalLabelPattern pattern) { JabRefPreferences.keyPattern = pattern; // Store overridden definitions to Preferences. Preferences pre = Preferences.userNodeForPackage(GlobalLabelPattern.class); try { pre.clear(); // We remove all old entries. } catch (BackingStoreException ex) { LOGGER.info("BackingStoreException in JabRefPreferences.putKeyPattern", ex); } Enumeration<String> allKeys = pattern.getAllKeys(); while (allKeys.hasMoreElements()) { String key = allKeys.nextElement(); if (!pattern.isDefaultValue(key)) { ArrayList<String> value = pattern.getValue(key); // no default value // the first entry in the array is the full pattern // see net.sf.jabref.logic.labelPattern.LabelPatternUtil.split(String) pre.put(key, value.get(0)); } } } private void restoreKeyBindings() { // Define default keybindings. defaultKeyBinds = new KeyBinds(); // First read the bindings, and their names. String[] bindNames = getStringArray("bindNames"); String[] bindings = getStringArray("bindings"); // Then set up the key bindings HashMap. if (bindNames == null || bindings == null || bindNames.length != bindings.length) { // Nothing defined in Preferences, or something is wrong. keyBinds = new KeyBinds(); return; } for (int i = 0; i < bindNames.length; i++) { keyBinds.put(bindNames[i], bindings[i]); } } private String getNextUnit(Reader data) throws IOException { // character last read // -1 if end of stream // initialization necessary, because of Java compiler int c = -1; // last character was escape symbol boolean escape = false; // true if a ";" is found boolean done = false; StringBuilder res = new StringBuilder(); while (!done && (c = data.read()) != -1) { if (c == '\\') { if (!escape) { escape = true; } else { escape = false; res.append('\\'); } } else { if (c == ';') { if (!escape) { done = true; } else { res.append(';'); } } else { res.append((char) c); } escape = false; } } if (res.length() > 0) { return res.toString(); } else if (c == -1) { // end of stream return null; } else { return ""; } } private String makeEscape(String s) { StringBuilder sb = new StringBuilder(); int c; for (int i = 0; i < s.length(); i++) { c = s.charAt(i); if (c == '\\' || c == ';') { sb.append('\\'); } sb.append((char) c); } return sb.toString(); } /** * Stores all information about the entry type in preferences, with the tag given by number. */ public void storeCustomEntryType(CustomEntryType tp, int number) { String nr = "" + number; put(JabRefPreferences.CUSTOM_TYPE_NAME + nr, tp.getName()); put(JabRefPreferences.CUSTOM_TYPE_REQ + nr, tp.getRequiredFieldsString()); putStringArray(JabRefPreferences.CUSTOM_TYPE_OPT + nr, tp.getOptionalFields().toArray(new String[0])); putStringArray(JabRefPreferences.CUSTOM_TYPE_PRIOPT + nr, tp.getPrimaryOptionalFields().toArray(new String[0])); } /** * Retrieves all information about the entry type in preferences, with the tag given by number. */ public CustomEntryType getCustomEntryType(int number) { String nr = "" + number; String name = get(JabRefPreferences.CUSTOM_TYPE_NAME + nr); String[] req = getStringArray(JabRefPreferences.CUSTOM_TYPE_REQ + nr); String[] opt = getStringArray(JabRefPreferences.CUSTOM_TYPE_OPT + nr); String[] priOpt = getStringArray(JabRefPreferences.CUSTOM_TYPE_PRIOPT + nr); if (name == null) { return null; } if (priOpt == null) { return new CustomEntryType(StringUtil.capitalizeFirst(name), req, opt); } String[] secOpt = StringUtil.getRemainder(opt, priOpt); return new CustomEntryType(StringUtil.capitalizeFirst(name), req, priOpt, secOpt); } public List<ExternalFileType> getDefaultExternalFileTypes() { List<ExternalFileType> list = new ArrayList<ExternalFileType>(); list.add(new ExternalFileType("PDF", "pdf", "application/pdf", "evince", "pdfSmall", IconTheme.getImage("pdfSmall"))); list.add(new ExternalFileType("PostScript", "ps", "application/postscript", "evince", "psSmall", IconTheme.getImage("psSmall"))); list.add(new ExternalFileType("Word", "doc", "application/msword", "oowriter", "openoffice", IconTheme.getImage("openoffice"))); list.add(new ExternalFileType("Word 2007+", "docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "oowriter", "openoffice", IconTheme.getImage("openoffice"))); list.add(new ExternalFileType("OpenDocument text", "odt", "application/vnd.oasis.opendocument.text", "oowriter", "openoffice", IconTheme.getImage("openoffice"))); list.add(new ExternalFileType("Excel", "xls", "application/excel", "oocalc", "openoffice", IconTheme.getImage("openoffice"))); list.add(new ExternalFileType("Excel 2007+", "xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "oocalc", "openoffice", IconTheme.getImage("openoffice"))); list.add(new ExternalFileType("OpenDocument spreadsheet", "ods", "application/vnd.oasis.opendocument.spreadsheet", "oocalc", "openoffice", IconTheme.getImage("openoffice"))); list.add(new ExternalFileType("PowerPoint", "ppt", "application/vnd.ms-powerpoint", "ooimpress", "openoffice", IconTheme.getImage("openoffice"))); list.add(new ExternalFileType("PowerPoint 2007+", "pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation", "ooimpress", "openoffice", IconTheme.getImage("openoffice"))); list.add(new ExternalFileType("OpenDocument presentation", "odp", "application/vnd.oasis.opendocument.presentation", "ooimpress", "openoffice", IconTheme.getImage("openoffice"))); list.add(new ExternalFileType("Rich Text Format", "rtf", "application/rtf", "oowriter", "openoffice", IconTheme.getImage("openoffice"))); list.add(new ExternalFileType("PNG image", "png", "image/png", "gimp", "picture", IconTheme.getImage("picture"))); list.add(new ExternalFileType("GIF image", "gif", "image/gif", "gimp", "picture", IconTheme.getImage("picture"))); list.add(new ExternalFileType("JPG image", "jpg", "image/jpeg", "gimp", "picture", IconTheme.getImage("picture"))); list.add(new ExternalFileType("Djvu", "djvu", "", "evince", "psSmall", IconTheme.getImage("psSmall"))); list.add(new ExternalFileType("Text", "txt", "text/plain", "emacs", "emacs", IconTheme.getImage("emacs"))); list.add(new ExternalFileType("LaTeX", "tex", "application/x-latex", "emacs", "emacs", IconTheme.getImage("emacs"))); list.add(new ExternalFileType("CHM", "chm", "application/mshelp", "gnochm", "www", IconTheme.getImage("www"))); list.add(new ExternalFileType("TIFF image", "tiff", "image/tiff", "gimp", "picture", IconTheme.getImage("picture"))); list.add(new ExternalFileType("URL", "html", "text/html", "firefox", "www", IconTheme.getImage("www"))); list.add(new ExternalFileType("MHT", "mht", "multipart/related", "firefox", "www", IconTheme.getImage("www"))); list.add(new ExternalFileType("ePUB", "epub", "application/epub+zip", "firefox", "www", IconTheme.getImage("www"))); // On all OSes there is a generic application available to handle file opening, // so we don't need the default application settings anymore: for (ExternalFileType type : list) { type.setOpenWith(""); } return list; } public ExternalFileType[] getExternalFileTypeSelection() { return externalFileTypes.toArray(new ExternalFileType[externalFileTypes.size()]); } /** * Look up the external file type registered with this name, if any. * * @param name The file type name. * @return The ExternalFileType registered, or null if none. */ public ExternalFileType getExternalFileTypeByName(String name) { for (ExternalFileType type : externalFileTypes) { if (type.getName().equals(name)) { return type; } } // Return an instance that signifies an unknown file type: return new UnknownExternalFileType(name); } /** * Look up the external file type registered for this extension, if any. * * @param extension The file extension. * @return The ExternalFileType registered, or null if none. */ public ExternalFileType getExternalFileTypeByExt(String extension) { for (ExternalFileType type : externalFileTypes) { if (type.getExtension() != null && type.getExtension().equalsIgnoreCase(extension)) { return type; } } return null; } /** * Look up the external file type registered for this filename, if any. * * @param filename The name of the file whose type to look up. * @return The ExternalFileType registered, or null if none. */ public ExternalFileType getExternalFileTypeForName(String filename) { int longestFound = -1; ExternalFileType foundType = null; for (ExternalFileType type : externalFileTypes) { if (type.getExtension() != null && filename.toLowerCase(). endsWith(type.getExtension().toLowerCase())) { if (type.getExtension().length() > longestFound) { longestFound = type.getExtension().length(); foundType = type; } } } return foundType; } /** * Look up the external file type registered for this MIME type, if any. * * @param mimeType The MIME type. * @return The ExternalFileType registered, or null if none. For the mime type "text/html", a valid file type is * guaranteed to be returned. */ public ExternalFileType getExternalFileTypeByMimeType(String mimeType) { for (ExternalFileType type : externalFileTypes) { if (type.getMimeType() != null && type.getMimeType().equals(mimeType)) { return type; } } if (mimeType.equals("text/html")) { return HTML_FALLBACK_TYPE; } else { return null; } } /** * Reset the List of external file types after user customization. * * @param types The new List of external file types. This is the complete list, not just new entries. */ public void setExternalFileTypes(List<ExternalFileType> types) { // First find a list of the default types: List<ExternalFileType> defTypes = getDefaultExternalFileTypes(); // Make a list of types that are unchanged: List<ExternalFileType> unchanged = new ArrayList<ExternalFileType>(); externalFileTypes.clear(); for (ExternalFileType type : types) { externalFileTypes.add(type); // See if we can find a type with matching name in the default type list: ExternalFileType found = null; for (ExternalFileType defType : defTypes) { if (defType.getName().equals(type.getName())) { found = defType; break; } } if (found != null) { // Found it! Check if it is an exact match, or if it has been customized: if (found.equals(type)) { unchanged.add(type); } else { // It was modified. Remove its entry from the defaults list, since // the type hasn't been removed: defTypes.remove(found); } } } // Go through unchanged types. Remove them from the ones that should be stored, // and from the list of defaults, since we don't need to mention these in prefs: for (ExternalFileType type : unchanged) { defTypes.remove(type); types.remove(type); } // Now set up the array to write to prefs, containing all new types, all modified // types, and a flag denoting each default type that has been removed: String[][] array = new String[types.size() + defTypes.size()][]; int i = 0; for (ExternalFileType type : types) { array[i] = type.getStringArrayRepresentation(); i++; } for (ExternalFileType type : defTypes) { array[i] = new String[] {type.getName(), JabRefPreferences.FILE_TYPE_REMOVED_FLAG}; i++; } //System.out.println("Encoded: '"+Util.encodeStringArray(array)+"'"); put("externalFileTypes", StringUtil.encodeStringArray(array)); } /** * Set up the list of external file types, either from default values, or from values recorded in Preferences. */ public void updateExternalFileTypes() { // First get a list of the default file types as a starting point: List<ExternalFileType> types = getDefaultExternalFileTypes(); // If no changes have been stored, simply use the defaults: if (prefs.get("externalFileTypes", null) == null) { externalFileTypes.clear(); externalFileTypes.addAll(types); return; } // Read the prefs information for file types: String[][] vals = StringUtil.decodeStringDoubleArray(prefs.get("externalFileTypes", "")); for (String[] val : vals) { if (val.length == 2 && val[1].equals(JabRefPreferences.FILE_TYPE_REMOVED_FLAG)) { // This entry indicates that a default entry type should be removed: ExternalFileType toRemove = null; for (ExternalFileType type : types) { if (type.getName().equals(val[0])) { toRemove = type; break; } } // If we found it, remove it from the type list: if (toRemove != null) { types.remove(toRemove); } } else { // A new or modified entry type. Construct it from the string array: ExternalFileType type = new ExternalFileType(val); // Check if there is a default type with the same name. If so, this is a // modification of that type, so remove the default one: ExternalFileType toRemove = null; for (ExternalFileType defType : types) { if (type.getName().equals(defType.getName())) { toRemove = defType; break; } } // If we found it, remove it from the type list: if (toRemove != null) { types.remove(toRemove); } // Then add the new one: types.add(type); } } // Finally, build the list of types based on the modified defaults list: for (ExternalFileType type : types) { externalFileTypes.add(type); } } /** * Removes all information about custom entry types with tags of * * @param number or higher. */ public void purgeCustomEntryTypes(int number) { purgeSeries(JabRefPreferences.CUSTOM_TYPE_NAME, number); purgeSeries(JabRefPreferences.CUSTOM_TYPE_REQ, number); purgeSeries(JabRefPreferences.CUSTOM_TYPE_OPT, number); purgeSeries(JabRefPreferences.CUSTOM_TYPE_PRIOPT, number); } /** * Removes all entries keyed by prefix+number, where number is equal to or higher than the given number. * * @param number or higher. */ public void purgeSeries(String prefix, int number) { while (get(prefix + number) != null) { remove(prefix + number); number++; } } public EntryEditorTabList getEntryEditorTabList() { if (tabList == null) { updateEntryEditorTabList(); } return tabList; } public void updateEntryEditorTabList() { tabList = new EntryEditorTabList(); } /** * Exports Preferences to an XML file. * * @param filename String File to export to */ public void exportPreferences(String filename) throws IOException { File f = new File(filename); OutputStream os = new FileOutputStream(f); try { prefs.exportSubtree(os); } catch (BackingStoreException ex) { throw new IOException(ex); } finally { if (os != null) { os.close(); } } } /** * Imports Preferences from an XML file. * * @param filename String File to import from */ public void importPreferences(String filename) throws IOException { File f = new File(filename); InputStream is = new FileInputStream(f); try { Preferences.importPreferences(is); } catch (InvalidPreferencesFormatException ex) { throw new IOException(ex); } } /** * Determines whether the given field should be written without any sort of wrapping. * * @param fieldName The field name. * @return true if the field should not be wrapped. */ public boolean isNonWrappableField(String fieldName) { return nonWrappableFields.contains(fieldName); } /** * ONLY FOR TESTING! * * Do not use in production code. Otherwise the singleton pattern is broken and preferences might get lost. * @param prefs */ void overwritePreferences(JabRefPreferences prefs) { singleton = prefs; } }
package org.apache.mesos.hdfs; import com.google.inject.Inject; import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.mesos.MesosSchedulerDriver; import org.apache.mesos.Protos; import org.apache.mesos.Protos.*; import org.apache.mesos.SchedulerDriver; import org.apache.mesos.hdfs.config.SchedulerConf; import org.apache.mesos.hdfs.state.AcquisitionPhase; import org.apache.mesos.hdfs.state.LiveState; import org.apache.mesos.hdfs.state.PersistentState; import org.apache.mesos.hdfs.util.HDFSConstants; import java.util.*; import java.util.concurrent.ExecutionException; public class Scheduler implements org.apache.mesos.Scheduler, Runnable { public static final Log log = LogFactory.getLog(Scheduler.class); private final SchedulerConf conf; private final LiveState liveState; private PersistentState persistentState; @Inject public Scheduler(SchedulerConf conf, LiveState liveState) { this(conf, liveState, new PersistentState(conf)); } public Scheduler(SchedulerConf conf, LiveState liveState, PersistentState persistentState) { this.conf = conf; this.liveState = liveState; this.persistentState = persistentState; } @Override public void disconnected(SchedulerDriver driver) { log.info("Scheduler driver disconnected"); } @Override public void error(SchedulerDriver driver, String message) { log.error("Scheduler driver error: " + message); } @Override public void executorLost(SchedulerDriver driver, ExecutorID executorID, SlaveID slaveID, int status) { log.info("Executor lost: executorId=" + executorID.getValue() + " slaveId=" + slaveID.getValue() + " status=" + status); } @Override public void frameworkMessage(SchedulerDriver driver, ExecutorID executorID, SlaveID slaveID, byte[] data) { log.info("Framework message: executorId=" + executorID.getValue() + " slaveId=" + slaveID.getValue() + " data='" + Arrays.toString(data) + "'"); } @Override public void offerRescinded(SchedulerDriver driver, OfferID offerId) { log.info("Offer rescinded: offerId=" + offerId.getValue()); } @Override public void registered(SchedulerDriver driver, FrameworkID frameworkId, MasterInfo masterInfo) { try { persistentState.setFrameworkId(frameworkId); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } log.info("Registered framework frameworkId=" + frameworkId.getValue()); liveState.updateReconciliationTimestamp(); driver.reconcileTasks(Collections.<Protos.TaskStatus>emptyList()); } @Override public void reregistered(SchedulerDriver driver, MasterInfo masterInfo) { log.info("Reregistered framework: starting task reconcile"); liveState.updateReconciliationTimestamp(); driver.reconcileTasks(Collections.<Protos.TaskStatus> emptyList()); } @Override public void statusUpdate(SchedulerDriver driver, TaskStatus status) { log.info(String.format( "Received status update for taskId=%s state=%s message='%s' stagingTasks.size=%d", status.getTaskId().getValue(), status.getState().toString(), status.getMessage(), liveState.getStagingTasksSize())); if (!isStagingState(status)) { liveState.removeStagingTask(status.getTaskId()); } if (isTerminalState(status)) { liveState.removeTask(status.getTaskId()); persistentState.removeTaskId(status.getTaskId().getValue()); if (liveState.reconciliationComplete()) { correctCurrentPhase(); } } else if (isRunningState(status)) { liveState.updateTaskForStatus(status); log.info(String.format("Current Acquisition Phase: %s", liveState .getCurrentAcquisitionPhase().toString())); switch (liveState.getCurrentAcquisitionPhase()) { case RECONCILING_TASKS : if (liveState.reconciliationComplete()) { reconcilePersistentState(); correctCurrentPhase(); } break; case JOURNAL_NODES : if (liveState.getJournalNodeSize() == conf.getJournalNodeCount()) { correctCurrentPhase(); } break; case NAME_NODE_1 : if (liveState.getNameNodeSize() == 1 && liveState.getFirstNameNodeTaskId() != null) { correctCurrentPhase(); } else { log.info("Cannot locate first namenode task id"); } break; case NAME_NODE_2 : if (liveState.getNameNodeSize() == HDFSConstants.TOTAL_NAME_NODES && liveState.getSecondNameNodeTaskId() != null) { reloadConfigsOnAllRunningTasks(driver); if (!liveState.isNameNode1Initialized() && !status.getMessage().equals(HDFSConstants.NAME_NODE_INIT_MESSAGE)) { sendMessageTo( driver, liveState.getFirstNameNodeTaskId(), liveState.getFirstNameNodeSlaveId(), HDFSConstants.NAME_NODE_INIT_MESSAGE); } if (liveState.isNameNode1Initialized() && !liveState.isNameNode2Initialized()) { sendMessageTo( driver, liveState.getSecondNameNodeTaskId(), liveState.getSecondNameNodeSlaveId(), HDFSConstants.NAME_NODE_BOOTSTRAP_MESSAGE); } else if (status.getMessage().equals(HDFSConstants.NAME_NODE_BOOTSTRAP_MESSAGE)) { correctCurrentPhase(); } } break; case DATA_NODES : break; } } else { log.warn(String.format("Don't know how to handle state=%s for taskId=%s", status.getState(), status.getTaskId().getValue())); } } @Override public void resourceOffers(SchedulerDriver driver, List<Offer> offers) { log.info(String.format("Received %d offers", offers.size())); if (liveState.getStagingTasksSize() != 0) { log.info("Declining offers because tasks are currently staging"); for (Offer offer : offers) { driver.declineOffer(offer.getId()); } } else { boolean acceptedOffer = false; for (Offer offer : offers) { if (acceptedOffer) { driver.declineOffer(offer.getId()); } else { switch (liveState.getCurrentAcquisitionPhase()) { case RECONCILING_TASKS : if (liveState.reconciliationComplete()) { reconcilePersistentState(); log.info("Current persistent state:"); log.info(String.format("JournalNodes: %s", persistentState.getJournalNodes())); log.info(String.format("NameNodes: %s", persistentState.getNameNodes())); log.info(String.format("DataNodes: %s", persistentState.getDataNodes())); correctCurrentPhase(); driver.declineOffer(offer.getId()); } else { log.info("Declining offers while reconciling tasks"); driver.declineOffer(offer.getId()); } break; case JOURNAL_NODES : if (liveState.getJournalNodeSize() < conf.getJournalNodeCount()) { if (maybeLaunchJournalNode(driver, offer)) { acceptedOffer = true; } else { driver.declineOffer(offer.getId()); } } break; case NAME_NODE_1 : if (maybeLaunchNameNode(driver, offer)) { acceptedOffer = true; } else { driver.declineOffer(offer.getId()); } break; case NAME_NODE_2 : if (maybeLaunchNameNode(driver, offer)) { acceptedOffer = true; } else { driver.declineOffer(offer.getId()); } break; case DATA_NODES : if (maybeLaunchDataNode(driver, offer)) { acceptedOffer = true; } else { driver.declineOffer(offer.getId()); } break; } } } } } @Override public void slaveLost(SchedulerDriver driver, SlaveID slaveId) { log.info("Slave lost slaveId=" + slaveId.getValue()); } @Override public void run() { FrameworkInfo.Builder frameworkInfo = FrameworkInfo.newBuilder() .setName("HDFS " + conf.getFrameworkName()) .setFailoverTimeout(conf.getFailoverTimeout()) .setUser(conf.getHdfsUser()) .setRole(conf.getHdfsRole()) .setCheckpoint(true); try { FrameworkID frameworkID = persistentState.getFrameworkID(); if (frameworkID != null) { frameworkInfo.setId(frameworkID); } } catch (InterruptedException | ExecutionException | InvalidProtocolBufferException e) { throw new RuntimeException(e); } MesosSchedulerDriver driver = new MesosSchedulerDriver(this, frameworkInfo.build(), conf.getMesosMasterUri()); driver.run().getValueDescriptor().getFullName(); } private void launchNode(SchedulerDriver driver, Offer offer, String nodeName, List<String> taskNames, String executorName) { log.info(String.format("Launching node of type %s with tasks %s", nodeName, taskNames.toString())); String taskIdName = String.format("%s.%s.%d", nodeName, executorName, System.currentTimeMillis()); List<Resource> resources = getExecutorResources(); ExecutorInfo executorInfo = createExecutor(taskIdName, nodeName, executorName, resources); List<TaskInfo> tasks = new ArrayList<>(); for (String taskName : taskNames) { List<Resource> taskResources = getTaskResources(taskName); TaskID taskId = TaskID.newBuilder() .setValue(String.format("task.%s.%s", taskName, taskIdName)) .build(); TaskInfo task = TaskInfo.newBuilder() .setExecutor(executorInfo) .setName(taskName) .setTaskId(taskId) .setSlaveId(offer.getSlaveId()) .addAllResources(taskResources) .setData(ByteString.copyFromUtf8( String.format("bin/hdfs-mesos-%s", taskName))) .build(); tasks.add(task); liveState.addStagingTask(task); persistentState.addNode(taskId, offer.getHostname(), taskName); } driver.launchTasks(Arrays.asList(offer.getId()), tasks); } private ExecutorInfo createExecutor(String taskIdName, String nodeName, String executorName, List<Resource> resources) { int confServerPort = conf.getConfigServerPort(); return ExecutorInfo .newBuilder() .setName(nodeName + " executor") .setExecutorId(ExecutorID.newBuilder().setValue("executor." + taskIdName).build()) .addAllResources(resources) .setCommand( CommandInfo .newBuilder() .addAllUris( Arrays.asList( CommandInfo.URI .newBuilder() .setValue( String.format("http://%s:%d/%s", conf.getFrameworkHostAddress(), confServerPort, HDFSConstants.HDFS_BINARY_FILE_NAME)) .build(), CommandInfo.URI .newBuilder() .setValue( String.format("http://%s:%d/%s", conf.getFrameworkHostAddress(), confServerPort, HDFSConstants.HDFS_CONFIG_FILE_NAME)) .build())) .setEnvironment(Environment.newBuilder() .addAllVariables(Arrays.asList( Environment.Variable.newBuilder() .setName("HADOOP_OPTS") .setValue(conf.getJvmOpts()).build(), Environment.Variable.newBuilder() .setName("HADOOP_HEAPSIZE") .setValue(String.format("%d", conf.getHadoopHeapSize())).build(), Environment.Variable.newBuilder() .setName("HADOOP_NAMENODE_OPTS") .setValue("-Xmx" + conf.getNameNodeHeapSize() + "m").build(), Environment.Variable.newBuilder() .setName("HADOOP_DATANODE_OPTS") .setValue("-Xmx" + conf.getDataNodeHeapSize() + "m").build(), Environment.Variable.newBuilder() .setName("EXECUTOR_OPTS") .setValue("-Xmx" + conf.getExecutorHeap() + "m").build()))) .setValue( "env ; cd hdfs-mesos-* && exec java $HADOOP_OPTS $EXECUTOR_OPTS " +
package org.broad.igv.bedpe; import org.apache.log4j.Logger; import org.broad.igv.Globals; import org.broad.igv.feature.genome.Genome; import org.broad.igv.track.TrackProperties; import org.broad.igv.ui.color.ColorUtilities; import org.broad.igv.util.ParsingUtils; import org.broad.igv.util.ResourceLocator; import java.awt.*; import java.io.BufferedReader; import java.io.IOException; import java.util.*; import java.util.List; public class BedPEParser { private static Logger log = Logger.getLogger(BedPEParser.class); enum DatasetType {TENX, CLUSTER, UNKNOWN} public static Dataset parse(ResourceLocator locator, Genome genome) throws IOException { int colorColumn = -1; int thicknessColumn = -1; DatasetType type = DatasetType.UNKNOWN; boolean parsedHeader = true; // Default column headers from BedPE spec. Can be overriden String[] columns = {"chrom1", "start1", "stop1", "chrom2", "start2", "stop2", "name", "score", "strand1", "strand2"}; boolean col7isNumeric = true; // Until proven otherwise Map<String, Color> colorCache = new HashMap<>(); List<BedPEFeature> features = new ArrayList<>(); BufferedReader br = null; try { br = ParsingUtils.openBufferedReader(locator.getPath()); String nextLine; boolean firstLine = true; int skippedLineCount = 0; while ((nextLine = br.readLine()) != null) { if (nextLine.startsWith("#columns")) { // An IGV hack, not sure anyone is using this try { String[] t1 = ParsingUtils.WHITESPACE_PATTERN.split(nextLine); if (t1.length == 2) { String[] t2 = ParsingUtils.SEMI_COLON_PATTERN.split(t1[1]); for (String keyValue : t2) { String[] t = keyValue.split("="); if (t[0].equals("color")) { colorColumn = Integer.parseInt(t[1]) - 1; } else if (t[0].equals("thickness")) { thicknessColumn = Integer.parseInt(t[1]) - 1; } } } } catch (NumberFormatException e) { log.error("Error parsing #column line.", e); } } else if (nextLine.trim().equals("#chrom1\tstart1\tstop1\tchrom2\tstart2\tstop2\tname\tqual\tstrand1\tstrand2\tfilters\tinfo")) { type = DatasetType.TENX; } if (nextLine.startsWith("#") || nextLine.startsWith("chr1\tx1\tx2")) { String[] tokens = Globals.tabPattern.split(nextLine); if (tokens.length >= 6) { columns = tokens; for (int i = 6; i < columns.length; i++) { if (columns[i].equalsIgnoreCase("color")) { colorColumn = i; } else if (columns[i].toLowerCase().equalsIgnoreCase("thickness")) { thicknessColumn = i; } } } } else if (nextLine.startsWith("track") || nextLine.startsWith("##track")) { TrackProperties trackProperties = new TrackProperties(); ParsingUtils.parseTrackLine(nextLine, trackProperties); } else if (firstLine && nextLine.startsWith("chromosome1\tx1\tx2") || nextLine.startsWith("chr1\tx1\tx2")) { columns = Globals.tabPattern.split(nextLine); for (int i = 6; i < columns.length; i++) { if (columns[i].equalsIgnoreCase("color")) { colorColumn = i; } } } else { String[] tokens = Globals.tabPattern.split(nextLine); if (tokens.length < 6) { if (skippedLineCount < 5) { skippedLineCount++; if(skippedLineCount == 5) { log.info("Skipping line: " + nextLine + (skippedLineCount < 5 ? "" : " Further skipped lines will not be logged")); } } continue; } String chr1 = genome == null ? tokens[0] : genome.getCanonicalChrName(tokens[0]); String chr2 = genome == null ? tokens[3] : genome.getCanonicalChrName(tokens[3]); int start1 = Integer.parseInt(tokens[1]); int end1 = Integer.parseInt(tokens[2]); int start2 = Integer.parseInt(tokens[4]); int end2 = Integer.parseInt(tokens[5]); BedPEFeature feature = new BedPEFeature(chr1, start1, end1, chr2, start2, end2); if (tokens.length > 6) { feature.name = tokens[6]; col7isNumeric = col7isNumeric && isNumeric(tokens[6]); } else { col7isNumeric = false; } if (tokens.length > 7) { feature.scoreString = tokens[7]; try { feature.score = Double.parseDouble(tokens[7]); } catch (NumberFormatException e) { feature.score = 0; } } if (tokens.length > 8) { Map<String, String> attributes = new LinkedHashMap<>(); for (int i = 8; i < tokens.length; i++) { String t = tokens[i]; String c = columns != null && columns.length > i ? columns[i] : String.valueOf(i); if (c.equals("info") && t.contains("=")) { String[] kvPairs = Globals.semicolonPattern.split(tokens[11]); for (String kvPair : kvPairs) { String[] kv = Globals.equalPattern.split(kvPair); if (kv.length > 1) { attributes.put(kv[0], kv[1]); } } } else { attributes.put(c, t); } } feature.attributes = attributes; feature.type = attributes.get("TYPE"); } if (colorColumn > 0 && tokens.length > colorColumn) { String colorString = tokens[colorColumn]; Color c = colorCache.get(colorString); if (c == null) { c = ColorUtilities.stringToColor(colorString); colorCache.put(colorString, c); } feature.color = c; } if (thicknessColumn > 0 && tokens.length > thicknessColumn) { feature.thickness = Integer.parseInt(tokens[thicknessColumn]); } // Skipping remaining fields for now features.add(feature); } firstLine = false; } // A hack to detect "interaction" bedpe files, which are not spec compliant. Interaction score is column 7 if (col7isNumeric) { for (BedPEFeature f : features) { f.score = Double.parseDouble(f.name); f.scoreString = f.name; f.name = null; } if (type == DatasetType.UNKNOWN) { type = DatasetType.CLUSTER; // A guess } } return new Dataset(type, features); } finally { br.close(); } } public static boolean isNumeric(String strNum) { return strNum.matches("-?\\d+(\\.\\d+)?"); } public static class Dataset { public DatasetType type; public List<BedPEFeature> features; public Dataset(DatasetType type, List<BedPEFeature> features) { this.type = type; this.features = features; } } }
package org.concord.energy3d.model; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import org.concord.energy3d.scene.Scene; import org.concord.energy3d.util.SelectUtil; import com.ardor3d.extension.model.collada.jdom.ColladaAnimUtils; import com.ardor3d.extension.model.collada.jdom.ColladaImporter; import com.ardor3d.extension.model.collada.jdom.ColladaMaterialUtils; import com.ardor3d.extension.model.collada.jdom.data.ColladaStorage; import com.ardor3d.math.Matrix3; import com.ardor3d.math.Vector3; import com.ardor3d.renderer.queue.RenderBucketType; import com.ardor3d.renderer.state.BlendState; import com.ardor3d.renderer.state.BlendState.TestFunction; import com.ardor3d.scenegraph.Spatial; import com.ardor3d.scenegraph.extension.BillboardNode; import com.ardor3d.scenegraph.extension.BillboardNode.BillboardAlignment; import com.ardor3d.scenegraph.shape.Quad; import com.ardor3d.util.resource.ResourceLocatorTool; import com.ardor3d.util.resource.ResourceSource; public class Tree extends HousePart { private static final long serialVersionUID = 1L; private static Spatial treeModel; private transient Spatial model; private transient BillboardNode billboard; public static void loadModel() { new Thread() { @Override public void run() { System.out.print("Loading tree model..."); Thread.yield(); final ResourceSource source = ResourceLocatorTool.locateResource(ResourceLocatorTool.TYPE_MODEL, "tree.dae"); final ColladaImporter colladaImporter = new ColladaImporter(); Logger.getLogger(ColladaAnimUtils.class.getName()).setLevel(Level.SEVERE); Logger.getLogger(ColladaMaterialUtils.class.getName()).setLevel(Level.SEVERE); ColladaStorage storage; try { storage = colladaImporter.load(source); treeModel = storage.getScene(); } catch (final IOException e) { e.printStackTrace(); } System.out.println("done"); } }.start(); } public Tree() { super(1, 1, 1); init(); } @Override protected void init() { super.init(); // model = treeModel.makeCopy(true); mesh = new Quad("Tree Quad", 30, 30); mesh.setRotation(new Matrix3().fromAngles(Math.PI / 2, 0, 0)); final BlendState bs = new BlendState(); bs.setEnabled(true); bs.setBlendEnabled(false); bs.setTestEnabled(true); bs.setTestFunction(TestFunction.GreaterThan); bs.setReference(0.7f); mesh.setRenderState(bs); mesh.getSceneHints().setRenderBucketType(RenderBucketType.Transparent); billboard = new BillboardNode("Billboard"); billboard.setAlignment(BillboardAlignment.AxialZ); billboard.attachChild(mesh); root.attachChild(billboard); // root.attachChild(mesh); } @Override public void setPreviewPoint(final int x, final int y) { final int index = 0; final PickedHousePart pick = SelectUtil.pickPart(x, y, (Spatial) null); Vector3 p = points.get(index); if (pick != null) { p = pick.getPoint(); snapToGrid(p, getAbsPoint(index), getGridSize()); p.setZ(15); points.get(index).set(p); } draw(); setEditPointsVisible(true); } @Override protected boolean mustHaveContainer() { return false; } @Override public boolean isDrawable() { return true; } @Override protected void drawMesh() { billboard.setTranslation(getAbsPoint(0)); // mesh.setTranslation(getAbsPoint(0)); } @Override protected String getTextureFileName() { return "tree.png"; } @Override public void updateTextureAndColor() { updateTextureAndColor(mesh, Scene.getInstance().getWallColor()); } }
package org.jsoftware.utils; import java.time.Instant; import java.util.Collection; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.function.Supplier; import java.util.stream.Collectors; /** * Simple cache based on LinkedHashMap * @author szalik */ public class SimpleCache<K,V> implements Map<K,V> { private final long timeoutMillis; private final SimpleCacheMap<K,CacheEntry<V>> cacheMap; /** * @param timeoutMillis cache ttl im milliseconds * @param cacheSize cache size */ public SimpleCache(long timeoutMillis, int cacheSize) { this.timeoutMillis = timeoutMillis; this.cacheMap = new SimpleCacheMap<>(cacheSize); } @Override public int size() { return cacheMap.size(); } @Override public boolean isEmpty() { return cacheMap.isEmpty(); } @Override public boolean containsKey(Object key) { return cacheMap.containsKey(key); } @Override public boolean containsValue(Object value) { for(CacheEntry<V> ce : cacheMap.values()) { if ((value == null && ce.getValue() == null) || (value != null && value.equals(ce.getValue()) && isValid(ce))) { return true; } } return false; } @Override public V get(Object key) { CacheEntry<V> ce = cacheMap.get(key); return isValid(ce) ? ce.getValue() : null; } @Override public V put(K key, V value) { CacheEntry<V> ce = createOrGetEntry(key); ce.put(now().toEpochMilli() + timeoutMillis, value); return isValid(ce) ? ce.getValue() : null; } @Override public V remove(Object key) { CacheEntry<V> ce = cacheMap.remove(key); return isValid(ce) ? ce.getValue() : null; } @Override public void putAll(Map<? extends K, ? extends V> m) { m.entrySet().forEach(me -> { CacheEntry<V> ce = createOrGetEntry(me.getKey()); ce.put(now().toEpochMilli() + timeoutMillis, me.getValue()); }); } @Override public void clear() { cacheMap.clear(); } @Override public Set<K> keySet() { return cacheMap.keySet(); } @Override public Collection<V> values() { return cacheMap.values().stream().map(ce -> ce.getValue()).collect(Collectors.toList()); } @Override public Set<Entry<K, V>> entrySet() { throw new NotImplementedException(); } /** * Thread-safe method fetching cache object * @param key cache key * @param supplier object supplier * @return object form cache or produced by supplier */ public V fetch(K key, Supplier<V> supplier) { CacheEntry<V> ce = createOrGetEntry(key); if (isValid(ce)) { return ce.getValue(); } else { ce.updateValue(now().toEpochMilli() + timeoutMillis, supplier); return ce.getValue(); } } private boolean isValid(CacheEntry<V> ce) { if (ce == null) { return false; } return ce.getTimeout() > now().toEpochMilli(); } private CacheEntry<V> createOrGetEntry(K key) { synchronized (cacheMap) { CacheEntry<V> ce = cacheMap.get(key); if (ce == null) { ce = new CacheEntry<>(); cacheMap.put(key, ce); } return ce; } } protected Instant now() { return Instant.now(); } } class CacheEntry<V> { private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); private volatile long timeout = Long.MIN_VALUE; private volatile V value; public long getTimeout() { return timeout; } public V getValue() { Lock rl = this.readWriteLock.readLock(); rl.lock(); try { return value; } finally { rl.unlock(); } } public void updateValue(long timeout, Supplier<V> supplier) { Lock wl = this.readWriteLock.writeLock(); if (! wl.tryLock()) { throw new IllegalStateException(); } try { this.value = null; this.timeout = timeout; this.value = supplier.get(); } finally { wl.unlock(); } } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CacheEntry<?> that = (CacheEntry<?>) o; return !(value != null ? !value.equals(that.value) : that.value != null); } @Override public int hashCode() { return value != null ? value.hashCode() : 0; } public void put(long timeout, V value) { this.timeout = timeout; this.value = value; } } class SimpleCacheMap<K,V> extends LinkedHashMap<K,V> { private final int cacheSize; SimpleCacheMap(int cacheSize) {this.cacheSize = cacheSize;} @Override protected boolean removeEldestEntry(Map.Entry eldest) { return this.size() >= cacheSize; } }
package org.jtrfp.trcl.beh; import java.lang.ref.WeakReference; import org.apache.commons.math3.geometry.euclidean.threed.Rotation; import org.apache.commons.math3.geometry.euclidean.threed.Vector3D; import org.jtrfp.trcl.core.TRFactory; import org.jtrfp.trcl.math.Vect3D; import org.jtrfp.trcl.math.Vect3D.ZeroNormException; import org.jtrfp.trcl.obj.WorldObject; public class FacingObject extends Behavior { private WeakReference<WorldObject> target; private final double [] work = new double[3]; private final double [] perp = new double[3]; private final double [] UP = new double[]{0,1,0}; private final double [] newTop = new double[3]; private Rotation readingOffset = Rotation.IDENTITY; private static final Vector3D DEFAULT_HEADING = Vector3D.PLUS_K; private static final Vector3D DEFAULT_TOP = Vector3D.PLUS_J; @Override public void tick(long tickTimeMillis){ if(target!=null){ final WorldObject parent = getParent(); final double [] tPos = target.get().getPosition(); final double [] pPos = parent.getPosition(); TRFactory.twosComplimentSubtract(tPos, pPos, work); Vector3D newHeading; try{newHeading = new Vector3D(Vect3D.normalize(work,work));} catch(ZeroNormException e){return;} Vect3D.cross(work, UP, perp); Vect3D.cross(perp, work, newTop); if(Vect3D.norm(newTop) == 0 || Vect3D.norm(perp) == 0) return;//Catch invalid state and abort final Rotation facingRot = new Rotation(DEFAULT_HEADING,DEFAULT_TOP,newHeading,new Vector3D(newTop)); parent.setHeading(facingRot.applyTo(readingOffset).applyTo(DEFAULT_HEADING)); parent.setTop (facingRot.applyTo(readingOffset).applyTo(DEFAULT_TOP)); }//end if(!null) }//end _tick(...) /** * @return the target */ public WorldObject getTarget() { return target.get(); } /** * @param target the target to set */ public FacingObject setTarget(WorldObject target) { this.target = new WeakReference<WorldObject>(target); return this; } /** * @return the readingOffset */ public Rotation getHeadingOffset() { return readingOffset; } /** * @param readingOffset the readingOffset to set */ public void setHeadingOffset(Rotation readingOffset) { this.readingOffset = readingOffset; } }//end FacingObject
package org.lantern; import java.net.InetAddress; import java.util.TimerTask; import org.lantern.event.Events; import org.lantern.state.Connectivity; import org.lantern.state.Model; import org.lastbamboo.common.stun.client.PublicIpAddress; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Inject; public class ConnectivityChecker extends TimerTask { private static Logger LOG = LoggerFactory .getLogger(ConnectivityChecker.class); private final Model model; private boolean connected = false; @Inject ConnectivityChecker(final Model model) { this.model = model; } @Override public void run() { final InetAddress ip = new PublicIpAddress().getPublicIpAddress(); Connectivity connectivity = model.getConnectivity(); if (ip == null) { LOG.info("No IP -- possibly no internet connection"); if (connected) { connected = false; ConnectivityChangedEvent event = new ConnectivityChangedEvent(false, false, null); Events.asyncEventBus().post(event); } return; } String oldIp = connectivity.getIp(); String newIpString = ip.getHostAddress(); connectivity.setIp(newIpString); if (newIpString.equals(oldIp)) { if (!connected) { ConnectivityChangedEvent event = new ConnectivityChangedEvent(true, true, ip); Events.asyncEventBus().post(event); connected = true; } } else { connected = true; ConnectivityChangedEvent event = new ConnectivityChangedEvent(true, false, ip); Events.asyncEventBus().post(event); } } }
package org.leplus.util; import java.io.IOException; import java.util.AbstractSet; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Set; public class IdentityHashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable { private static final Object DUMMY = new Object(); private IdentityHashMap<E, Object> map; public IdentityHashSet() { super(); map = new IdentityHashMap<E, Object>(); } public IdentityHashSet(final int expectedMaxSize) { super(); map = new IdentityHashMap<E, Object>(expectedMaxSize); } @Override public boolean add(final E e) { return map.put(e, DUMMY) == null; } @Override public void clear() { map.clear(); } @Override public boolean contains(final Object o) { return map.containsKey(o); } @Override public boolean isEmpty() { return map.isEmpty(); } @Override public Iterator<E> iterator() { return map.keySet().iterator(); } @Override public boolean remove(final Object o) { return map.remove(o) == DUMMY; } @Override public int size() { return map.size(); } @Override public int hashCode() { return map.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; IdentityHashSet<?> other = (IdentityHashSet<?>) obj; if (map == null) { if (other.map != null) return false; } else if (!map.equals(other.map)) return false; return true; } @SuppressWarnings("unchecked") public Object clone() { try { IdentityHashSet<E> newSet = (IdentityHashSet<E>) super.clone(); newSet.map = (IdentityHashMap<E, Object>) map.clone(); return newSet; } catch (CloneNotSupportedException e) { throw new AssertionError("Unexpected cloning error"); } } }
package org.lightmare.deploy.fs; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.Path; import java.nio.file.StandardWatchEventKinds; import java.nio.file.WatchEvent; import java.nio.file.WatchEvent.Kind; import java.nio.file.WatchKey; import java.nio.file.WatchService; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.apache.log4j.Logger; import org.lightmare.cache.ConnectionContainer; import org.lightmare.cache.DeploymentDirectory; import org.lightmare.cache.MetaContainer; import org.lightmare.cache.RestContainer; import org.lightmare.config.Configuration; import org.lightmare.jpa.datasource.FileParsers; import org.lightmare.jpa.datasource.Initializer; import org.lightmare.rest.providers.RestProvider; import org.lightmare.utils.CollectionUtils; import org.lightmare.utils.LogUtils; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.concurrent.ThreadFactoryUtil; import org.lightmare.utils.fs.WatchUtils; /** * Deployment manager, {@link Watcher#deployFile(URL)}, * {@link Watcher#undeployFile(URL)}, {@link Watcher#listDeployments()} and * {@link File} modification event handler for deployments if java version is * 1.7 or above * * @author levan * @since 0.0.45-SNAPSHOT */ public class Watcher implements Runnable { //Name of deployment watch service thread private static final String DEPLOY_THREAD_NAME = "watch_thread"; private static final int DEPLOY_POOL_PRIORITY = Thread.MAX_PRIORITY - 5; private static final long SLEEP_TIME = 5500L; private static final ExecutorService DEPLOY_POOL = Executors .newSingleThreadExecutor(new ThreadFactoryUtil(DEPLOY_THREAD_NAME, DEPLOY_POOL_PRIORITY)); private Set<DeploymentDirectory> deployments; private Set<String> dataSources; private static final Logger LOG = Logger.getLogger(Watcher.class); /** * Defines file types for watch service * * @author Levan * @since 0.0.45-SNAPSHOT */ private static enum WatchFileType { DATA_SOURCE, DEPLOYMENT, NONE; } /** * To filter only deployed sub files from directory * * @author levan * @since 0.0.45-SNAPSHOT */ private static class DeployFiletr implements FileFilter { @Override public boolean accept(File file) { boolean accept; try { URL url = file.toURI().toURL(); url = WatchUtils.clearURL(url); accept = MetaContainer.chackDeployment(url); } catch (MalformedURLException ex) { LOG.error(ex.getMessage(), ex); accept = false; } catch (IOException ex) { LOG.error(ex.getMessage(), ex); accept = false; } return accept; } } private Watcher() { deployments = getDeployDirectories(); dataSources = getDataSourcePaths(); } /** * Clears and gets file {@link URL} by file name * * @param fileName * @return {@link URL} * @throws IOException */ private static URL getAppropriateURL(String fileName) throws IOException { File file = new File(fileName); URL url = file.toURI().toURL(); url = WatchUtils.clearURL(url); return url; } /** * Gets {@link Set} of {@link DeploymentDirectory} instances from * configuration * * @return {@link Set}<code><DeploymentDirectory></code> */ private static Set<DeploymentDirectory> getDeployDirectories() { Collection<Configuration> configs = MetaContainer.CONFIGS.values(); Set<DeploymentDirectory> deploymetDirss = new HashSet<DeploymentDirectory>(); Set<DeploymentDirectory> deploymetDirssCurrent; for (Configuration config : configs) { deploymetDirssCurrent = config.getDeploymentPath(); if (config.isWatchStatus() && CollectionUtils.valid(deploymetDirssCurrent)) { deploymetDirss.addAll(deploymetDirssCurrent); } } return deploymetDirss; } /** * Gets {@link Set} of data source paths from configuration * * @return {@link Set}<code><String></code> */ private static Set<String> getDataSourcePaths() { Collection<Configuration> configs = MetaContainer.CONFIGS.values(); Set<String> paths = new HashSet<String>(); Set<String> pathsCurrent; for (Configuration config : configs) { pathsCurrent = config.getDataSourcePath(); if (config.isWatchStatus() && CollectionUtils.valid(pathsCurrent)) { paths.addAll(pathsCurrent); } } return paths; } /** * Checks and gets appropriated {@link WatchFileType} by passed file name * * @param fileName * @return {@link WatchFileType} */ private static WatchFileType checkType(String fileName) { WatchFileType type; File file = new File(fileName); String path = file.getPath(); String filePath = WatchUtils.clearPath(path); path = file.getParent(); String parentPath = WatchUtils.clearPath(path); Set<DeploymentDirectory> apps = getDeployDirectories(); Set<String> dss = getDataSourcePaths(); if (CollectionUtils.valid(apps)) { String deploymantPath; Iterator<DeploymentDirectory> iterator = apps.iterator(); boolean notDeployment = Boolean.TRUE; DeploymentDirectory deployment; while (iterator.hasNext() && notDeployment) { deployment = iterator.next(); deploymantPath = deployment.getPath(); notDeployment = ObjectUtils.notEquals(deploymantPath, parentPath); } if (notDeployment) { type = WatchFileType.NONE; } else { type = WatchFileType.DEPLOYMENT; } } else if (CollectionUtils.valid(dss) && dss.contains(filePath)) { type = WatchFileType.DATA_SOURCE; } else { type = WatchFileType.NONE; } return type; } private static void fillFileList(File[] files, List<File> list) { if (CollectionUtils.valid(files)) { for (File file : files) { list.add(file); } } } /** * Lists all deployed {@link File}s * * @return {@link List}<File> */ public static List<File> listDeployments() { Collection<Configuration> configs = MetaContainer.CONFIGS.values(); Set<DeploymentDirectory> deploymetDirss = new HashSet<DeploymentDirectory>(); Set<DeploymentDirectory> deploymetDirssCurrent; for (Configuration config : configs) { deploymetDirssCurrent = config.getDeploymentPath(); if (CollectionUtils.valid(deploymetDirssCurrent)) { deploymetDirss.addAll(deploymetDirssCurrent); } } File[] files; List<File> list = new ArrayList<File>(); if (CollectionUtils.valid(deploymetDirss)) { String path; DeployFiletr filter = new DeployFiletr(); for (DeploymentDirectory deployment : deploymetDirss) { path = deployment.getPath(); files = new File(path).listFiles(filter); fillFileList(files, list); } } return list; } /** * Lists all data source {@link File}s * * @return {@link List}<File> */ public static List<File> listDataSources() { Collection<Configuration> configs = MetaContainer.CONFIGS.values(); Set<String> paths = new HashSet<String>(); Set<String> pathsCurrent; for (Configuration config : configs) { pathsCurrent = config.getDataSourcePath(); if (CollectionUtils.valid(pathsCurrent)) { paths.addAll(pathsCurrent); } } File file; List<File> list = new ArrayList<File>(); if (CollectionUtils.valid(paths)) { for (String path : paths) { file = new File(path); list.add(file); } } return list; } /** * Deploys application or data source file by passed file name * * @param fileName * @throws IOException */ public static void deployFile(String fileName) throws IOException { WatchFileType type = checkType(fileName); if (type.equals(WatchFileType.DATA_SOURCE)) { FileParsers fileParsers = new FileParsers(); fileParsers.parseStandaloneXml(fileName); } else if (type.equals(WatchFileType.DEPLOYMENT)) { URL url = getAppropriateURL(fileName); deployFile(url); } } /** * Deploys application or data source file by passed {@link URL} instance * * @param url * @throws IOException */ public static void deployFile(URL url) throws IOException { URL[] archives = { url }; MetaContainer.getCreator().scanForBeans(archives); } /** * Removes from deployments application or data source file by passed * {@link URL} instance * * @param url * @throws IOException */ public static void undeployFile(URL url) throws IOException { boolean valid = MetaContainer.undeploy(url); if (valid && RestContainer.hasRest()) { RestProvider.reload(); } } /** * Removes from deployments application or data source file by passed file * name * * @param fileName * @throws IOException */ public static void undeployFile(String fileName) throws IOException { WatchFileType type = checkType(fileName); if (type.equals(WatchFileType.DATA_SOURCE)) { Initializer.undeploy(fileName); } else if (type.equals(WatchFileType.DEPLOYMENT)) { URL url = getAppropriateURL(fileName); undeployFile(url); } } /** * Removes from deployments and deploys again application or data source * file by passed file name * * @param fileName * @throws IOException */ public static void redeployFile(String fileName) throws IOException { undeployFile(fileName); deployFile(fileName); } /** * Handles file change event * * @param dir * @param currentEvent * @throws IOException */ private void handleEvent(Path dir, WatchEvent<Path> currentEvent) throws IOException { if (ObjectUtils.notNull(currentEvent)) { Path prePath = currentEvent.context(); Path path = dir.resolve(prePath); String fileName = path.toString(); int count = currentEvent.count(); Kind<?> kind = currentEvent.kind(); if (kind == StandardWatchEventKinds.ENTRY_MODIFY) { LogUtils.info(LOG, "Modify: %s, count: %s\n", fileName, count); redeployFile(fileName); } else if (kind == StandardWatchEventKinds.ENTRY_DELETE) { LogUtils.info(LOG, "Delete: %s, count: %s\n", fileName, count); undeployFile(fileName); } else if (kind == StandardWatchEventKinds.ENTRY_CREATE) { LogUtils.info(LOG, "Create: %s, count: %s\n", fileName, count); redeployFile(fileName); } } } /** * Runs file watch service * * @param watch * @throws IOException */ private void runService(WatchService watch) throws IOException { Path dir; boolean toRun = true; boolean valid; while (toRun) { try { WatchKey key; key = watch.take(); List<WatchEvent<?>> events = key.pollEvents(); WatchEvent<?> currentEvent = null; WatchEvent<Path> typedCurrentEvent; int times = 0; dir = (Path) key.watchable(); for (WatchEvent<?> event : events) { if (event.kind() == StandardWatchEventKinds.OVERFLOW) { continue; } if (times == 0 || event.count() > currentEvent.count()) { currentEvent = event; } times++; valid = key.reset(); toRun = valid && key.isValid(); if (toRun) { Thread.sleep(SLEEP_TIME); typedCurrentEvent = ObjectUtils.cast(currentEvent); handleEvent(dir, typedCurrentEvent); } } } catch (InterruptedException ex) { throw new IOException(ex); } } } /** * Registers path to watch service * * @param fs * @param path * @param watch * @throws IOException */ private void registerPath(FileSystem fs, String path, WatchService watch) throws IOException { Path deployPath = fs.getPath(path); deployPath.register(watch, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.OVERFLOW, StandardWatchEventKinds.ENTRY_DELETE); runService(watch); } /** * Registers passed {@link File} array to watch service * * @param files * @param fs * @param watch * @throws IOException */ private void registerPaths(File[] files, FileSystem fs, WatchService watch) throws IOException { String path; for (File file : files) { path = file.getPath(); registerPath(fs, path, watch); } } /** * Registers deployments directories to watch service * * @param deploymentDirss * @param fs * @param watch * @throws IOException */ private void registerPaths(Collection<DeploymentDirectory> deploymentDirss, FileSystem fs, WatchService watch) throws IOException { String path; boolean scan; File directory; File[] files; for (DeploymentDirectory deployment : deploymentDirss) { path = deployment.getPath(); scan = deployment.isScan(); if (scan) { directory = new File(path); files = directory.listFiles(); if (CollectionUtils.valid(files)) { registerPaths(files, fs, watch); } } else { registerPath(fs, path, watch); } } } /** * Registers data source path to watch service * * @param paths * @param fs * @param watch * @throws IOException */ private void registerDsPaths(Collection<String> paths, FileSystem fs, WatchService watch) throws IOException { for (String path : paths) { registerPath(fs, path, watch); } } @Override public void run() { try { FileSystem fs = FileSystems.getDefault(); WatchService watch = null; try { watch = fs.newWatchService(); } catch (IOException ex) { LOG.error(ex.getMessage(), ex); throw ex; } if (CollectionUtils.valid(deployments)) { registerPaths(deployments, fs, watch); } if (CollectionUtils.valid(dataSources)) { registerDsPaths(dataSources, fs, watch); } } catch (IOException ex) { LOG.fatal(ex.getMessage(), ex); LOG.fatal("system going to shut down cause of hot deployment"); try { ConnectionContainer.closeConnections(); } catch (IOException iex) { LOG.fatal(iex.getMessage(), iex); } System.exit(-1); } finally { DEPLOY_POOL.shutdown(); } } /** * Starts watch service for application and data source files */ public static void startWatch() { Watcher watcher = new Watcher(); DEPLOY_POOL.submit(watcher); } }
package org.lightmare.deploy.fs; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.Path; import java.nio.file.StandardWatchEventKinds; import java.nio.file.WatchEvent; import java.nio.file.WatchEvent.Kind; import java.nio.file.WatchKey; import java.nio.file.WatchService; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.apache.log4j.Logger; import org.lightmare.cache.ConnectionContainer; import org.lightmare.cache.DeploymentDirectory; import org.lightmare.cache.MetaContainer; import org.lightmare.cache.RestContainer; import org.lightmare.config.Configuration; import org.lightmare.jpa.datasource.FileParsers; import org.lightmare.jpa.datasource.Initializer; import org.lightmare.rest.providers.RestProvider; import org.lightmare.utils.CollectionUtils; import org.lightmare.utils.LogUtils; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.concurrent.ThreadFactoryUtil; import org.lightmare.utils.fs.WatchUtils; /** * Deployment manager, {@link Watcher#deployFile(URL)}, * {@link Watcher#undeployFile(URL)}, {@link Watcher#listDeployments()} and * {@link File} modification event handler for deployments if java version is * 1.7 or above * * @author levan * @since 0.0.45-SNAPSHOT */ public class Watcher implements Runnable { // Name of deployment watch service thread private static final String DEPLOY_THREAD_NAME = "watch_thread"; // Priority of deployment watch service thread private static final int DEPLOY_POOL_PRIORITY = Thread.MAX_PRIORITY - 5; // Sleep time of thread between watch service status scans private static final long SLEEP_TIME = 5500L; // Thread pool for watch service threads private static final ExecutorService DEPLOY_POOL = Executors .newSingleThreadExecutor(new ThreadFactoryUtil(DEPLOY_THREAD_NAME, DEPLOY_POOL_PRIORITY)); //Sets of directories of application deployments private Set<DeploymentDirectory> deployments; private Set<String> dataSources; private static final Logger LOG = Logger.getLogger(Watcher.class); /** * Defines file types for watch service * * @author Levan * @since 0.0.45-SNAPSHOT */ private static enum WatchFileType { DATA_SOURCE, DEPLOYMENT, NONE; } /** * To filter only deployed sub files from directory * * @author levan * @since 0.0.45-SNAPSHOT */ private static class DeployFiletr implements FileFilter { @Override public boolean accept(File file) { boolean accept; try { URL url = file.toURI().toURL(); url = WatchUtils.clearURL(url); accept = MetaContainer.chackDeployment(url); } catch (MalformedURLException ex) { LOG.error(ex.getMessage(), ex); accept = false; } catch (IOException ex) { LOG.error(ex.getMessage(), ex); accept = false; } return accept; } } private Watcher() { deployments = getDeployDirectories(); dataSources = getDataSourcePaths(); } /** * Clears and gets file {@link URL} by file name * * @param fileName * @return {@link URL} * @throws IOException */ private static URL getAppropriateURL(String fileName) throws IOException { File file = new File(fileName); URL url = file.toURI().toURL(); url = WatchUtils.clearURL(url); return url; } /** * Gets {@link Set} of {@link DeploymentDirectory} instances from * configuration * * @return {@link Set}<code><DeploymentDirectory></code> */ private static Set<DeploymentDirectory> getDeployDirectories() { Collection<Configuration> configs = MetaContainer.CONFIGS.values(); Set<DeploymentDirectory> deploymetDirss = new HashSet<DeploymentDirectory>(); Set<DeploymentDirectory> deploymetDirssCurrent; for (Configuration config : configs) { deploymetDirssCurrent = config.getDeploymentPath(); if (config.isWatchStatus() && CollectionUtils.valid(deploymetDirssCurrent)) { deploymetDirss.addAll(deploymetDirssCurrent); } } return deploymetDirss; } /** * Gets {@link Set} of data source paths from configuration * * @return {@link Set}<code><String></code> */ private static Set<String> getDataSourcePaths() { Collection<Configuration> configs = MetaContainer.CONFIGS.values(); Set<String> paths = new HashSet<String>(); Set<String> pathsCurrent; for (Configuration config : configs) { pathsCurrent = config.getDataSourcePath(); if (config.isWatchStatus() && CollectionUtils.valid(pathsCurrent)) { paths.addAll(pathsCurrent); } } return paths; } /** * Checks and gets appropriated {@link WatchFileType} by passed file name * * @param fileName * @return {@link WatchFileType} */ private static WatchFileType checkType(String fileName) { WatchFileType type; File file = new File(fileName); String path = file.getPath(); String filePath = WatchUtils.clearPath(path); path = file.getParent(); String parentPath = WatchUtils.clearPath(path); Set<DeploymentDirectory> apps = getDeployDirectories(); Set<String> dss = getDataSourcePaths(); if (CollectionUtils.valid(apps)) { String deploymantPath; Iterator<DeploymentDirectory> iterator = apps.iterator(); boolean notDeployment = Boolean.TRUE; DeploymentDirectory deployment; while (iterator.hasNext() && notDeployment) { deployment = iterator.next(); deploymantPath = deployment.getPath(); notDeployment = ObjectUtils.notEquals(deploymantPath, parentPath); } if (notDeployment) { type = WatchFileType.NONE; } else { type = WatchFileType.DEPLOYMENT; } } else if (CollectionUtils.valid(dss) && dss.contains(filePath)) { type = WatchFileType.DATA_SOURCE; } else { type = WatchFileType.NONE; } return type; } private static void fillFileList(File[] files, List<File> list) { if (CollectionUtils.valid(files)) { for (File file : files) { list.add(file); } } } /** * Lists all deployed {@link File}s * * @return {@link List}<File> */ public static List<File> listDeployments() { Collection<Configuration> configs = MetaContainer.CONFIGS.values(); Set<DeploymentDirectory> deploymetDirss = new HashSet<DeploymentDirectory>(); Set<DeploymentDirectory> deploymetDirssCurrent; for (Configuration config : configs) { deploymetDirssCurrent = config.getDeploymentPath(); if (CollectionUtils.valid(deploymetDirssCurrent)) { deploymetDirss.addAll(deploymetDirssCurrent); } } File[] files; List<File> list = new ArrayList<File>(); if (CollectionUtils.valid(deploymetDirss)) { String path; DeployFiletr filter = new DeployFiletr(); for (DeploymentDirectory deployment : deploymetDirss) { path = deployment.getPath(); files = new File(path).listFiles(filter); fillFileList(files, list); } } return list; } /** * Lists all data source {@link File}s * * @return {@link List}<File> */ public static List<File> listDataSources() { Collection<Configuration> configs = MetaContainer.CONFIGS.values(); Set<String> paths = new HashSet<String>(); Set<String> pathsCurrent; for (Configuration config : configs) { pathsCurrent = config.getDataSourcePath(); if (CollectionUtils.valid(pathsCurrent)) { paths.addAll(pathsCurrent); } } File file; List<File> list = new ArrayList<File>(); if (CollectionUtils.valid(paths)) { for (String path : paths) { file = new File(path); list.add(file); } } return list; } /** * Deploys application or data source file by passed file name * * @param fileName * @throws IOException */ public static void deployFile(String fileName) throws IOException { WatchFileType type = checkType(fileName); if (type.equals(WatchFileType.DATA_SOURCE)) { FileParsers fileParsers = new FileParsers(); fileParsers.parseStandaloneXml(fileName); } else if (type.equals(WatchFileType.DEPLOYMENT)) { URL url = getAppropriateURL(fileName); deployFile(url); } } /** * Deploys application or data source file by passed {@link URL} instance * * @param url * @throws IOException */ public static void deployFile(URL url) throws IOException { URL[] archives = { url }; MetaContainer.getCreator().scanForBeans(archives); } /** * Removes from deployments application or data source file by passed * {@link URL} instance * * @param url * @throws IOException */ public static void undeployFile(URL url) throws IOException { boolean valid = MetaContainer.undeploy(url); if (valid && RestContainer.hasRest()) { RestProvider.reload(); } } /** * Removes from deployments application or data source file by passed file * name * * @param fileName * @throws IOException */ public static void undeployFile(String fileName) throws IOException { WatchFileType type = checkType(fileName); if (type.equals(WatchFileType.DATA_SOURCE)) { Initializer.undeploy(fileName); } else if (type.equals(WatchFileType.DEPLOYMENT)) { URL url = getAppropriateURL(fileName); undeployFile(url); } } /** * Removes from deployments and deploys again application or data source * file by passed file name * * @param fileName * @throws IOException */ public static void redeployFile(String fileName) throws IOException { undeployFile(fileName); deployFile(fileName); } /** * Handles file change event * * @param dir * @param currentEvent * @throws IOException */ private void handleEvent(Path dir, WatchEvent<Path> currentEvent) throws IOException { if (ObjectUtils.notNull(currentEvent)) { Path prePath = currentEvent.context(); Path path = dir.resolve(prePath); String fileName = path.toString(); int count = currentEvent.count(); Kind<?> kind = currentEvent.kind(); if (kind == StandardWatchEventKinds.ENTRY_MODIFY) { LogUtils.info(LOG, "Modify: %s, count: %s\n", fileName, count); redeployFile(fileName); } else if (kind == StandardWatchEventKinds.ENTRY_DELETE) { LogUtils.info(LOG, "Delete: %s, count: %s\n", fileName, count); undeployFile(fileName); } else if (kind == StandardWatchEventKinds.ENTRY_CREATE) { LogUtils.info(LOG, "Create: %s, count: %s\n", fileName, count); redeployFile(fileName); } } } /** * Runs file watch service * * @param watch * @throws IOException */ private void runService(WatchService watch) throws IOException { Path dir; boolean toRun = true; boolean valid; while (toRun) { try { WatchKey key; key = watch.take(); List<WatchEvent<?>> events = key.pollEvents(); WatchEvent<?> currentEvent = null; WatchEvent<Path> typedCurrentEvent; int times = 0; dir = (Path) key.watchable(); for (WatchEvent<?> event : events) { if (event.kind() == StandardWatchEventKinds.OVERFLOW) { continue; } if (times == 0 || event.count() > currentEvent.count()) { currentEvent = event; } times++; valid = key.reset(); toRun = valid && key.isValid(); if (toRun) { Thread.sleep(SLEEP_TIME); typedCurrentEvent = ObjectUtils.cast(currentEvent); handleEvent(dir, typedCurrentEvent); } } } catch (InterruptedException ex) { throw new IOException(ex); } } } /** * Registers path to watch service * * @param fs * @param path * @param watch * @throws IOException */ private void registerPath(FileSystem fs, String path, WatchService watch) throws IOException { Path deployPath = fs.getPath(path); deployPath.register(watch, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.OVERFLOW, StandardWatchEventKinds.ENTRY_DELETE); runService(watch); } /** * Registers passed {@link File} array to watch service * * @param files * @param fs * @param watch * @throws IOException */ private void registerPaths(File[] files, FileSystem fs, WatchService watch) throws IOException { String path; for (File file : files) { path = file.getPath(); registerPath(fs, path, watch); } } /** * Registers deployments directories to watch service * * @param deploymentDirss * @param fs * @param watch * @throws IOException */ private void registerPaths(Collection<DeploymentDirectory> deploymentDirss, FileSystem fs, WatchService watch) throws IOException { String path; boolean scan; File directory; File[] files; for (DeploymentDirectory deployment : deploymentDirss) { path = deployment.getPath(); scan = deployment.isScan(); if (scan) { directory = new File(path); files = directory.listFiles(); if (CollectionUtils.valid(files)) { registerPaths(files, fs, watch); } } else { registerPath(fs, path, watch); } } } /** * Registers data source path to watch service * * @param paths * @param fs * @param watch * @throws IOException */ private void registerDsPaths(Collection<String> paths, FileSystem fs, WatchService watch) throws IOException { for (String path : paths) { registerPath(fs, path, watch); } } @Override public void run() { try { FileSystem fs = FileSystems.getDefault(); WatchService watch = null; try { watch = fs.newWatchService(); } catch (IOException ex) { LOG.error(ex.getMessage(), ex); throw ex; } if (CollectionUtils.valid(deployments)) { registerPaths(deployments, fs, watch); } if (CollectionUtils.valid(dataSources)) { registerDsPaths(dataSources, fs, watch); } } catch (IOException ex) { LOG.fatal(ex.getMessage(), ex); LOG.fatal("system going to shut down cause of hot deployment"); try { ConnectionContainer.closeConnections(); } catch (IOException iex) { LOG.fatal(iex.getMessage(), iex); } System.exit(-1); } finally { DEPLOY_POOL.shutdown(); } } /** * Starts watch service for application and data source files */ public static void startWatch() { Watcher watcher = new Watcher(); DEPLOY_POOL.submit(watcher); } }
package org.myrobotlab.service; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Image; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; // import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.io.File; import java.io.Serializable; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.TreeMap; import javax.swing.Box; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.SwingUtilities; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import org.myrobotlab.codec.CodecUtils; import org.myrobotlab.framework.Instantiator; import org.myrobotlab.framework.Message; import org.myrobotlab.framework.Service; import org.myrobotlab.framework.ServiceType; import org.myrobotlab.framework.Status; import org.myrobotlab.framework.interfaces.ServiceInterface; import org.myrobotlab.image.Util; import org.myrobotlab.logging.Appender; import org.myrobotlab.logging.Level; import org.myrobotlab.logging.LoggerFactory; import org.myrobotlab.logging.Logging; import org.myrobotlab.logging.LoggingFactory; import org.myrobotlab.swing.ServiceGui; import org.myrobotlab.swing.SwingGuiGui; import org.myrobotlab.swing.Welcome; import org.myrobotlab.swing.widget.AboutDialog; import org.myrobotlab.swing.widget.Console; import org.myrobotlab.swing.widget.DockableTab; import org.myrobotlab.swing.widget.DockableTabPane; import org.slf4j.Logger; import com.mxgraph.model.mxCell; import com.mxgraph.view.mxGraph; public class SwingGui extends Service implements WindowListener, ActionListener, Serializable, DocumentListener { private static final long serialVersionUID = 1L; transient public final static Logger log = LoggerFactory.getLogger(SwingGui.class); String graphXML = ""; boolean fullscreen; public int closeTimeout = 0; // TODO - make MTOD !! from internet // TODO - spawn thread callback / subscribe / promise - for new version transient JFrame frame; transient DockableTabPane tabs;// is loaded = new DockableTabPane(this); transient SwingGuiGui guiServiceGui; transient JPanel tabPanel; Map<String, String> userDefinedServiceTypeColors = new HashMap<String, String>(); /** * the all important 2nd stage routing map after the message gets back to the * gui service the 'rest' of the callback is handled with this data structure * * <pre> * "serviceName.method" --&gt; List<ServiceGui> * Map<{name}.{method}, List<ServiceGui>>> nameMethodCallbackMap * * </pre> * * The same mechanism is employed in mrl.js to handle all call-backs to * ServiceGui.js derived panels. * * FIXME / TODO ? - "Probably" should be Map<{name}, Map<{method}, List * <ServiceGui>>> * */ transient Map<String, List<ServiceGui>> nameMethodCallbackMap; transient JTextField status = new JTextField("status:"); transient JButton statusClear = new JButton("clear"); transient final JTextField search = new JTextField(); boolean active = false; /** * used for "this" reference in anonymous swing utilities calls */ transient SwingGui self; static public void attachJavaConsole() { JFrame j = new JFrame("Java Console"); j.setSize(500, 550); Console c = new Console(); j.add(c.getScrollPane()); j.setVisible(true); c.startLogging(); } static public void console() { attachJavaConsole(); } public static List<Component> getAllComponents(final Container c) { Component[] comps = c.getComponents(); List<Component> compList = new ArrayList<Component>(); for (Component comp : comps) { compList.add(comp); if (comp instanceof Container) compList.addAll(getAllComponents((Container) comp)); } return compList; } public void setColor(String serviceType, String hexColor) { userDefinedServiceTypeColors.put(serviceType, hexColor); } public static Color getColorFromURI(Object uri) { StringBuffer sb = new StringBuffer(String.format("%d", Math.abs(uri.hashCode()))); Color c = new Color(Color.HSBtoRGB(Float.parseFloat("0." + sb.reverse().toString()), 0.8f, 0.7f)); return c; } public Color getColorHash(String uri) { if (userDefinedServiceTypeColors.containsKey(uri)) { // e.g. "#FFCCEE" return Color.decode(userDefinedServiceTypeColors.get(uri)); } StringBuffer sb = new StringBuffer(String.format("%d", Math.abs(uri.hashCode()))); Color c = new Color(Color.HSBtoRGB(Float.parseFloat("0." + sb.reverse().toString()), 0.4f, 0.95f)); return c; } static public void restart() { JFrame frame = new JFrame(); frame.setLocationByPlatform(true); int ret = JOptionPane.showConfirmDialog(frame, "<html>New components have been added,<br>" + " it is necessary to restart in order to use them.</html>", "restart", JOptionPane.YES_NO_OPTION); if (ret == JOptionPane.OK_OPTION) { log.info("restarting"); // Runtime.restart(restartScript); Runtime.getInstance().restart(); // <-- FIXME WRONG need to send // message - may be remote !! } else { log.info("chose not to restart"); return; } } public SwingGui(String n) { super(n); this.self = this; status.setEditable(false); if (tabs == null) { tabs = new DockableTabPane(this); } else { tabs.setStateSaver(this); } log.info("tabs size {}", tabs.size()); for (String title : tabs.keySet()) { DockableTab tab = tabs.get(title); log.info("{} ({},{}) w={} h={}", title, tab.getX(), tab.getY(), tab.getWidth(), tab.getHeight()); } // subscribe to services being added and removed // we want to know about new services registered or released // we create explicit mappings vs just [ // subscribe(Runtime.getRuntimeName(), "released") ] // because we would 'mask' the Runtime's service subscriptions - // intercept and mask them // new service --go--> addTab // remove service --go--> removeTab subscribe(Runtime.getRuntimeName(), "released", getName(), "removeTab"); subscribe(Runtime.getRuntimeName(), "registered", getName(), "addTab"); } public void about() { new AboutDialog(this); } @Override public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); Object o = e.getSource(); if (statusClear == o) { status.setForeground(Color.black); status.setOpaque(false); status.setText("status:"); } if ("unhide all".equals(cmd)) { unhideAll(); } else if ("hide all".equals(cmd)) { hideAll(); } else if (cmd.equals(Appender.FILE)) { Logging logging = LoggingFactory.getInstance(); logging.addAppender(Appender.FILE); } else if (cmd.equals(Appender.NONE)) { Logging logging = LoggingFactory.getInstance(); logging.addAppender(Appender.NONE); } else if ("explode".equals(cmd)) { explode(); } else if ("collapse".equals(cmd)) { collapse(); } else if ("about".equals(cmd)) { new AboutDialog(this); // display(); } else { log.info("unknown command {}", cmd); } } /** * add a service tab to the SwingGui * * @param sw * - name of service to add * * FIXME - full parameter of addTab(final String serviceName, final * String serviceType, final String lable) then overload */ synchronized public void addTab(final ServiceInterface sw) { if (Runtime.isHeadless()) { log.warn("{} SwingGui is in headless environment", getName()); return; } // scroll.addItem(sw.getName()); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { String name = sw.getName(); // change tab color based on name // it is better to add a new interfaced method I think ? String guiClass = String.format("org.myrobotlab.swing.%sGui", sw.getClass().getSimpleName()); log.debug("createTab {} {}", name, guiClass); ServiceGui newGui = null; newGui = (ServiceGui) Instantiator.getNewInstance(guiClass, name, self); if (newGui == null) { log.info("could not construct a {} object - creating generic template", guiClass); newGui = (ServiceGui) Instantiator.getNewInstance("org.myrobotlab.swing.NoGui", name, self); } // serviceGuiMap.put(name, newGui); // subscribeToServiceMethod(name, newGui); - not needed as the key // is "more" unique and called each time a subscribe // is used by a ServiceGui newGui.subscribeGui(); // state and status are both subscribed for the service here // these are messages going to the services of interest subscribe(name, "publishStatus"); subscribe(name, "publishState"); // this is preparing our routing map for callback // so when we receive our callback message we know where to route it subscribeToServiceMethod(String.format("%s.%s", name, CodecUtils.getCallBackName("publishStatus")), newGui); subscribeToServiceMethod(String.format("%s.%s", name, CodecUtils.getCallBackName("publishState")), newGui); // send a publishState to the service // to initialize the ServiceGui - good for remote stuffs send(name, "publishState"); if (getName().equals(name) && guiServiceGui == null) { guiServiceGui = (SwingGuiGui) newGui; guiServiceGui.rebuildGraph(); } // newGui.getDisplay().setBackground(Color.CYAN); tabs.addTab(name, newGui.getDisplay(), Runtime.getService(name).getDescription()); tabs.getTabs().setBackgroundAt(tabs.size() - 1, getColorHash(sw.getClass().getSimpleName())); tabs.get(name).transitDockedColor = tabs.getTabs().getBackgroundAt(tabs.size() - 1); // pack(); FIXED THE EVIL BLACK FROZEN GUI ISSUE !!!! } }); } public JFrame createJFrame(boolean fullscreen) { if (Runtime.isHeadless()) { log.warn("{} SwingGui is in headless environment", getName()); return null; } if (frame != null) { frame.dispose(); } frame = new JFrame(); if (!fullscreen) { frame.addWindowListener(this); frame.setTitle("myrobotlab - " + getName() + " " + Runtime.getVersion().trim()); frame.add(tabPanel); String logoFile = Util.getResourceDir() + File.separator + "mrl_logo_36_36.png"; Toolkit kit = Toolkit.getDefaultToolkit(); Image img = kit.createImage(logoFile); frame.setIconImage(img); // menu frame.setJMenuBar(createMenu()); frame.setVisible(true); frame.pack(); } else { frame.add(tabPanel); frame.setJMenuBar(createMenu()); frame.setExtendedState(JFrame.MAXIMIZED_BOTH); frame.setUndecorated(true); frame.setVisible(true); } return frame; } public void maximize() { frame.setExtendedState(frame.getExtendedState() | JFrame.MAXIMIZED_BOTH); } /* * Build the menu for display. */ public JMenuBar createMenu() { JMenuBar menuBar = new JMenuBar(); JMenu help = new JMenu("help"); JMenuItem about = new JMenuItem("about"); about.addActionListener(this); help.add(about); menuBar.add(search); menuBar.add(Box.createHorizontalGlue()); menuBar.add(help); search.getDocument().addDocumentListener(this); // search.addActionListener(this); return menuBar; } /* * puts unique service.method and ServiceGui into map also in mrl.js * * the format of the key needs to be {name}.method * */ public void subscribeToServiceMethod(String key, ServiceGui sg) { List<ServiceGui> list = null; if (nameMethodCallbackMap.containsKey(key)) { list = nameMethodCallbackMap.get(key); } else { list = new ArrayList<ServiceGui>(); nameMethodCallbackMap.put(key, list); } boolean found = false; for (int i = 0; i < list.size(); ++i) { ServiceGui existingSg = list.get(i); if (existingSg == sg) { found = true; } } if (!found) { list.add(sg); // that was easy ;) } } /* * closes window and puts the panel back into the tabbed pane */ public void dockTab(final String title) { tabs.dockTab(title); } public HashMap<String, mxCell> getCells() { return guiServiceGui.serviceCells; } public String getDstMethodName() { return guiServiceGui.dstMethodName.getText(); } public String getDstServiceName() { return guiServiceGui.dstServiceName.getText(); } public JFrame getFrame() { return frame; } public mxGraph getGraph() { return guiServiceGui.graph; } public String getGraphXML() { return graphXML; } public String getSrcMethodName() { return guiServiceGui.srcMethodName.getText(); } public String getSrcServiceName() { return guiServiceGui.srcServiceName.getText(); } /** * set the main status bar with Status information * * @param inStatus */ public void setStatus(Status inStatus) { if (inStatus.isError()) { status.setOpaque(true); status.setForeground(Color.white); status.setBackground(Color.red); } else if (inStatus.isWarn()) { status.setOpaque(true); status.setForeground(Color.black); status.setBackground(Color.yellow); } else { status.setForeground(Color.black); status.setOpaque(false); } if (inStatus.detail != null && inStatus.detail.length() > 128) { status.setText(inStatus.detail.substring(128)); } else { status.setText(inStatus.detail); } } public void hideAll() { log.info("hideAll"); for (String key : tabs.keySet()) { hideTab(key); } } public void hideTab(final String title) { tabs.hideTab(title); } public void noWorky() { // String img = // SwingGui.class.getResource(Util.getRessourceDir() + "/expert.jpg").toString(); String logon = (String) JOptionPane.showInputDialog(getFrame(), "<html>This will send your myrobotlab.log file<br><p align=center>to our crack team of experts,<br> please type your myrobotlab.org user</p></html>", "No Worky!", JOptionPane.WARNING_MESSAGE, Util.getResourceIcon("expert.jpg"), null, null); if (logon == null || logon.length() == 0) { return; } try { if (Runtime.noWorky(logon).isInfo()) { JOptionPane.showMessageDialog(getFrame(), "log file sent, Thank you", "Sent !", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(getFrame(), "could not send log file :(", "DOH !", JOptionPane.ERROR_MESSAGE); } } catch (Exception e1) { JOptionPane.showMessageDialog(getFrame(), Service.stackToString(e1), "DOH !", JOptionPane.ERROR_MESSAGE); } } public void pack() { if (frame != null) { frame.pack(); frame.repaint(); } } @Override public boolean preProcessHook(Message m) { // FIXME - problem with collisions of this service's methods // and dialog methods ?!?!? // if the method name is == to a method in the SwingGui if (methodSet.contains(m.method)) { // process the message like a regular service return true; } // otherwise send the message to the dialog with the senders name // key is now for callback is {name}.method String key = String.format("%s.%s", m.sender, m.method); List<ServiceGui> sgs = nameMethodCallbackMap.get(key); if (sgs == null) { log.error("attempting to update derived ServiceGui with - callback " + key + " not available in map " + getName()); } else { // FIXME - NORMALIZE - Instantiator or Service - not both !!! // Instantiator.invokeMethod(serviceGuiMap.get(m.sender), m.method, // m.data); for (int i = 0; i < sgs.size(); ++i) { ServiceGui sg = sgs.get(i); invokeOn(sg, m.method, m.data); } } return false; } // FIXME - when a service is 'being' released Runtime should // manage the releasing of the subscriptions !!! synchronized public void removeTab(final ServiceInterface si) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { String name = si.getName(); tabs.removeTab(name); if (guiServiceGui != null) { guiServiceGui.rebuildGraph(); } frame.pack(); frame.repaint(); } }); } public void setArrow(String s) { guiServiceGui.arrow0.setText(s); } public void setDstMethodName(String d) { guiServiceGui.dstMethodName.setText(d); } public void setDstServiceName(String d) { guiServiceGui.dstServiceName.setText(d); } public void setGraphXML(String xml) { graphXML = xml; } public void setPeriod0(String s) { guiServiceGui.period0.setText(s); } public void setPeriod1(String s) { guiServiceGui.period1.setText(s); } public void setSrcMethodName(String d) { guiServiceGui.srcMethodName.setText(d); } public void setSrcServiceName(String d) { guiServiceGui.srcServiceName.setText(d); } @Override synchronized public void startService() { super.startService(); // FIXME - silly - some of these should be initialized in the constructor or // before !! if (!active) { active = true; nameMethodCallbackMap = new HashMap<String, List<ServiceGui>>(); // builds all the service tabs for the first time called when // SwingGui // starts // add welcome table - weird - this needs to be involved in display tabs.addTab("Welcome", new Welcome("welcome", this).getDisplay()); // subscribeToServiceMethod("Welcome", new Welcome("welcome", this, // tabs)); /** * pack() repaint() works on current selected (non-hidden) tab welcome is * the first panel when the UI starts - therefore this controls the * initial size .. however the largest panel typically at this point is * the RuntimeGui - so we set it to the rough size of that panel */ Map<String, ServiceInterface> services = Runtime.getRegistry(); log.info("buildTabPanels service count " + Runtime.getRegistry().size()); TreeMap<String, ServiceInterface> sortedMap = new TreeMap<String, ServiceInterface>(services); Iterator<String> it = sortedMap.keySet().iterator(); tabPanel = new JPanel(new BorderLayout()); tabPanel.add(tabs.getTabs(), BorderLayout.CENTER); JPanel statusPanel = new JPanel(new BorderLayout()); statusPanel.add(status, BorderLayout.CENTER); statusPanel.add(statusClear, BorderLayout.EAST); tabPanel.add(statusPanel, BorderLayout.SOUTH); statusClear.addActionListener(this); status.setOpaque(true); while (it.hasNext()) { String serviceName = it.next(); addTab(Runtime.getService(serviceName)); } // frame.repaint(); not necessary - pack calls repaint // pick out a reference to our own gui List<ServiceGui> sgs = nameMethodCallbackMap.get(getName()); if (sgs != null) { for (int i = 0; i < sgs.size(); ++i) { // another potential bug :( guiServiceGui = (SwingGuiGui) sgs.get(i); } } // create gui parts createJFrame(fullscreen); } } @Override public void stopService() { super.stopService(); if (frame != null) { frame.dispose(); } active = false; } public void explode() { tabs.explode(); } public void collapse() { tabs.collapse(); } public void fullscreen(boolean b) { if (fullscreen != b) { fullscreen = b; createJFrame(b); save(); // request to alter fullscreen } } public void undockTab(final String title) { tabs.undockTab(title); } public void unhideAll() { log.info("unhideAll"); for (String key : tabs.keySet()) { unhideTab(key); } } // must handle docked or undocked & re-entrant for unhidden public void unhideTab(final String title) { tabs.unhideTab(title); } // @Override - only in Java 1.6 @Override public void windowActivated(WindowEvent e) { // log.info("windowActivated"); } // @Override - only in Java 1.6 @Override public void windowClosed(WindowEvent e) { // log.info("windowClosed"); } // @Override - only in Java 1.6 @Override public void windowClosing(WindowEvent e) { // save all necessary serializations /** * WRONG - USE ONLY RUNTIME TO SHUTDOWN !!! save(); Runtime.releaseAll(); * System.exit(1); // the Big Hamm'r */ Runtime.shutdown(closeTimeout); } // @Override - only in Java 1.6 @Override public void windowDeactivated(WindowEvent e) { // log.info("windowDeactivated"); } // @Override - only in Java 1.6 @Override public void windowDeiconified(WindowEvent e) { // log.info("windowDeiconified"); } // @Override - only in Java 1.6 @Override public void windowIconified(WindowEvent e) { // log.info("windowActivated"); } // @Override - only in Java 1.6 @Override public void windowOpened(WindowEvent e) { // log.info("windowOpened"); } public static void main(String[] args) throws ClassNotFoundException, URISyntaxException { LoggingFactory.getInstance().configure(); Logging logging = LoggingFactory.getInstance(); try { logging.setLevel(Level.INFO); // Runtime.start("i01", "InMoov"); // Runtime.start("mac", "Runtime"); // Runtime.start("python", "Python"); // RemoteAdapter remote = (RemoteAdapter)Runtime.start("remote", // "RemoteAdapter"); // remote.setDefaultPrefix("raspi"); // remote.connect("tcp://127.0.0.1:6767"); SwingGui gui = (SwingGui) Runtime.start("gui", "SwingGui"); // Runtime.start("python", "Python"); for (int i = 0; i < 40; ++i) { Runtime.start(String.format("servo%d", i), "Servo"); } } catch (Exception e) { Logging.logError(e); } } public void setActiveTab(String title) { // we need to wait a little after Runtime.start to select an active tab // TODO understand why we need a sleep(1000); this.tabs.getTabs().setSelectedIndex(tabs.getTabs().indexOfTab(title)); } /** * This static method returns all the details of the class without it having * to be constructed. It has description, categories, dependencies, and peer * definitions. * * @return ServiceType - returns all the data * */ static public ServiceType getMetaData() { ServiceType meta = new ServiceType(SwingGui.class.getCanonicalName()); meta.addDescription("Service used to graphically display and control other services"); meta.addCategory("display"); meta.includeServiceInOneJar(true); meta.addDependency("com.fifesoft", "rsyntaxtextarea", "2.0.5.1"); meta.addDependency("com.fifesoft", "autocomplete", "2.0.5.1"); meta.addDependency("com.jidesoft", "jide-oss", "3.6.18"); meta.addDependency("com.mxgraph", "jgraphx", "1.10.4.2"); return meta; } public Component getDisplay() { return (Component) tabs.getTabs(); } public void setDesktop(String name) { tabs.setDesktop(name); } public void resetDesktop(String name) { tabs.resetDesktop(name); } @Override public void changedUpdate(DocumentEvent e) { // log.info("changedUpdate"); } @Override public void insertUpdate(DocumentEvent e) { // log.info("insertUpdate"); Map<String, DockableTab> m = tabs.getDockableTabs(); String type = search.getText().toLowerCase(); for (DockableTab t : m.values()) { if (t.getTitleLabel().getText().toString().toLowerCase().contains(type)) { t.unhideTab(); } else { t.hideTab(); } } } @Override public void removeUpdate(DocumentEvent e) { String type = search.getText(); Map<String, DockableTab> m = tabs.getDockableTabs(); if (type == null || type.length() == 0) { for (DockableTab t : m.values()) { t.unhideTab(); } } } }
package org.nnsoft.shs; import static org.nnsoft.shs.lang.Preconditions.checkArgument; import static java.nio.channels.SelectionKey.OP_ACCEPT; import static java.nio.channels.ServerSocketChannel.open; import static java.nio.channels.spi.SelectorProvider.provider; import static java.util.concurrent.Executors.newFixedThreadPool; import static org.nnsoft.shs.HttpServer.Status.INITIALIZED; import static org.nnsoft.shs.HttpServer.Status.RUNNING; import static org.nnsoft.shs.HttpServer.Status.STOPPED; import static org.slf4j.LoggerFactory.getLogger; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.Iterator; import java.util.concurrent.ExecutorService; import org.nnsoft.shs.dispatcher.RequestDispatcher; import org.slf4j.Logger; /** * A simple {@link HttpServer} implementation. * * This class must NOT be shared across threads, consider it be used inside main(String...) method. */ public final class SimpleHttpServer implements HttpServer, Runnable { private final Logger logger = getLogger( getClass() ); private ExecutorService requestsExecutor; private RequestDispatcher dispatcher; private Selector selector; private Status currentStatus = STOPPED; /** * {@inheritDoc} */ public void init( int port, int threads, RequestDispatcher dispatcher ) throws InitException { checkArgument( port > 0, "Impossible to listening on port %s, it must be a positive number", port ); checkArgument( threads > 0, "Impossible to serve requests with negative or none threads" ); checkArgument( dispatcher != null, "Impossible to serve requests with a null dispatcher" ); if ( currentStatus != STOPPED ) { throw new InitException( "Current server cannot be configured while in %s status.", currentStatus ); } logger.info( "Initializing server using {} threads...", threads ); requestsExecutor = newFixedThreadPool( threads ); logger.info( "Done! Initializing the request dispatcher..." ); this.dispatcher = dispatcher; logger.info( "Done! listening on port {} ...", port ); ServerSocketChannel server; try { server = open(); server.socket().bind( new InetSocketAddress( port ) ); server.configureBlocking( false ); selector = provider().openSelector(); server.register( selector, OP_ACCEPT ); } catch ( IOException e ) { throw new InitException( "Impossible to start server on port %s (with %s threads): %s", port, threads, e.getMessage() ); } logger.info( "Done! Server has been successfully initialized, it can be now started" ); currentStatus = INITIALIZED; } /** * {@inheritDoc} */ public void start() throws RunException { if ( currentStatus != INITIALIZED ) { throw new RunException( "Current server cannot be configured while in %s status, stop then init again before.", currentStatus ); } logger.info( "Server is starting up..." ); requestsExecutor.submit( this ); logger.info( "Server successfully started! Waiting for new requests..." ); currentStatus = RUNNING; } /** * {@inheritDoc} */ public void run() { while ( currentStatus == RUNNING ) { // Wait for an event one of the registered channels try { selector.select(); } catch ( IOException ioe ) { logger.error( "Something wrong happened while listening for connections: {}", ioe.getMessage() ); try { stop(); } catch ( ShutdownException se ) { logger.error( "Server not correctly shutdow, see nested exceptions", se ); } throw new RuntimeException( new RunException( "A fatal error occurred while waiting for clients: %s", ioe.getMessage() ) ); } // Iterate over the set of keys for which events are available Iterator<SelectionKey> selectedKeys = selector.selectedKeys().iterator(); while ( selectedKeys.hasNext() ) { SelectionKey key = selectedKeys.next(); selectedKeys.remove(); if ( !key.isValid() ) { continue; } // Check what event is available and deal with it if ( key.isAcceptable() ) { ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel(); try { SocketChannel socketChannel = serverSocketChannel.accept(); Socket socket = socketChannel.socket(); requestsExecutor.submit( new SocketRunnable( dispatcher, socket ) ); } catch ( IOException e ) { logger.warn( "Impossible to accept client request: {}", e.getMessage() ); } } } } } /** * {@inheritDoc} */ public void stop() throws ShutdownException { if ( currentStatus != RUNNING ) { throw new ShutdownException( "Current server cannot be stopped while in %s status.", currentStatus ); } logger.info( "Server is shutting down..." ); try { if ( selector != null && selector.isOpen() ) { selector.close(); } } catch ( IOException e ) { throw new ShutdownException( "An error occurred while shutting down the server: %s", e.getMessage() ); } finally { requestsExecutor.shutdown(); logger.info( "Server is now stopped. Bye!" ); currentStatus = STOPPED; } } /** * {@inheritDoc} */ public Status getStatus() { return currentStatus; } }
package org.olap.server.processor; import org.olap.server.driver.ServerCellSet; import org.olap.server.driver.ServerConnection; import org.olap.server.driver.ServerOlapStatement; import org.olap.server.driver.metadata.ServerCatalog; import org.olap.server.driver.metadata.ServerSchema; import org.olap.server.driver.util.ParseUtils; import org.olap.server.processor.sql.SqlConnector; import org.olap.server.processor.sql.SqlQuery; import org.olap4j.CellSet; import org.olap4j.OlapException; import org.olap4j.mdx.AxisNode; import org.olap4j.mdx.IdentifierNode; import org.olap4j.mdx.SelectNode; import org.olap4j.metadata.Cube; public class Query { private ServerOlapStatement serverOlapStatement; private ServerConnection serverConnection; private SelectNode selectNode; private ServerSchema schema; private ServerCatalog catalog; private Cube cube; public Query(ServerOlapStatement serverOlapStatement, SelectNode node) throws OlapException { this.serverOlapStatement = serverOlapStatement; this.serverConnection = serverOlapStatement.getServerConnection(); this.schema = (ServerSchema) serverConnection.getOlapSchema(); this.catalog = (ServerCatalog) serverConnection.getOlapCatalog(); this.selectNode = ParseUtils.normalize(serverOlapStatement.getMdxParser(), node); String cubeName = ParseUtils.identifierNames((IdentifierNode)this.selectNode.getFrom())[0]; this.cube = schema.getCubes().get(cubeName); if(this.cube==null) throw new OlapException("Cube "+cubeName+" not found in schema "+schema.getName()); } public CellSet execute() throws OlapException { ServerCellSet cellSet = new ServerCellSet(serverOlapStatement, cube); fetchAxisMetaData(cellSet); SqlQuery query = new SqlQuery(catalog.getPhysicalSchema(), cellSet); query.generateQuery(); SqlConnector exec = SqlConnector.getConnector(catalog); exec.execute(query.toString(), query); return cellSet; } protected void fetchAxisMetaData(ServerCellSet cellSet) throws OlapException { for(AxisNode axisNode : selectNode.getAxisList()){ cellSet.setAxis( new ResultAxis(cellSet, axisNode ) ); } cellSet.setAxis( new ResultAxis(cellSet, selectNode.getFilterAxis()) ); } }
package org.projectblueshift.api; import java.net.InetSocketAddress; public interface Server { public InetSocketAddress getSocketAddress(); public short getPort(); public void shutdown(); public void init(); }
package org.testng.internal; import org.testng.IClass; import org.testng.IMethodSelector; import org.testng.IObjectFactory; import org.testng.TestNGException; import org.testng.TestRunner; import org.testng.annotations.IAnnotation; import org.testng.annotations.IFactoryAnnotation; import org.testng.annotations.IParametersAnnotation; import org.testng.internal.annotations.IAnnotationFinder; import org.testng.internal.annotations.Sets; import org.testng.junit.IJUnitTestRunner; import org.testng.xml.XmlTest; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Vector; /** * Utility class for different class manipulations. */ public final class ClassHelper { private static final String JUNIT_TESTRUNNER= "org.testng.junit.JUnitTestRunner"; /** The additional class loaders to find classes in. */ private static final List<ClassLoader> m_classLoaders = new Vector<ClassLoader>(); /** Add a class loader to the searchable loaders. */ public static void addClassLoader(final ClassLoader loader) { m_classLoaders.add(loader); } /** Hide constructor. */ private ClassHelper() { // Hide Constructor } public static <T> T newInstance(Class<T> clazz) { try { T instance = clazz.newInstance(); return instance; } catch(IllegalAccessException iae) { throw new TestNGException("Class " + clazz.getName() + " does not have a no-args constructor", iae); } catch(InstantiationException ie) { throw new TestNGException("Cannot instantiate class " + clazz.getName(), ie); } catch(ExceptionInInitializerError eiierr) { throw new TestNGException("An exception occurred in static initialization of class " + clazz.getName(), eiierr); } catch(SecurityException se) { throw new TestNGException(se); } } /** * Tries to load the specified class using the context ClassLoader or if none, * than from the default ClassLoader. This method differs from the standard * class loading methods in that it does not throw an exception if the class * is not found but returns null instead. * * @param className the class name to be loaded. * * @return the class or null if the class is not found. */ public static Class<?> forName(final String className) { Vector<ClassLoader> allClassLoaders = new Vector<ClassLoader>(); ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); if (contextClassLoader != null) { allClassLoaders.add(contextClassLoader); } if (m_classLoaders != null) { allClassLoaders.addAll(m_classLoaders); } int count = 0; for (ClassLoader classLoader : allClassLoaders) { ++count; if (null == classLoader) { continue; } try { return classLoader.loadClass(className); } catch(ClassNotFoundException ex) { // With additional class loaders, it is legitimate to ignore ClassNotFoundException if (null == m_classLoaders || m_classLoaders.size() == 0) { logClassNotFoundError(className, ex); } } } try { return Class.forName(className); } catch(ClassNotFoundException cnfe) { logClassNotFoundError(className, cnfe); return null; } } private static void logClassNotFoundError(String className, Exception ex) { Utils.log("ClassHelper", 2, "Could not instantiate " + className + " : Class doesn't exist (" + ex.getMessage() + ")"); } /** * For the given class, returns the method annotated with &#64;Factory or null * if none is found. This method does not search up the superclass hierarchy. * If more than one method is @Factory annotated, a TestNGException is thrown. * @param cls The class to search for the @Factory annotation. * @param finder The finder (JDK 1.4 or JDK 5.0+) use to search for the annotation. * * @return the @Factory <CODE>method</CODE> or null * * FIXME: @Factory method must be public! */ public static Method findDeclaredFactoryMethod(Class<?> cls, IAnnotationFinder finder) { Method result = null; for (Method method : cls.getMethods()) { IAnnotation f = finder.findAnnotation(method, IFactoryAnnotation.class); if (null != f) { if (null != result) { throw new TestNGException(cls.getName() + ": only one @Factory method allowed"); } result = method; } } // If we didn't find anything, look for nested classes // if (null == result) { // Class[] subClasses = cls.getClasses(); // for (Class subClass : subClasses) { // result = findFactoryMethod(subClass, finder); // if (null != result) { // break; // Found the method, verify that it returns an array of objects // TBD return result; } /** * Extract all callable methods of a class and all its super (keeping in mind * the Java access rules). * * @param clazz * @return */ public static Set<Method> getAvailableMethods(Class<?> clazz) { Set<Method> methods = Sets.newHashSet(); methods.addAll(Arrays.asList(clazz.getDeclaredMethods())); Class<?> parent = clazz.getSuperclass(); while (Object.class != parent) { methods.addAll(extractMethods(clazz, parent, methods)); parent = parent.getSuperclass(); } return methods; } /** * @param runner * @return */ public static IJUnitTestRunner createTestRunner(TestRunner runner) { try { IJUnitTestRunner tr= (IJUnitTestRunner) ClassHelper.forName(JUNIT_TESTRUNNER).newInstance(); tr.setTestResultNotifier(runner); return tr; } catch(Exception ex) { throw new TestNGException("Cannot create JUnit runner " + JUNIT_TESTRUNNER, ex); } } private static Set<Method> extractMethods(Class<?> childClass, Class<?> clazz, Set<Method> collected) { Set<Method> methods = Sets.newHashSet(); Method[] declaredMethods = clazz.getDeclaredMethods(); Package childPackage = childClass.getPackage(); Package classPackage = clazz.getPackage(); boolean isSamePackage = false; if ((null == childPackage) && (null == classPackage)) { isSamePackage = true; } if ((null != childPackage) && (null != classPackage)) { isSamePackage = childPackage.getName().equals(classPackage.getName()); } for (Method method : declaredMethods) { int methodModifiers = method.getModifiers(); if ((Modifier.isPublic(methodModifiers) || Modifier.isProtected(methodModifiers)) || (isSamePackage && !Modifier.isPrivate(methodModifiers))) { if (!isOverridden(method, collected) && !Modifier.isAbstract(methodModifiers)) { methods.add(method); } } } return methods; } private static boolean isOverridden(Method method, Set<Method> collectedMethods) { Class<?> methodClass = method.getDeclaringClass(); Class<?>[] methodParams = method.getParameterTypes(); for (Method m: collectedMethods) { Class<?>[] paramTypes = m.getParameterTypes(); if (method.getName().equals(m.getName()) && methodClass.isAssignableFrom(m.getDeclaringClass()) && methodParams.length == paramTypes.length) { boolean sameParameters = true; for (int i= 0; i < methodParams.length; i++) { if (!methodParams[i].equals(paramTypes[i])) { sameParameters = false; break; } } if (sameParameters) { return true; } } } return false; } public static IMethodSelector createSelector(org.testng.xml.XmlMethodSelector selector) { try { Class<?> cls = Class.forName(selector.getClassName()); return (IMethodSelector) cls.newInstance(); } catch(Exception ex) { throw new TestNGException("Couldn't find method selector : " + selector.getClassName(), ex); } } /** * Create an instance for the given class. */ public static Object createInstance(Class<?> declaringClass, Map<Class, IClass> classes, XmlTest xmlTest, IAnnotationFinder finder, IObjectFactory objectFactory) { Object result; try { // Any annotated constructor? Constructor<?> constructor = findAnnotatedConstructor(finder, declaringClass); if (null != constructor) { IParametersAnnotation annotation = (IParametersAnnotation) finder.findAnnotation(constructor, IParametersAnnotation.class); String[] parameterNames = annotation.getValue(); Object[] parameters = Parameters.createInstantiationParameters(constructor, "@Parameters", finder, parameterNames, xmlTest.getParameters(), xmlTest.getSuite()); result = objectFactory.newInstance(constructor, parameters); } // No, just try to instantiate the parameterless constructor (or the one // with a String) else { // If this class is a (non-static) nested class, the constructor contains a hidden // parameter of the type of the enclosing class Class<?>[] parameterTypes = new Class[0]; Object[] parameters = new Object[0]; Class<?> ec = getEnclosingClass(declaringClass); boolean isStatic = 0 != (declaringClass.getModifiers() & Modifier.STATIC); // Only add the extra parameter if the nested class is not static if ((null != ec) && !isStatic) { parameterTypes = new Class[] { ec }; // Create an instance of the enclosing class so we can instantiate // the nested class (actually, we reuse the existing instance). IClass enclosingIClass = classes.get(ec); Object[] enclosingInstances; if (null != enclosingIClass) { enclosingInstances = enclosingIClass.getInstances(false); if ((null == enclosingInstances) || (enclosingInstances.length == 0)) { Object o = objectFactory.newInstance(ec.getConstructor(parameterTypes)); enclosingIClass.addInstance(o); enclosingInstances = new Object[] { o }; } } else { enclosingInstances = new Object[] { ec.newInstance() }; } Object enclosingClassInstance = enclosingInstances[0]; // Utils.createInstance(ec, classes, xmlTest, finder); parameters = new Object[] { enclosingClassInstance }; } // isStatic Constructor<?> ct = null; try { ct = declaringClass.getDeclaredConstructor(parameterTypes); } catch (NoSuchMethodException ex) { // Couldn't find a parameterless constructor, we'll pass a null constructor to the factory // and hope it can deal with it } result = objectFactory.newInstance(ct, parameters); } } catch (TestNGException ex) { // We need to pass this along throw ex; } catch (NoSuchMethodException ex) { result = ClassHelper.tryOtherConstructor(declaringClass); } catch (Throwable cause) { // Something else went wrong when running the constructor throw new TestNGException("An error occurred while instantiating class " + declaringClass.getName() + ": " + cause.getMessage(), cause); } if (null == result) { //result should not be null throw new TestNGException("An error occurred while instantiating class " + declaringClass.getName() + ". Check to make sure it can be accessed/instantiated."); } return result; } /** * Class.getEnclosingClass() only exists on JDK5, so reimplementing it * here. */ private static Class<?> getEnclosingClass(Class<?> declaringClass) { Class<?> result = null; String className = declaringClass.getName(); int index = className.indexOf("$"); if (index != -1) { String ecn = className.substring(0, index); try { result = Class.forName(ecn); } catch (ClassNotFoundException e) { e.printStackTrace(); } } return result; } /** * Find the best constructor given the parameters found on the annotation */ private static Constructor<?> findAnnotatedConstructor(IAnnotationFinder finder, Class<?> declaringClass) { Constructor<?>[] constructors = declaringClass.getDeclaredConstructors(); for (Constructor<?> result : constructors) { IParametersAnnotation annotation = (IParametersAnnotation) finder.findAnnotation(result, IParametersAnnotation.class); if (null != annotation) { String[] parameters = annotation.getValue(); Class<?>[] parameterTypes = result.getParameterTypes(); if (parameters.length != parameterTypes.length) { throw new TestNGException("Parameter count mismatch: " + result + "\naccepts " + parameterTypes.length + " parameters but the @Test annotation declares " + parameters.length); } else { return result; } } } return null; } public static <T> T tryOtherConstructor(Class<T> declaringClass) { T result; try { // Special case for inner classes if (declaringClass.getModifiers() == 0) { return null; } Constructor<T> ctor = declaringClass.getConstructor(new Class[] { String.class }); result = ctor.newInstance(new Object[] { "Default test name" }); } catch (Exception e) { String message = e.getMessage(); if ((message == null) && (e.getCause() != null)) { message = e.getCause().getMessage(); } String error = "Could not create an instance of class " + declaringClass + ((message != null) ? (": " + message) : "") + ".\nPlease make sure it has a constructor that accepts either a String or no parameter."; throw new TestNGException(error); } return result; } /** * When given a file name to form a class name, the file name is parsed and divided * into segments. For example, "c:/java/classes/com/foo/A.class" would be divided * into 6 segments {"C:" "java", "classes", "com", "foo", "A"}. The first segment * actually making up the class name is [3]. This value is saved in m_lastGoodRootIndex * so that when we parse the next file name, we will try 3 right away. If 3 fails we * will take the long approach. This is just a optimization cache value. */ private static int m_lastGoodRootIndex = -1; /** * Returns the Class object corresponding to the given name. The name may be * of the following form: * <ul> * <li>A class name: "org.testng.TestNG"</li> * <li>A class file name: "/testng/src/org/testng/TestNG.class"</li> * <li>A class source name: "d:\testng\src\org\testng\TestNG.java"</li> * </ul> * * @param file * the class name. * @return the class corresponding to the name specified. */ public static Class<?> fileToClass(String file) { Class<?> result = null; if(!file.endsWith(".class") && !file.endsWith(".java")) { // Doesn't end in .java or .class, assume it's a class name result = ClassHelper.forName(file); if (null == result) { throw new TestNGException("Cannot load class from file: " + file); } return result; } int classIndex = file.lastIndexOf(".class"); if (-1 == classIndex) { classIndex = file.lastIndexOf(".java"); // if(-1 == classIndex) { // result = ClassHelper.forName(file); // if (null == result) { // throw new TestNGException("Cannot load class from file: " + file); // return result; } // Transforms the file name into a class name. // Remove the ".class" or ".java" extension. String shortFileName = file.substring(0, classIndex); // Split file name into segments. For example "c:/java/classes/com/foo/A" // becomes {"c:", "java", "classes", "com", "foo", "A"} String[] segments = shortFileName.split("[/\\\\]", -1); // Check if the last good root index works for this one. For example, if the previous // name was "c:/java/classes/com/foo/A.class" then m_lastGoodRootIndex is 3 and we // try to make a class name ignoring the first m_lastGoodRootIndex segments (3). This // will succeed rapidly if the path is the same as the one from the previous name. if (-1 != m_lastGoodRootIndex) { // TODO use a SringBuffer here String className = segments[m_lastGoodRootIndex]; for (int i = m_lastGoodRootIndex + 1; i < segments.length; i++) { className += "." + segments[i]; } result = ClassHelper.forName(className); if (null != result) { return result; } } // We haven't found a good root yet, start by resolving the class from the end segment // and work our way up. For example, if we start with "c:/java/classes/com/foo/A" // we'll start by resolving "A", then "foo.A", then "com.foo.A" until something // resolves. When it does, we remember the path we are at as "lastGoodRoodIndex". // TODO CQ use a StringBuffer here String className = null; for (int i = segments.length - 1; i >= 0; i if (null == className) { className = segments[i]; } else { className = segments[i] + "." + className; } result = ClassHelper.forName(className); if (null != result) { m_lastGoodRootIndex = i; break; } } if (null == result) { throw new TestNGException("Cannot load class from file: " + file); } return result; } }
package potaufeu; import java.io.*; import java.nio.file.*; import java.nio.file.attribute.*; import java.util.*; import java.util.function.*; public final class FileAttributeFormatter { private static final Log log = Log.logger(FileAttributeFormatter.class); private static volatile boolean unixViewNotAvailableChecked = false; private final Path path; private final BasicFileAttributes attr; private Function<Long, String> fileSizeFormatter; private Function<FileTime, String> fileTimeFormatter; public FileAttributeFormatter(Path path) { this(path, readBasicAttributes(path)); } public FileAttributeFormatter(Path path, BasicFileAttributes attributes) { this.path = path; this.attr = attributes; this.fileSizeFormatter = x -> String.valueOf(x); this.fileTimeFormatter = x -> String.valueOf(x); } public Path getPath() { return path; } public BasicFileAttributes getAttribute() { return attr; } public Function<Long, String> getFileSizeFormatter() { return fileSizeFormatter; } public void setFileSizeFormatter(Function<Long, String> fileSizeFormatter) { this.fileSizeFormatter = fileSizeFormatter; } public Function<FileTime, String> getFileTimeFormatter() { return fileTimeFormatter; } public void setFileTimeFormatter(Function<FileTime, String> fileTimeFormatter) { this.fileTimeFormatter = fileTimeFormatter; } public String name() { return name(path); } public static String name(File file) { return file.getName(); } public static String name(Path path) { return path.getFileName().toString(); } public String formattedSize() { return fileSizeFormatter.apply(attr.size()); } public long size() { return size(path); } public static long size(File file) { return file.length(); } public static long size(Path path) { return readBasicAttributes(path).size(); } public String formattedCtime() { return fileTimeFormatter.apply(attr.creationTime()); } public static long ctime(File file) { return ctime(file.toPath()); } public static long ctime(Path path) { return readBasicAttributes(path).creationTime().toMillis(); } public String formattedMtime() { return fileTimeFormatter.apply(attr.lastModifiedTime()); } public static long mtime(File file) { return file.lastModified(); } public static long mtime(Path path) { return mtime(path.toFile()); } public String formattedAtime() { return fileTimeFormatter.apply(attr.lastAccessTime()); } public static long atime(File file) { return atime(file.toPath()); } public static long atime(Path path) { return readBasicAttributes(path).lastAccessTime().toMillis(); } public char entryType() { return getEntryType(attr); } public static char entryType(Path path) { return getEntryType(readBasicAttributes(path)); } public static char getEntryType(BasicFileAttributes attr) { if (attr.isDirectory()) return 'd'; if (attr.isSymbolicLink()) return 'l'; if (attr.isRegularFile()) return '-'; if (attr.isOther()) return ':'; return '?'; } public String formattedPermissions() { return permissions().map(PosixFilePermissions::toString).orElse("rwx } public Optional<Set<PosixFilePermission>> permissions() { return permissions(attr); } public static Optional<Set<PosixFilePermission>> permissions(Path path) { return permissions(path); } public static Optional<Set<PosixFilePermission>> permissions(BasicFileAttributes attr) { if (attr instanceof PosixFileAttributes) { PosixFileAttributes posixAttr = (PosixFileAttributes) attr; return Optional.of(posixAttr.permissions()); } return Optional.empty(); } public char aclSign() { return aclSign(path); } public static char aclSign(Path path) { AclFileAttributeView view = Files.getFileAttributeView(path, AclFileAttributeView.class); if (view != null) try { List<AclEntry> x = view.getAcl(); if (!x.isEmpty()) return '+'; } catch (IOException e) { log.warn(() -> "", e); } return ' '; } public String nLink() { // XXX bad performance ? if (!unixViewNotAvailableChecked) try { return String.valueOf(Files.getAttribute(path, "unix:nlink")); } catch (Exception e) { log.debug(() -> String.format("[%s] at accessing unix:nlink", e)); unixViewNotAvailableChecked = true; } return ""; } public String ownerString() { return ownerString(path, attr); } public static String ownerString(Path path, BasicFileAttributes attr) { if (attr instanceof PosixFileAttributes) { PosixFileAttributes posixAttr = (PosixFileAttributes) attr; return String.format("%-8s %-8s", posixAttr.owner(), posixAttr.group()); } try { UserPrincipal principal = Files.getOwner(path); if (principal != null) return principal.getName(); } catch (IOException e) { log.warn(() -> "in ownerString", e); } return "??? ??? "; // 17 (8+1+8) } public static <T extends Path> Function<T, Long> toLongLambda(String attrName) { switch (attrName) { case "size": return x -> size(x); case "ctime": return x -> ctime(x); case "mtime": return x -> mtime(x); case "atime": return x -> atime(x); default: throw new IllegalArgumentException("bad attrName: " + attrName); } } static BasicFileAttributes readBasicAttributes(Path path) { try { try { return Files.readAttributes(path, PosixFileAttributes.class); } catch (UnsupportedOperationException e) { // ignore } return Files.readAttributes(path, BasicFileAttributes.class); } catch (IOException e) { throw new UncheckedIOException(e); } } }
package refinedstorage.tile; import io.netty.buffer.ByteBuf; import net.minecraft.block.Block; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; import refinedstorage.RefinedStorageUtils; import refinedstorage.tile.config.IRedstoneModeConfig; import refinedstorage.tile.config.RedstoneMode; import refinedstorage.tile.controller.ControllerSearcher; import refinedstorage.tile.controller.TileController; import java.util.HashSet; import java.util.Set; public abstract class TileMachine extends TileBase implements ISynchronizedContainer, IRedstoneModeConfig { public static final String NBT_CONNECTED = "Connected"; protected boolean connected; protected boolean wasConnected; protected RedstoneMode redstoneMode = RedstoneMode.IGNORE; protected TileController controller; private Block block; private Set<String> visited = new HashSet<String>(); public TileController getController() { return controller; } public void searchController(World world) { visited.clear(); TileController newController = ControllerSearcher.search(world, pos, visited); if (controller == null) { if (newController != null) { onConnected(world, newController); } } else { if (newController == null) { onDisconnected(world); } } } @Override public void update() { if (!worldObj.isRemote) { if (ticks == 0) { block = worldObj.getBlockState(pos).getBlock(); searchController(worldObj); } if (wasConnected != isActive() && canSendConnectivityData()) { wasConnected = isActive(); RefinedStorageUtils.updateBlock(worldObj, pos); } if (isActive()) { updateMachine(); } } super.update(); } public boolean canSendConnectivityData() { return true; } public boolean canUpdate() { return redstoneMode.isEnabled(worldObj, pos); } public boolean isActive() { return connected && canUpdate(); } public void onConnected(World world, TileController controller) { if (tryConnect(controller) && block != null) { world.notifyNeighborsOfStateChange(pos, block); } } private boolean tryConnect(TileController controller) { if (!controller.canRun()) { return false; } this.controller = controller; this.connected = true; controller.addMachine(this); return true; } public void onDisconnected(World world) { this.connected = false; if (this.controller != null) { this.controller.removeMachine(this); this.controller = null; } world.notifyNeighborsOfStateChange(pos, block); } public boolean isConnected() { return connected; } public void setConnected(boolean connected) { this.connected = connected; } @Override public RedstoneMode getRedstoneMode() { return redstoneMode; } @Override public void setRedstoneMode(RedstoneMode mode) { markDirty(); this.redstoneMode = mode; } @Override public void readContainerData(ByteBuf buf) { redstoneMode = RedstoneMode.getById(buf.readInt()); } @Override public void writeContainerData(ByteBuf buf) { buf.writeInt(redstoneMode.id); } @Override public void read(NBTTagCompound nbt) { super.read(nbt); if (nbt.hasKey(RedstoneMode.NBT)) { redstoneMode = RedstoneMode.getById(nbt.getInteger(RedstoneMode.NBT)); } } @Override public NBTTagCompound write(NBTTagCompound tag) { super.write(tag); tag.setInteger(RedstoneMode.NBT, redstoneMode.id); return tag; } public NBTTagCompound writeUpdate(NBTTagCompound tag) { super.writeUpdate(tag); tag.setBoolean(NBT_CONNECTED, isActive()); return tag; } public void readUpdate(NBTTagCompound tag) { super.readUpdate(tag); connected = tag.getBoolean(NBT_CONNECTED); } public abstract int getEnergyUsage(); public abstract void updateMachine(); @Override public boolean equals(Object other) { if (other == this) { return true; } if (!(other instanceof TileMachine)) { return false; } return ((TileMachine) other).getPos().equals(pos); } @Override public int hashCode() { return pos.hashCode(); } }
package se.kth.bbc.yarn; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.Serializable; import java.nio.charset.Charset; import java.nio.file.Files; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.PostConstruct; import javax.faces.bean.ManagedBean; import javax.faces.bean.ManagedProperty; import javax.faces.bean.ViewScoped; import org.apache.flink.client.program.ProgramInvocationException; import org.apache.hadoop.yarn.exceptions.YarnException; import org.primefaces.event.FileUploadEvent; import org.primefaces.model.UploadedFile; import se.kth.bbc.flink.FlinkRunnerSimple; import se.kth.bbc.lims.Constants; import se.kth.bbc.lims.MessagesController; import se.kth.bbc.study.StudyMB; /** * * @author stig */ @ManagedBean @ViewScoped public class FlinkController implements Serializable { private static final Logger logger = Logger.getLogger(FlinkController.class.getName()); private final JobController jc = new JobController(); private static final String KEY_JOB_JAR = "jobJarPath"; @ManagedProperty(value = "#{studyManagedBean}") private transient StudyMB study; private String jobjarmain; private String jobArgs; private int paral = 1; private int port; private String host; private static ExecutorService exc = Executors.newCachedThreadPool(); @PostConstruct public void init() { try { jc.setBasePath(study.getStudyName(), study.getUsername()); } catch (IOException c) { logger.log(Level.SEVERE, "Failed to create directory structure.", c); MessagesController.addErrorMessage("Failed to initialize Yarn controller. Running Yarn jobs will not work."); } } public void handleJobJarUpload(FileUploadEvent event) { try { jc.handleFileUpload(KEY_JOB_JAR, event); } catch (IllegalStateException e) { try { jc.setBasePath(study.getStudyName(), study.getUsername()); jc.handleFileUpload(KEY_JOB_JAR, event); } catch (IOException c) { logger.log(Level.SEVERE, "Failed to create directory structure.", c); MessagesController.addErrorMessage("Failed to initialize Yarn controller. Running Yarn jobs will not work."); } } } public void setJobJarMain(String s) { this.jobjarmain = s.trim(); } public String getJobJarMain() { return jobjarmain; } public String getJobArgs() { return jobArgs; } public void setJobArgs(String jobArgs) { this.jobArgs = jobArgs.trim(); } public void setStudy(StudyMB study) { this.study = study; } public void setParal(String s) { try { paral = Integer.valueOf(s.trim()); } catch (NumberFormatException e) { paral = 2; } } public String getParal() { return "" + paral; } public void extraFileUploads(FileUploadEvent event) { UploadedFile file = event.getFile(); String key = file.getFileName(); try { jc.handleFileUpload(key, event); } catch (IllegalStateException e) { try { jc.setBasePath(study.getStudyName(), study.getUsername()); jc.handleFileUpload(key, event); } catch (IOException c) { logger.log(Level.SEVERE, "Failed to create directory structure.", c); MessagesController.addErrorMessage("Failed to initialize Flink controller. Running Yarn jobs will not work."); } } } public void runJar() { Runnable c = new Runnable() { @Override public void run() { getAddressPort(Constants.FLINK_CONF_DIR); FlinkRunnerSimple.FlinkBuilder b = new FlinkRunnerSimple.FlinkBuilder(new File(jc.getFilePath(KEY_JOB_JAR)), jobjarmain, host, port); b.setParallelism(paral); b.setJobArgs(parseArgs(jobArgs).split(" ")); FlinkRunnerSimple p = b.build(); try { p.runJob(); } catch (IOException | ProgramInvocationException | YarnException ex) { logger.log(Level.SEVERE, null, ex); MessagesController.addErrorMessage("Failed to run job."); } } }; exc.execute(c); } private String parseArgs(String s) { for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '$') { i++; if (i >= s.length()) { break; } if (s.charAt(i) == '{') { int end = s.indexOf('}', i); if (end != -1) { String pre = s.substring(0, i - 1); String post = s.substring(end + 1); String key = s.substring(i + 1, end); String value = jc.getFilePath(key); if (value != null) { s = pre + value + post; } else { s = pre + post; } } } } } return s; } public String getJobJarName() { String path = jc.getFilePath(KEY_JOB_JAR); if (path == null) { return null; } int lastslash = path.lastIndexOf("/"); return path.substring(lastslash); } public class StringPair { private String one; private String two; public String getOne() { return one; } public void setOne(String one) { this.one = one; } public String getTwo() { return two; } public void setTwo(String two) { this.two = two; } public StringPair(String one, String two) { this.one = one; this.two = two; } } public List<StringPair> getUploadedFiles() { List<StringPair> pairs = new ArrayList<>(); for (String a : jc.getFiles().keySet()) { String path = jc.getFilePath(a); int lastslash = path.lastIndexOf("/"); String flnm = path.substring(lastslash); pairs.add(new StringPair(a, flnm)); } return pairs; } private void getAddressPort(String location) { File f = new File(location); Charset charset = Charset.defaultCharset(); try (BufferedReader reader = Files.newBufferedReader(f.toPath(), charset)) { String line = null; while ((line = reader.readLine()) != null) { if (line.contains("jobManager")) { int index = line.indexOf("="); String val = line.substring(index + 1); int sep = line.indexOf("\\:"); host = line.substring(index + 1, sep); port = Integer.valueOf(line.substring(sep + 2)); } } } catch (IOException x) { System.err.format("IOException: %s%n", x); } } }
package seedu.unburden.model; import javafx.collections.ObservableList; import seedu.unburden.model.tag.Tag; import seedu.unburden.commons.exceptions.*; import seedu.unburden.model.tag.UniqueTagList; import seedu.unburden.model.task.ReadOnlyTask; import seedu.unburden.model.task.Task; import seedu.unburden.model.task.UniqueTaskList; import java.util.*; import java.util.stream.Collectors; /** * Wraps all data at the address-book level * Duplicates are not allowed (by .equals comparison) */ public class ListOfTask implements ReadOnlyListOfTask { private final UniqueTaskList tasks; private final UniqueTagList tags; { tasks = new UniqueTaskList(); tags = new UniqueTagList(); } public ListOfTask() {} /** * Persons and Tags are copied into this addressbook */ public ListOfTask(ReadOnlyListOfTask toBeCopied) { this(toBeCopied.getUniqueTaskList(), toBeCopied.getUniqueTagList()); } /** * Persons and Tags are copied into this addressbook */ public ListOfTask(UniqueTaskList persons, UniqueTagList tags) { resetData(persons.getInternalList(), tags.getInternalList()); } public static ReadOnlyListOfTask getEmptyAddressBook() { return new ListOfTask(); } //// list overwrite operations public ObservableList<Task> getTasks() { return tasks.getInternalList(); } public void setTasks(List<Task> tasks) { this.tasks.getInternalList().setAll(tasks); } public void setTags(Collection<Tag> tags) { this.tags.getInternalList().setAll(tags); } public void resetData(Collection<? extends ReadOnlyTask> newPersons, Collection<Tag> newTags) { setTasks(newPersons.stream().map(Task::new).collect(Collectors.toList())); setTags(newTags); } public void resetData(ReadOnlyListOfTask newData) { resetData(newData.getTaskList(), newData.getTagList()); } //// person-level operations /** * Adds a person to the address book. * Also checks the new person's tags and updates {@link #tags} with any new tags found, * and updates the Tag objects in the person to point to those in {@link #tags}. * * @throws UniqueTaskList.DuplicatePersonException if an equivalent person already exists. */ public void addTask(Task p) throws UniqueTaskList.DuplicateTaskException { syncTagsWithMasterList(p); tasks.add(p); } /** * Ensures that every tag in this person: * - exists in the master list {@link #tags} * - points to a Tag object in the master list */ private void syncTagsWithMasterList(Task task) { final UniqueTagList taskTags = task.getTags(); tags.mergeFrom(taskTags); // Create map with values = tag object references in the master list final Map<Tag, Tag> masterTagObjects = new HashMap<>(); for (Tag tag : tags) { masterTagObjects.put(tag, tag); } // Rebuild the list of person tags using references from the master list final Set<Tag> commonTagReferences = new HashSet<>(); for (Tag tag : taskTags) { commonTagReferences.add(masterTagObjects.get(tag)); } task.setTags(new UniqueTagList(commonTagReferences)); } public boolean removeTask(ReadOnlyTask key) throws UniqueTaskList.TaskNotFoundException { if (tasks.remove(key)) { return true; } else { throw new UniqueTaskList.TaskNotFoundException(); } } public boolean editTask(ReadOnlyTask key, String args) throws UniqueTaskList.TaskNotFoundException, IllegalValueException{ if (tasks.edit(key, args)) return true; else { throw new UniqueTaskList.TaskNotFoundException(); } } public void doneTask(ReadOnlyTask key, boolean isDone){ tasks.done(key,isDone); } //// tag-level operations public void addTag(Tag t) throws UniqueTagList.DuplicateTagException { tags.add(t); } //// util methods @Override public String toString() { return tasks.getInternalList().size() + " Tasks, " + tags.getInternalList().size() + " tags"; // TODO: refine later } @Override public List<ReadOnlyTask> getTaskList() { return Collections.unmodifiableList(tasks.getInternalList()); } @Override public List<Tag> getTagList() { return Collections.unmodifiableList(tags.getInternalList()); } @Override public UniqueTaskList getUniqueTaskList() { return this.tasks; } @Override public UniqueTagList getUniqueTagList() { return this.tags; } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof ListOfTask // instanceof handles nulls && this.tasks.equals(((ListOfTask) other).tasks) && this.tags.equals(((ListOfTask) other).tags)); } @Override public int hashCode() { // use this method for custom fields hashing instead of implementing your own return Objects.hash(tasks, tags); } }
package tf.gpx.edit.viewer; import java.io.ByteArrayInputStream; import java.util.ArrayList; import java.util.Base64; import java.util.Iterator; import java.util.List; import java.util.Set; import javafx.css.PseudoClass; import javafx.geometry.BoundingBox; import javafx.geometry.Insets; import javafx.scene.CacheHint; import javafx.scene.Cursor; import javafx.scene.Node; import javafx.scene.chart.NumberAxis; import javafx.scene.chart.XYChart; import javafx.scene.control.Label; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.Background; import javafx.scene.layout.Border; import javafx.scene.text.Font; import javafx.scene.text.Text; import javafx.scene.text.TextAlignment; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.tuple.Pair; import tf.gpx.edit.helper.EarthGeometry; import tf.gpx.edit.helper.GPXEditorPreferences; import tf.gpx.edit.items.GPXLineItem; import tf.gpx.edit.items.GPXRoute; import tf.gpx.edit.items.GPXTrack; import tf.gpx.edit.items.GPXTrackSegment; import tf.gpx.edit.items.GPXWaypoint; import tf.gpx.edit.main.GPXEditor; /** * Helper class to hold stuff required by both HeightChart and LineChart * @author thomas */ public interface IChartBasics<T extends XYChart> { static String DATA_SEP = "-"; static String SHIFT_LABEL = "ShiftNode"; static String SHIFT_TEXT = "ShiftText"; public static enum ChartType { HEIGHTCHART, SPEEDCHART; } public static enum ColorPseudoClass { BLACK(PseudoClass.getPseudoClass("line-color-Black")), DARKRED(PseudoClass.getPseudoClass("line-color-DarkRed")), DARKGREEN(PseudoClass.getPseudoClass("line-color-DarkGreen")), DARKYELLOW(PseudoClass.getPseudoClass("line-color-GoldenRod")), DARKBLUE(PseudoClass.getPseudoClass("line-color-DarkBlue")), DARKMAGENTA(PseudoClass.getPseudoClass("line-color-DarkMagenta")), DARKCYAN(PseudoClass.getPseudoClass("line-color-DarkCyan")), DARKGRAY(PseudoClass.getPseudoClass("line-color-DarkGray")), LIGHTGRAY(PseudoClass.getPseudoClass("line-color-LightGray")), RED(PseudoClass.getPseudoClass("line-color-Red")), GREEN(PseudoClass.getPseudoClass("line-color-Green")), YELLOW(PseudoClass.getPseudoClass("line-color-Yellow")), BLUE(PseudoClass.getPseudoClass("line-color-Blue")), MAGENTA(PseudoClass.getPseudoClass("line-color-Magenta")), CYAN(PseudoClass.getPseudoClass("line-color-Cyan")), WHITE(PseudoClass.getPseudoClass("line-color-White")), SILVER(PseudoClass.getPseudoClass("line-color-Silver")); private final PseudoClass myPseudoClass; ColorPseudoClass(final PseudoClass pseudoClass) { myPseudoClass = pseudoClass; } public PseudoClass getPseudoClass() { return myPseudoClass; } public static PseudoClass getPseudoClassForColorName(final String colorName) { PseudoClass result = BLACK.getPseudoClass(); for (ColorPseudoClass color : ColorPseudoClass.values()) { if (color.name().toUpperCase().equals(colorName.toUpperCase())) { result = color.getPseudoClass(); } } return result; } } default void initialize() { getChart().setVisible(false); getChart().setAnimated(false); getChart().setCache(true); getChart().setCacheShape(true); getChart().setCacheHint(CacheHint.SPEED); getChart().setLegendVisible(false); getChart().setCursor(Cursor.DEFAULT); getChart().getXAxis().setAnimated(false); getChart().getYAxis().setAnimated(false); } // what any decent CHart needs to implement public abstract List<GPXLineItem> getGPXLineItems(); public void setGPXLineItems(final List<GPXLineItem> lineItems); public abstract double getMinimumDistance(); public abstract void setMinimumDistance(final double value); public abstract double getMaximumDistance(); public abstract void setMaximumDistance(final double value); public abstract double getMinimumYValue(); public abstract void setMinimumYValue(final double value); public abstract double getMaximumYValue(); public abstract void setMaximumYValue(final double value); public abstract List<Pair<GPXWaypoint, Double>> getPoints(); public abstract ChartsPane getChartsPane(); public abstract void setChartsPane(final ChartsPane pane); // only extensions of XYChart allowed public abstract T getChart(); public abstract Iterator<XYChart.Data<Double, Double>> getDataIterator(final XYChart.Series<Double, Double> series); // as default I don't shown file waypoints default boolean fileWaypointsInChart() { return false; } public abstract void setCallback(final GPXEditor gpxEditor); default void setEnable(final boolean enabled) { getChart().setDisable(!enabled); getChart().setVisible(enabled); getChart().toFront(); } @SuppressWarnings("unchecked") default void setGPXWaypoints(final List<GPXLineItem> lineItems, final boolean doFitBounds) { setGPXLineItems(lineItems); if (getChart().isDisabled()) { return; } // invisble update - much faster getChart().setVisible(false); getPoints().clear(); getChart().getData().clear(); // TFE, 20191230: avoid mess up when metadata is selected - nothing todo after clearing if (CollectionUtils.isEmpty(lineItems) || GPXLineItem.GPXLineItemType.GPXMetadata.equals(lineItems.get(0).getType())) { // nothing more todo... return; } setMinimumDistance(0d); setMaximumDistance(0d); setMinimumYValue(Double.MAX_VALUE); setMaximumYValue(Double.MIN_VALUE); final boolean alwaysShowFileWaypoints = GPXEditorPreferences.ALWAYS_SHOW_FILE_WAYPOINTS.getAsType(Boolean::valueOf); // TFE, 20191112: create series per track & route to be able to handle different colors final List<XYChart.Series<Double, Double>> seriesList = new ArrayList<>(); // TFE, 20200212: file waypoints need special treatment // need to calculate distance from other waypoints to show correctly on chart XYChart.Series<Double, Double> fileWaypointSeries = null; // show file waypoints only once boolean fileShown = false; for (GPXLineItem lineItem : lineItems) { // only files can have file waypoints if (fileWaypointsInChart()) { if (GPXLineItem.GPXLineItemType.GPXFile.equals(lineItem.getType())) { fileWaypointSeries = getXYChartSeriesForGPXLineItem(lineItem); } else if (alwaysShowFileWaypoints && !fileShown) { // add file waypoints as well, even though file isn't selected fileWaypointSeries = getXYChartSeriesForGPXLineItem(lineItem.getGPXFile()); fileShown = true; } } if (GPXLineItem.GPXLineItemType.GPXFile.equals(lineItem.getType()) || GPXLineItem.GPXLineItemType.GPXTrack.equals(lineItem.getType())) { for (GPXTrack gpxTrack : lineItem.getGPXTracks()) { // add track segments individually for (GPXTrackSegment gpxTrackSegment : gpxTrack.getGPXTrackSegments()) { seriesList.add(getXYChartSeriesForGPXLineItem(gpxTrackSegment)); } } } // track segments can have waypoints if (GPXLineItem.GPXLineItemType.GPXTrackSegment.equals(lineItem.getType())) { seriesList.add(getXYChartSeriesForGPXLineItem(lineItem)); } // files and routes can have routes if (GPXLineItem.GPXLineItemType.GPXFile.equals(lineItem.getType()) || GPXLineItem.GPXLineItemType.GPXRoute.equals(lineItem.getType())) { for (GPXRoute gpxRoute : lineItem.getGPXRoutes()) { seriesList.add(getXYChartSeriesForGPXLineItem(gpxRoute)); } } } if (fileWaypointSeries != null && CollectionUtils.isNotEmpty(fileWaypointSeries.getData())) { int waypointIconSize = GPXEditorPreferences.WAYPOINT_ICON_SIZE.getAsType(Integer::valueOf); int waypointLabelSize = GPXEditorPreferences.WAYPOINT_LABEL_SIZE.getAsType(Integer::valueOf); int waypointLabelAngle = GPXEditorPreferences.WAYPOINT_LABEL_ANGLE.getAsType(Integer::valueOf); int waypointThreshold = GPXEditorPreferences.WAYPOINT_THRESHOLD.getAsType(Integer::valueOf); // merge seriesList into one big series to iterate all in one loop XYChart.Series<Double, Double> flatSeries = new XYChart.Series<>(); for (XYChart.Series<Double, Double> series : seriesList) { flatSeries.getData().addAll(series.getData()); } for (XYChart.Data<Double, Double> data : fileWaypointSeries.getData()) { // 1. check file waypoints against other waypoints for minimum distance final GPXWaypoint fileWaypoint = (GPXWaypoint) data.getExtraValue(); XYChart.Data<Double, Double> closest = null; double mindistance = Double.MAX_VALUE; for (XYChart.Data<Double, Double> waypoint : flatSeries.getData()) { final double distance = EarthGeometry.distanceGPXWaypoints(fileWaypoint, (GPXWaypoint) waypoint.getExtraValue()); if (distance < mindistance) { closest = waypoint; mindistance = distance; } } if (closest != null && (mindistance < waypointThreshold || waypointThreshold == 0)) { // System.out.println(fileWaypointSeries.getData().indexOf(data) + 1 + ": " + fileWaypoint.getName() + ", " + ((GPXWaypoint) closest.getExtraValue()).getID() + ", " + closest.getXValue()); data.setXValue(closest.getXValue()); // 2. add text & icon as label to node final Label text = new Label(fileWaypoint.getName()); text.getStyleClass().add("item-id"); text.setFont(Font.font("Verdana", waypointLabelSize)); text.setRotate(360.0 - waypointLabelAngle); text.setBorder(Border.EMPTY); text.setBackground(Background.EMPTY); text.setPadding(Insets.EMPTY); text.setVisible(true); text.setMouseTransparent(true); // nodes are shown center-center aligned, hack needed to avoid that text.setUserData(SHIFT_LABEL); // add waypoint icon final String iconBase64 = MarkerManager.getInstance().getIcon(MarkerManager.getInstance().getMarkerForSymbol(fileWaypoint.getSym()).getIconName()); final Image image = new Image(new ByteArrayInputStream(Base64.getDecoder().decode(iconBase64)), waypointIconSize, waypointIconSize, false, false); text.setGraphic(new ImageView(image)); text.setGraphicTextGap(0); data.setNode(text); } // add each file waypoint as own series - we don't want to have aera or linees drawn... final XYChart.Series<Double, Double> series = new XYChart.Series<>(); series.getData().add(data); setSeriesUserData(series, fileWaypoint); seriesList.add(series); } } int dataCount = 0; for (XYChart.Series<Double, Double> series : seriesList) { dataCount += series.getData().size(); } showData(seriesList, dataCount); setAxis(getMinimumDistance(), getMaximumDistance(), getMinimumYValue(), getMaximumYValue()); // hide chart if no waypoints have been set getChart().setVisible(dataCount > 0); } @SuppressWarnings("unchecked") private void showData(final List<XYChart.Series<Double, Double>> seriesList, final int dataCount) { // TFE, 20180516: ignore fileWaypointsCount in count of wwaypoints to show. Otherwise no trackSegments getAsString shown if already enough waypoints... // file fileWaypointsCount don't count into MAX_WAYPOINTS //final long fileWaypointsCount = lineItem.getCombinedGPXWaypoints(GPXLineItem.GPXLineItemType.GPXFile).size(); //final double ratio = (GPXTrackviewer.MAX_WAYPOINTS - fileWaypointsCount) / (lineItem.getCombinedGPXWaypoints(null).size() - fileWaypointsCount); // TFE, 20190819: make number of waypoints to show a preference final double ratio = GPXEditorPreferences.MAX_WAYPOINTS_TO_SHOW.getAsType(Double::valueOf) / // might have no waypoints at all... Math.max(dataCount, 1); // TFE, 20191125: only show up to GPXEditorPreferenceStore.MAX_WAYPOINTS_TO_SHOW wayoints // similar logic to TrackMap.showWaypoints - could maybe be abstracted int count = 0, i = 0, j = 0; for (XYChart.Series<Double, Double> series : seriesList) { if (!series.getData().isEmpty()) { final XYChart.Series<Double, Double> reducedSeries = new XYChart.Series<>(); reducedSeries.setName(series.getName()); final GPXWaypoint firstWaypoint = (GPXWaypoint) series.getData().get(0).getExtraValue(); if (firstWaypoint.isGPXFileWaypoint()) { // we show all file waypoints reducedSeries.getData().addAll(series.getData()); } else { // we only show a subset of other waypoints - up to MAX_WAYPOINTS for (XYChart.Data<Double, Double> data : series.getData()) { i++; if (i * ratio >= count) { reducedSeries.getData().add(data); count++; } } } getChart().getData().add(reducedSeries); if (!GPXLineItem.GPXLineItemType.GPXFile.equals(firstWaypoint.getType())) { // and now color the series nodes according to lineitem color final PseudoClass color = IChartBasics.ColorPseudoClass.getPseudoClassForColorName(getSeriesColor(reducedSeries)); reducedSeries.getNode().pseudoClassStateChanged(color, true); Set<Node> nodes = getChart().lookupAll(".series" + j); for (Node n : nodes) { n.pseudoClassStateChanged(color, true); } } j++; } } // add labels to series on base chart if (getChartsPane().getBaseChart().equals(this)) { for (XYChart.Series<Double, Double> series : seriesList) { // only if not empty and not for file waypoints if (!series.getData().isEmpty() && !((GPXWaypoint) series.getData().get(0).getExtraValue()).isGPXFileWaypoint()) { // add item ID as text "in the middle" of the waypoints above x-axis - for base chart final Text text = new Text(getSeriesID(series)); text.getStyleClass().add("item-id"); text.setFont(Font.font("Verdana", 9)); text.setTextAlignment(TextAlignment.LEFT); text.setRotate(270.0); text.setVisible(true); text.setMouseTransparent(true); // text should be just above yAxis, only possible after layout text.setUserData(SHIFT_TEXT); // calculate "middle" for x and 10% above lower for y final double xPosText = (series.getData().get(0).getXValue() + series.getData().get(series.getData().size()-1).getXValue()) / 2.0; if (xPosText > 0.0) { // add data point with this text as node final XYChart.Data<Double, Double> idLabel = new XYChart.Data<>(xPosText, getMinimumYValue()); idLabel.setExtraValue((GPXWaypoint) series.getData().get(0).getExtraValue()); idLabel.setNode(text); // add each label as own series - we don't want to have aera or linees drawn... final XYChart.Series<Double, Double> idSeries = new XYChart.Series<>(); idSeries.getData().add(idLabel); getChart().getData().add(idSeries); } } } } // final AtomicInteger shownCount = new AtomicInteger(0); // getChart().getData().forEach((t) -> { // XYChart.Series<Double, Double> series = (XYChart.Series<Double, Double>) t; // shownCount.set(shownCount.getAsString() + series.getData().size()); // System.out.println("Datapoints added: " + shownCount.getAsString()); } @SuppressWarnings("unchecked") default void adaptLayout() { final int waypointIconSize = GPXEditorPreferences.WAYPOINT_ICON_SIZE.getAsType(Integer::valueOf); // shift nodes to center-left from center-center getChart().getData().forEach((t) -> { final XYChart.Series<Double, Double> series = (XYChart.Series<Double, Double>) t; for (Iterator<XYChart.Data<Double, Double>> it = getDataIterator(series); it.hasNext(); ) { XYChart.Data<Double, Double> data = it.next(); final double xVal = getChart().getXAxis().getDisplayPosition(data.getXValue()); final double yVal = getChart().getYAxis().getDisplayPosition(data.getYValue()); if (Double.isNaN(xVal) || Double.isNaN(yVal)) { continue; } Node symbol = data.getNode(); if (symbol != null) { symbol.applyCss(); if (SHIFT_LABEL.equals((String) symbol.getUserData())) { // shift done in AreaChart.layoutPlotChildren() is // final double w = symbol.prefWidth(-1); // final double h = symbol.prefHeight(-1); // symbol.resizeRelocate(x-(w/2), y-(h/2),w,h); // resize done in Node.relocate() is // setLayoutX(x - getLayoutBounds().getMinX()); // setLayoutY(y - getLayoutBounds().getMinY()); final double w = symbol.prefWidth(-1); final double h = symbol.prefHeight(-1); // factor in getRotate() to calculate horizontal + vertical shift values // shift such that center of icon is on point // for horizontal // 0 degrees: w/2 - icon // 45 degrees: w/2 / sqrt(2) - icon / sqrt(2) // 90 degrees: 0 // 135 degrees: -w/2 / sqrt(2) + icon / sqrt(2) // 180 degrees: -w/2 + icon // 225 degrees: -w/2 / sqrt(2) + icon / sqrt(2) // 270 degrees: 0 // 315 degrees: w/2 / sqrt(2) // => cos(getRotate()) * w/2 // for vertical // 0 degrees: 0 // 45 degrees: w/2 / sqrt(2) - icon / sqrt(2) // 90 degrees: w/2 - icon // 135 degrees: w/2 / sqrt(2) - icon / sqrt(2) // 180 degrees: 0 // 225 degrees: -w/2 / sqrt(2) + icon / sqrt(2) // 270 degrees: -w/2 // 315 degrees: -w/2 / sqrt(2) // => sin(getRotate()) * w/2 final double angle = symbol.getRotate() * Math.PI / 180.0; final double shiftX = Math.cos(angle) * (w-waypointIconSize)/2.0; final double shiftY = Math.sin(angle) * (w-waypointIconSize)/2.0; // System.out.println("Shifting node: " + ((GPXWaypoint) data.getExtraValue()).getName() + " by " + shiftX + ", " + shiftY); // undo old shift and shift to center-center instead symbol.setLayoutX(symbol.getLayoutX() + shiftX); symbol.setLayoutY(symbol.getLayoutY() + shiftY); } else if (SHIFT_TEXT.equals((String) symbol.getUserData())) { // now getYAxis().getZeroPosition() should yield something useful data.setYValue(getChart().getYAxis().getZeroPosition()); } } } }); } @SuppressWarnings("unchecked") default boolean hasData() { boolean result = false; final List<XYChart.Series<Double, Double>> seriesList = (List<XYChart.Series<Double, Double>>) getChart().getData(); for (XYChart.Series<Double, Double> series: seriesList) { if (!series.getData().isEmpty()) { result = true; break; } } return result; } private XYChart.Series<Double, Double> getXYChartSeriesForGPXLineItem(final GPXLineItem lineItem) { final List<XYChart.Data<Double, Double>> dataList = new ArrayList<>(); for (GPXWaypoint gpxWaypoint : lineItem.getGPXWaypoints()) { setMaximumDistance(getMaximumDistance() + gpxWaypoint.getDistance()); final double yValue = getYValueAndSetMinMax(gpxWaypoint); XYChart.Data<Double, Double> data = new XYChart.Data<>(getMaximumDistance() / 1000.0, yValue); data.setExtraValue(gpxWaypoint); dataList.add(data); getPoints().add(Pair.of(gpxWaypoint, getMaximumDistance())); } final XYChart.Series<Double, Double> series = new XYChart.Series<>(); series.getData().addAll(dataList); setSeriesUserData(series, lineItem); return series; } private static void setSeriesUserData(final XYChart.Series<Double, Double> series, final GPXLineItem lineItem) { String seriesID = lineItem.getCombinedID(); // add track id for track segments if (GPXLineItem.GPXLineItemType.GPXTrackSegment.equals(lineItem.getType())) { seriesID = lineItem.getParent().getCombinedID() + "." + seriesID; } series.setName(seriesID + DATA_SEP + lineItem.getColor()); } private static String getSeriesID(final XYChart.Series<Double, Double> series) { return series.getName().split(DATA_SEP)[0]; } private static String getSeriesColor(final XYChart.Series<Double, Double> series) { return series.getName().split(DATA_SEP)[1]; } public abstract double getYValueAndSetMinMax(final GPXWaypoint gpxWaypoint); default void setAxis(final double minDist, final double maxDist, final double minHght, final double maxHght) { double distance = maxDist - minDist; // calculate scaling for ticks so their number is smaller than 25 double tickUnit = 1.0; if (distance / 1000.0 > 24.9) { tickUnit = 2.0; } if (distance / 1000.0 > 49.9) { tickUnit = 5.0; } if (distance / 1000.0 > 499.9) { tickUnit = 50.0; } if (distance / 1000.0 > 4999.9) { tickUnit = 500.0; } ((NumberAxis) getChart().getXAxis()).setTickUnit(tickUnit); // TFE, 20181124: set lower limit as well since it might have changed in setViewLimits ((NumberAxis) getChart().getXAxis()).setLowerBound(minDist / 1000.0); ((NumberAxis) getChart().getXAxis()).setUpperBound(maxDist / 1000.0); // System.out.println("minHght: " + minHght + ", maxHght:" + maxHght); ((NumberAxis) getChart().getYAxis()).setTickUnit(10.0); ((NumberAxis) getChart().getYAxis()).setLowerBound(minHght); ((NumberAxis) getChart().getYAxis()).setUpperBound(maxHght); } @SuppressWarnings("unchecked") default XYChart.Data<Double, Double> getNearestDataForXValue(final Double xValue) { final List<XYChart.Series<Double, Double>> seriesList = (List<XYChart.Series<Double, Double>>) getChart().getData(); XYChart.Data<Double, Double> nearestData = null; double distance = Double.MAX_VALUE; for (XYChart.Series<Double, Double> series: seriesList) { for (XYChart.Data<Double, Double> data : series.getData()) { double xData = data.getXValue(); double dataDistance = Math.abs(xValue - xData); if (dataDistance < distance) { distance = dataDistance; nearestData = data; } } } return nearestData; } // set lineStart bounding box to limit which waypoints are shown // or better: to define, what min and max x-axis to use default void setViewLimits(final BoundingBox newBoundingBox) { if (getPoints().isEmpty()) { // nothing to show yet... return; } // init with maximum values double minDist = getMinimumDistance(); double maxDist = getMaximumDistance(); double minHght = getMinimumYValue(); double maxHght = getMaximumYValue(); if (newBoundingBox != null) { minHght = Double.MAX_VALUE; maxHght = Double.MIN_VALUE; boolean waypointFound = false; // 1. iterate over myPoints for (Pair<GPXWaypoint, Double> point: getPoints()) { GPXWaypoint waypoint = point.getLeft(); if (!waypoint.isGPXFileWaypoint() && newBoundingBox.contains(waypoint.getLatitude(), waypoint.getLongitude())) { // 2. if waypoint in bounding box: // if first waypoint use this for minDist // use this for maxDist if (!waypointFound) { minDist = point.getRight(); } maxDist = point.getRight(); final double elevation = waypoint.getElevation(); minHght = Math.min(minHght, elevation); maxHght = Math.max(maxHght, elevation); waypointFound = true; } if (!waypointFound) { minDist = 0.0; maxDist = 0.0; } } // if no waypoint in bounding box show nothing } setAxis(minDist, maxDist, minHght, maxHght); } @SuppressWarnings("unchecked") default void updateGPXWaypoints(final List<GPXWaypoint> gpxWaypoints) { // TODO: fill with life } default void setSelectedGPXWaypoints(final List<GPXWaypoint> gpxWaypoints, final Boolean highlightIfHidden, final Boolean useLineMarker) { if (getChart().isDisabled()) { return; } } default void clearSelectedGPXWaypoints() { if (getChart().isDisabled()) { return; } } default void updateLineColor(final GPXLineItem lineItem) { // nothing todo } default void loadPreferences() { // nothing todo } default void savePreferences() { // nothing todo } }
package de.thexxturboxx.blockhelper; import buildcraft.transport.TileGenericPipe; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.SidedProxy; import cpw.mods.fml.common.network.IPacketHandler; import cpw.mods.fml.common.network.PacketDispatcher; import cpw.mods.fml.common.network.Player; import de.thexxturboxx.blockhelper.api.BlockHelperInfoProvider; import de.thexxturboxx.blockhelper.api.BlockHelperModSupport; import factorization.common.TileEntityCommon; import ic2.core.Ic2Items; import inficraft.microblocks.core.api.multipart.ICoverSystem; import inficraft.microblocks.core.api.multipart.IMultipartTile; import java.awt.Color; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Random; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Gui; import net.minecraft.client.gui.ScaledResolution; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.monster.IMob; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.network.INetworkManager; import net.minecraft.network.packet.Packet250CustomPayload; import net.minecraft.src.BaseMod; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.MovingObjectPosition; import net.minecraft.world.World; import net.minecraftforge.common.DimensionManager; public class mod_BlockHelper extends BaseMod implements IPacketHandler { private static final String PACKAGE = "de.thexxturboxx.blockhelper."; private static final String MOD_ID = "BlockHelper"; static final String NAME = "Block Helper"; static final String VERSION = "0.9"; static final String CHANNEL = "BlockHelperInfo"; public static final MopType[] MOP_TYPES = MopType.values(); public static boolean isClient; private boolean isHidden = false; @SidedProxy(clientSide = PACKAGE + "BlockHelperClientProxy", serverSide = PACKAGE + "BlockHelperCommonProxy") public static BlockHelperCommonProxy proxy; public static String getModId() { return MOD_ID; } @Override public String getName() { return NAME; } @Override public String getVersion() { return VERSION; } @Override public void load() { proxy.load(this); } @Override public boolean onTickInGame(float time, Minecraft mc) { try { BlockHelperUpdater.notifyUpdater(mc); if (mc.theWorld.isRemote) { updateKeyState(); if (mc.currentScreen != null || isHidden) return true; int i = isLookingAtBlock(mc); if (i == 0) return true; MovingObjectPosition mop = mc.objectMouseOver; ByteArrayOutputStream buffer = new ByteArrayOutputStream(); DataOutputStream os = new DataOutputStream(buffer); try { if (MOP_TYPES[i] == MopType.ENTITY) { PacketCoder.encode(os, new PacketInfo(mc.theWorld.provider.dimensionId, mop, MOP_TYPES[i], mop.entityHit.entityId)); } else { PacketCoder.encode(os, new PacketInfo(mc.theWorld.provider.dimensionId, mop, MOP_TYPES[i])); } } catch (IOException e1) { e1.printStackTrace(); } byte[] fieldData = buffer.toByteArray(); Packet250CustomPayload packet = new Packet250CustomPayload(); packet.channel = CHANNEL; packet.data = fieldData; packet.length = fieldData.length; PacketDispatcher.sendPacketToServer(packet); switch (i) { case 1: int meta = mc.theWorld.getBlockMetadata(mop.blockX, mop.blockY, mop.blockZ); int id = mc.theWorld.getBlockId(mop.blockX, mop.blockY, mop.blockZ); ItemStack is = new ItemStack(Block.blocksList[id], 1, meta); TileEntity te = mc.theWorld.getBlockTileEntity(mop.blockX, mop.blockY, mop.blockZ); String itemId = is.itemID + ":" + is.getItemDamage(); String ct = null; String name = ""; if (te != null) { if (iof(te, "thermalexpansion.transport.tileentity.TileConduitLiquid")) { is.setItemDamage(4096); } else if (iof(te, "ic2.core.block.wiring.TileEntityCable")) { is = new ItemStack(Item.itemsList[Ic2Items.copperCableItem.itemID], 1, meta); } else if (iof(te, "factorization.common.TileEntityCommon")) { ct = "Factorization"; is.setItemDamage(((TileEntityCommon) te).getFactoryType().md); } else if (iof(te, "codechicken.chunkloader.TileChunkLoaderBase")) { ct = "ChickenChunks"; } else if (iof(te, "buildcraft.transport.TileGenericPipe")) { TileGenericPipe pipe = (TileGenericPipe) te; ct = "BuildCraft"; if (pipe.pipe != null && pipe.initialized) { is = new ItemStack(Item.itemsList[pipe.pipe.itemID], te.blockMetadata); } } else if (iof(te, "inficraft.microblocks.core.api.multipart.IMultipartTile")) { IMultipartTile te1 = (IMultipartTile) te; if (mop.subHit >= 0) { is = te1.pickPart(mop, mop.subHit); } else { ICoverSystem ci = te1.getCoverSystem(); is = ci == null ? is : ci.pickPart(mop, -1 - mop.subHit); } ct = "InfiMicroblocks"; } } Block b = Block.blocksList[id]; if (b != null) { if (iof(b, "net.meteor.common.BlockMeteorShieldTorch")) { is = new ItemStack(b.idDropped(0, null, 0), 1, meta); } } if (is.getItem() == null) return true; if (ct == null) { if (is.getItem().getCreativeTab() != null) { if (is.getItem().getCreativeTab().getTabIndex() < 12) { ct = "Minecraft"; } else { ct = is.getItem().getCreativeTab().getTranslatedTabLabel(); } } else { ct = "Unknown"; } } infoWidth = 0; int[] xy = drawBox(mc); currLine = 12; infos.clear(); try { name = is.getDisplayName(); if (name.equals("")) throw new IllegalArgumentException(); } catch (Throwable e) { try { name = new ItemStack(b).getDisplayName(); if (name.equals("")) throw new IllegalArgumentException(); } catch (Throwable e1) { try { if (b != null) { name = new ItemStack(Item.itemsList[b.idDropped(meta, new Random(), 0)], 1, b.damageDropped(meta)).getDisplayName(); } if (name.equals("")) throw new IllegalArgumentException(); } catch (Throwable e2) { name = "Please report this!"; } } } String harvest = "Please report this!"; boolean harvestable = false; if (b != null) { float hardness = b.getBlockHardness(proxy.getWorld(), mop.blockX, mop.blockY, mop.blockZ); if (hardness == -1.0F || hardness == -1.0D || hardness == -1) { harvest = "Unbreakable"; } else if (b.canHarvestBlock(proxy.getPlayer(), meta)) { harvestable = true; harvest = "Currently harvestable"; } else { harvest = "Currently not harvestable"; } } addInfo(name); addInfo(itemId); addInfo("§o" + ct.replaceAll("§.", ""), 0x000000ff); addAdditionalInfo(packetInfos); addInfo((harvestable ? "§a" : "§4") + " §r" + harvest); drawInfo(xy, mc); break; case 2: Entity e = mop.entityHit; infoWidth = 0; xy = drawBox(mc); currLine = 12; infos.clear(); String nameEntity = e.getEntityName(); if (e instanceof IMob) { nameEntity = "§4" + nameEntity; } addInfo(nameEntity); addAdditionalInfo(packetInfos); drawInfo(xy, mc); break; default: break; } } } catch (Throwable e) { e.printStackTrace(); } return true; } private void updateKeyState() { if (BlockHelperClientProxy.showHide.isPressed()) { isHidden = !isHidden; } } private int getStringMid(int[] xy, String s, Minecraft mc) { return xy[0] - mc.fontRenderer.getStringWidth(s) / 2; } private int isLookingAtBlock(Minecraft mc) { MovingObjectPosition mop = mc.objectMouseOver; if (mop == null) return 0; switch (mop.typeOfHit) { case ENTITY: return 2; case TILE: Material b = mc.theWorld.getBlockMaterial(mop.blockX, mop.blockY, mop.blockZ); if (b != null) return 1; else return 0; default: return 0; } } private static class FormatString { private final String str; private final int color; FormatString(String str, int color) { this.str = str; this.color = color; } } private static List<String> packetInfos = new ArrayList<String>(); private static final List<FormatString> infos = new ArrayList<FormatString>(); private void addAdditionalInfo(List<String> info) { for (String s : info) { addInfo("§7" + s); } } private void addInfo(String info) { addInfo(info, 0xffffffff); } private void addInfo(String info, int color) { if (info != null && !info.equals("")) { infos.add(new FormatString(info, color)); } } private static int currLine; private static int infoWidth = 0; private static final int dark = new Color(17, 2, 16).getRGB(); public static int light = new Color(52, 18, 102).getRGB(); private void drawInfo(int[] xy, Minecraft mc) { for (FormatString s : infos) { mc.fontRenderer.drawString(s.str, getStringMid(xy, s.str, mc), currLine, s.color); currLine = currLine + 8; } } private int[] drawBox(Minecraft mc) { int[] xy = new int[2]; ScaledResolution res = new ScaledResolution(mc.gameSettings, mc.displayWidth, mc.displayHeight); int width = res.getScaledWidth(); int height = res.getScaledHeight(); if (BlockHelperClientProxy.mode != 1) { for (FormatString s : infos) { infoWidth = Math.max(mc.fontRenderer.getStringWidth(s.str) + 12, infoWidth); } infoWidth *= BlockHelperClientProxy.size; int minusHalf = (width - infoWidth) / 2; int plusHalf = (width + infoWidth) / 2; Gui.drawRect(minusHalf + 2, 7, plusHalf - 2, currLine + 5, dark); Gui.drawRect(minusHalf + 1, 8, plusHalf - 1, currLine + 4, dark); Gui.drawRect(minusHalf + 2, 8, plusHalf - 2, currLine + 4, light); Gui.drawRect(((width - infoWidth) / 2) + 3, 9, ((width + infoWidth) / 2) - 3, currLine + 3, dark); } xy[0] = width / 2; xy[1] = height / 2; return xy; } @Override public void onPacketData(INetworkManager manager, Packet250CustomPayload packetGot, Player player) { try { if (packetGot.channel.equals(CHANNEL)) { ByteArrayInputStream isRaw = new ByteArrayInputStream(packetGot.data); DataInputStream is = new DataInputStream(isRaw); if (isClient && FMLCommonHandler.instance().getEffectiveSide().isClient()) { try { packetInfos = ((PacketClient) PacketCoder.decode(is)).data; } catch (IOException e) { e.printStackTrace(); } } else if (FMLCommonHandler.instance().getEffectiveSide().isServer()) { PacketInfo pi = null; try { pi = (PacketInfo) PacketCoder.decode(is); } catch (IOException e1) { e1.printStackTrace(); } if (pi == null || pi.mop == null) return; World w = DimensionManager.getProvider(pi.dimId).worldObj; if (pi.mt == MopType.ENTITY) { Entity en = w.getEntityByID(pi.entityId); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); DataOutputStream os = new DataOutputStream(buffer); PacketClient pc = new PacketClient(); if (en != null) { try { pc.add(((EntityLiving) en).getHealth() + " / " + ((EntityLiving) en).getMaxHealth() + " "); PacketCoder.encode(os, pc); } catch (IOException e) { e.printStackTrace(); } catch (Throwable e) { try { PacketCoder.encode(os, pc); } catch (IOException e1) { e1.printStackTrace(); } } } else { try { PacketCoder.encode(os, pc); } catch (IOException e) { e.printStackTrace(); } } byte[] fieldData = buffer.toByteArray(); Packet250CustomPayload packet = new Packet250CustomPayload(); packet.channel = CHANNEL; packet.data = fieldData; packet.length = fieldData.length; PacketDispatcher.sendPacketToPlayer(packet, player); } else if (pi.mt == MopType.BLOCK) { TileEntity te = w.getBlockTileEntity(pi.mop.blockX, pi.mop.blockY, pi.mop.blockZ); int id = w.getBlockId(pi.mop.blockX, pi.mop.blockY, pi.mop.blockZ); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); DataOutputStream os = new DataOutputStream(buffer); PacketClient info = new PacketClient(); if (id > 0) { int meta = w.getBlockMetadata(pi.mop.blockX, pi.mop.blockY, pi.mop.blockZ); Block b = Block.blocksList[id]; BlockHelperModSupport.addInfo(info, b, id, meta, te); } try { PacketCoder.encode(os, info); } catch (IOException e) { e.printStackTrace(); } byte[] fieldData = buffer.toByteArray(); Packet250CustomPayload packet = new Packet250CustomPayload(); packet.channel = CHANNEL; packet.data = fieldData; packet.length = fieldData.length; PacketDispatcher.sendPacketToPlayer(packet, player); } } } } catch (Throwable e) { e.printStackTrace(); } } static boolean iof(Object obj, String clazz) { return BlockHelperInfoProvider.isLoadedAndInstanceOf(obj, clazz); } }
package tigase.conf; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import tigase.db.TigaseDBException; import tigase.util.DataTypes; import tigase.util.JDBCAbstract; import static tigase.conf.Configurable.*; /** * Created: Dec 15, 2009 10:44:00 PM * * @author <a href="mailto:artur.hefczyc@tigase.org">Artur Hefczyc</a> * @version $Rev$ */ public class ConfigSQLRepository extends ConfigurationCache { public static final String CONFIG_REPO_URI_PROP_KEY = "tigase-config-repo-uri"; public static final String CONFIG_REPO_URI_INIT_KEY = "--tigase-config-repo-uri"; /** * Private logger for class instancess. */ private static final Logger log = Logger.getLogger(ConfigSQLRepository.class.getName()); private JDBCAccess dbAccess = new JDBCAccess(); @Override public void init(Map<String, Object> params) throws ConfigurationException { String config_db_uri = System.getProperty(CONFIG_REPO_URI_PROP_KEY); if (config_db_uri == null) { config_db_uri = (String)params.get(CONFIG_REPO_URI_INIT_KEY); } if (config_db_uri == null) { config_db_uri = (String)params.get(GEN_USER_DB_URI); } if (config_db_uri == null) { log.severe("Missing configuration database connection string."); log.severe("Tigase needs a database connection string to load configuration."); log.severe("You can provide it in a few ways and the Tigase server checks"); log.severe("following parameters in the order below:"); log.severe("1. System property: -Dtigase-config-repo-uri=db-connection-string"); log.severe("2. init.properties file or command line parameter: --tigase-config-repo-uri=db-connection-string"); log.severe("3. init.properties file or command line parameter: --user-db-uri=db-connection-string"); log.severe("Please correct the error and restart the server."); System.exit(1); } try { dbAccess.initRepository(config_db_uri, null); } catch (SQLException ex) { log.log(Level.SEVERE, "Problem connecting to configuration database: ", ex); log.severe("Please check whether the database connection string is correct: " + config_db_uri); System.exit(1); } } @Override public Set<ConfigItem> getItemsForComponent(String compName) { return dbAccess.getCompItems(compName); } @Override public ConfigItem getItem(String compName, String node, String key) { return dbAccess.getItem(compName, node, key); } @Override public void addItem(String compName, ConfigItem item) { dbAccess.addItem(item); } @Override public void removeItem(String compName, ConfigItem item) { dbAccess.removeItem(item); } @Override public String[] getCompNames() { return dbAccess.getComponentNames(); } @Override public String[] getKeys(String compName, String node) { return dbAccess.getKeys(compName, node); } @Override public int size() { return dbAccess.getPropertiesCount(); } @Override public Collection<ConfigItem> allItems() throws TigaseDBException { return dbAccess.getAllItems(); } private class JDBCAccess extends JDBCAbstract { public static final String TABLE_NAME = "tigase_configuration"; private static final String CLUSTER_NODE_COLUMN = "cluster_node"; private static final String COMPONENT_NAME_COLUMN = "component_name"; private static final String NODE_NAME_COLUMN = "key_node"; private static final String KEY_NAME_COLUMN = "key_name"; private static final String VALUE_COLUMN = "value"; private static final String FLAG_COLUMN = "flag"; private static final String VALUE_TYPE_COLUMN = "value_type"; private static final String LAST_UPDATE_COLUMN = "last_update"; private static final String CREATE_TABLE_QUERY = "create table " + TABLE_NAME + " (" + " " + COMPONENT_NAME_COLUMN + " varchar(127) NOT NULL," + " " + KEY_NAME_COLUMN + " varchar(127) NOT NULL," + " " + VALUE_COLUMN + " varchar(8191) NOT NULL," + " " + CLUSTER_NODE_COLUMN + " varchar(255) NOT NULL DEFAULT ''," + " " + NODE_NAME_COLUMN + " varchar(127) NOT NULL DEFAULT ''," + " " + FLAG_COLUMN + " varchar(32) NOT NULL DEFAULT 'DEFAULT'," + " " + VALUE_TYPE_COLUMN + " varchar(8) NOT NULL DEFAULT 'S'," + " " + LAST_UPDATE_COLUMN + " timestamp," + " primary key(" + CLUSTER_NODE_COLUMN + ", " + COMPONENT_NAME_COLUMN + ", " + NODE_NAME_COLUMN + ", " + KEY_NAME_COLUMN + ", " + FLAG_COLUMN + "))"; private static final String CLUSTER_NODE_WHERE_PART = " (" + CLUSTER_NODE_COLUMN + " = '' " + " OR " + CLUSTER_NODE_COLUMN + " = ?) "; private static final String ITEM_WHERE_PART = " where " + CLUSTER_NODE_WHERE_PART + " AND (" + COMPONENT_NAME_COLUMN + " = ?) " + " AND (" + NODE_NAME_COLUMN + " = ?) " + " AND (" + KEY_NAME_COLUMN + " = ?) "; //+ " AND (" + FLAG_COLUMN + " = ?)"; private static final String CHECK_TABLE_QUERY = "select count(*) from " + TABLE_NAME; private static final String GET_ITEM_QUERY = "select * from " + TABLE_NAME + ITEM_WHERE_PART; private static final String ADD_ITEM_QUERY = "insert into " + TABLE_NAME + " (" + CLUSTER_NODE_COLUMN + ", " + COMPONENT_NAME_COLUMN + ", " + NODE_NAME_COLUMN + ", " + KEY_NAME_COLUMN + ", " + VALUE_COLUMN + ", " + VALUE_TYPE_COLUMN + ", " + FLAG_COLUMN + ") " + " values (?, ?, ?, ?, ?, ?, ?)"; private static final String UPDATE_ITEM_QUERY = "update " + TABLE_NAME + " set " + VALUE_COLUMN + " = ? " + " where (" + CLUSTER_NODE_COLUMN + " = ?) " + " AND (" + COMPONENT_NAME_COLUMN + " = ?) " + " AND (" + NODE_NAME_COLUMN + " = ?) " + " AND (" + KEY_NAME_COLUMN + " = ?)"; private static final String DELETE_ITEM_QUERY = "delete from " + TABLE_NAME + ITEM_WHERE_PART; private static final String GET_ALL_ITEMS_QUERY = "select * from " + TABLE_NAME + " where " + CLUSTER_NODE_WHERE_PART; private static final String GET_COMPONENT_ITEMS_QUERY = "select * from " + TABLE_NAME + " where " + CLUSTER_NODE_WHERE_PART + " AND (" + COMPONENT_NAME_COLUMN + " = ?)"; private static final String GET_UPDATED_ITEMS_QUERY = "select * from " + TABLE_NAME + " where " + CLUSTER_NODE_WHERE_PART + " AND (" + FLAG_COLUMN + " <> 'INITIAL')" + " AND (" + LAST_UPDATE_COLUMN + " > ?)"; private static final String GET_COMPONENT_NAMES_QUERY = "select distinct(" + COMPONENT_NAME_COLUMN + ") from " + TABLE_NAME + " where " + CLUSTER_NODE_COLUMN; private static final String GET_PROPERTIES_COUNT_QUERY = "select count(*) as count from " + TABLE_NAME + " where " + CLUSTER_NODE_COLUMN; private static final String GET_KEYS_QUERY = "select " + KEY_NAME_COLUMN + " from " + TABLE_NAME + " where " + CLUSTER_NODE_WHERE_PART + " AND (" + COMPONENT_NAME_COLUMN + " = ?)" + " AND (" + NODE_NAME_COLUMN + " = ?)"; private PreparedStatement createTableSt = null; private PreparedStatement checkTableSt = null; private PreparedStatement getItemSt = null; private PreparedStatement getAllItemsSt = null; private PreparedStatement getCompItemsSt = null; private PreparedStatement getUpdatedItemsSt = null; private PreparedStatement addItemSt = null; private PreparedStatement updateItemSt = null; private PreparedStatement deleteItemSt = null; private PreparedStatement getCompNamesSt = null; private PreparedStatement getPropertiesCountSt = null; private PreparedStatement getKeysSt = null; @Override public void initRepository(String conn_str, Map<String, String> params) throws SQLException { setResourceUri(conn_str); checkConnection(); // Check if DB is correctly setup and contains all required tables. checkDB(); } @Override protected void initPreparedStatements() throws SQLException { super.initPreparedStatements(); checkTableSt = prepareStatement(CHECK_TABLE_QUERY); getItemSt = prepareStatement(GET_ITEM_QUERY); getAllItemsSt = prepareStatement(GET_ALL_ITEMS_QUERY); getCompItemsSt = prepareStatement(GET_COMPONENT_ITEMS_QUERY); addItemSt = prepareStatement(ADD_ITEM_QUERY); updateItemSt = prepareStatement(UPDATE_ITEM_QUERY); deleteItemSt = prepareStatement(DELETE_ITEM_QUERY); getUpdatedItemsSt = prepareStatement(GET_UPDATED_ITEMS_QUERY); getCompNamesSt = prepareStatement(GET_COMPONENT_NAMES_QUERY); getPropertiesCountSt = prepareStatement(GET_PROPERTIES_COUNT_QUERY); getKeysSt = prepareStatement(GET_KEYS_QUERY); } private void checkDB() throws SQLException { ResultSet rs = null; try { rs = checkTableSt.executeQuery(); if (rs.next()) { long count = rs.getLong(1); log.info("DB for external component OK, items: " + count); } } catch (Exception e) { initializeDB(); } finally { release(null, rs); rs = null; } } private void initializeDB() throws SQLException { createTableSt = prepareStatement(CREATE_TABLE_QUERY); log.info("DB for external component is not OK, creating missing tables..."); createTableSt.executeUpdate(); log.info("DB for external component created OK"); } private Collection<ConfigItem> getAllItems() { List<ConfigItem> result = new ArrayList<ConfigItem>(); ResultSet rs = null; try { checkConnection(); synchronized (getAllItemsSt) { getAllItemsSt.setString(1, getDefHostname()); rs = getAllItemsSt.executeQuery(); while (rs.next()) { ConfigItem item = createItemFromRS(rs); if (item.getFlag() != ConfigItem.FLAGS.INITIAL) { result.add(item); } } } } catch (SQLException e) { log.log(Level.WARNING, "Problem getting elements from DB: ", e); } finally { release(null, rs); } return result; } private ConfigItem createItemFromRS(ResultSet rs) throws SQLException { ConfigItem result = getItemInstance(); String clusterNode = rs.getString(CLUSTER_NODE_COLUMN); String compName = rs.getString(COMPONENT_NAME_COLUMN); String nodeName = rs.getString(NODE_NAME_COLUMN); String keyName = rs.getString(KEY_NAME_COLUMN); String value_str = rs.getString(VALUE_COLUMN); String value_type = rs.getString(VALUE_TYPE_COLUMN); String flag_str = rs.getString(FLAG_COLUMN); result.set(clusterNode, compName, nodeName, keyName, value_str, value_type.charAt(0), flag_str); return result; } private Set<ConfigItem> getCompItems(String compName) { Set<ConfigItem> result = new LinkedHashSet<ConfigItem>(); ResultSet rs = null; try { checkConnection(); synchronized (getCompItemsSt) { getCompItemsSt.setString(1, getDefHostname()); getCompItemsSt.setString(2, compName); rs = getCompItemsSt.executeQuery(); while (rs.next()) { ConfigItem item = createItemFromRS(rs); if (item.getFlag() != ConfigItem.FLAGS.INITIAL) { result.add(item); } } } } catch (SQLException e) { log.log(Level.WARNING, "Problem getting elements from DB: ", e); } finally { release(null, rs); } return result; } private ConfigItem getItem(String compName, String node, String key) { ConfigItem result = null; ResultSet rs = null; try { checkConnection(); synchronized (getItemSt) { getItemSt.setString(1, getDefHostname()); getItemSt.setString(2, compName); getItemSt.setString(3, node); getItemSt.setString(4, key); rs = getItemSt.executeQuery(); while (rs.next()) { ConfigItem item = createItemFromRS(rs); if (item.getFlag() != ConfigItem.FLAGS.INITIAL) { result = item; break; } } } } catch (SQLException e) { log.log(Level.WARNING, "Problem getting elements from DB: ", e); } finally { release(null, rs); } return result; } private void addItem(ConfigItem item) { try { checkConnection(); synchronized (addItemSt) { addItemSt.setString(1, (item.getClusterNode() != null ? item.getClusterNode() : "")); addItemSt.setString(2, item.getCompName()); addItemSt.setString(3, (item.getNodeName() != null ? item.getNodeName() : "")); addItemSt.setString(4, item.getKeyName()); addItemSt.setString(5, item.getConfigValToString()); addItemSt.setString(6, "" + DataTypes.getTypeId(item.getConfigVal())); addItemSt.setString(7, item.getFlag().name()); addItemSt.executeUpdate(); } } catch (SQLException e) { // Maybe the configuration item is already there, let's try to update it then try { checkConnection(); synchronized (updateItemSt) { updateItemSt.setString(1, item.getConfigValToString()); updateItemSt.setString(2, (item.getClusterNode() != null ? item.getClusterNode() : "")); updateItemSt.setString(3, item.getCompName()); updateItemSt.setString(4, (item.getNodeName() != null ? item.getNodeName() : "")); updateItemSt.setString(5, item.getKeyName()); updateItemSt.executeUpdate(); } } catch (SQLException ex) { try { // Maybe the configuration item is already there, let's try to update it then log.log(Level.WARNING, "Problem adding/updating an item to DB: " + item.toElement() + "\n", ex); log.log(Level.WARNING, "SQLWarning: " + updateItemSt.getWarnings().getMessage() + ", state: " + updateItemSt.getWarnings().getSQLState()); } catch (SQLException ex1) { Logger.getLogger(ConfigSQLRepository.class.getName()). log(Level.SEVERE, null, ex1); } } } catch (Exception e) { log.warning(e + "Exception while adding config item: " + item.toString()); } } private String[] getComponentNames() { List<String> result = new ArrayList<String>(); ResultSet rs = null; try { checkConnection(); synchronized (getCompNamesSt) { getCompNamesSt.setString(1, getDefHostname()); rs = getCompNamesSt.executeQuery(); while (rs.next()) { result.add(rs.getString(COMPONENT_NAME_COLUMN)); } } } catch (SQLException e) { log.log(Level.WARNING, "Problem getting component names from DB: ", e); } finally { release(null, rs); } return result.toArray(new String[result.size()]); } private int getPropertiesCount() { int result = 0; ResultSet rs = null; try { checkConnection(); synchronized (getPropertiesCountSt) { getPropertiesCountSt.setString(1, getDefHostname()); rs = getPropertiesCountSt.executeQuery(); while (rs.next()) { result = rs.getInt("count"); } } } catch (SQLException e) { log.log(Level.WARNING, "Problem getting elements count from DB: ", e); } finally { release(null, rs); } return result; } private String[] getKeys(String compName, String node) { List<String> result = new ArrayList<String>(); ResultSet rs = null; try { checkConnection(); synchronized (getKeysSt) { getKeysSt.setString(1, getDefHostname()); getKeysSt.setString(2, compName); getKeysSt.setString(3, node); rs = getKeysSt.executeQuery(); while (rs.next()) { result.add(rs.getString(KEY_NAME_COLUMN)); } } } catch (SQLException e) { log.log(Level.WARNING, "Problem getting keys from DB: ", e); } finally { release(null, rs); } return result.toArray(new String[result.size()]); } private void removeItem(ConfigItem item) { try { checkConnection(); synchronized (deleteItemSt) { deleteItemSt.setString(1, (item.getClusterNode() != null ? item.getClusterNode() : "")); deleteItemSt.setString(2, item.getCompName()); deleteItemSt.setString(3, (item.getNodeName() != null ? item.getNodeName() : "")); deleteItemSt.setString(4, item.getKeyName()); deleteItemSt.executeUpdate(); } } catch (SQLException e) { log.log(Level.WARNING, "Problem removing an item from DB: " + item.toElement(), e); } } } }
package tigase.net; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.channels.SelectableChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.Iterator; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.logging.Level; import java.util.logging.Logger; /** * Describe class ConnectionOpenThread here. * * * Created: Wed Jan 25 23:51:28 2006 * * @author <a href="mailto:artur.hefczyc@tigase.org">Artur Hefczyc</a> * @version $Rev$ */ public class ConnectionOpenThread implements Runnable { private static final Logger log = Logger.getLogger(ConnectionOpenThread.class.getName()); private static ConnectionOpenThread acceptThread = null; public static final long def_5222_throttling = 200; /** Field description */ public static final long def_5223_throttling = 50; /** Field description */ public static final long def_5280_throttling = 1000; /** Field description */ public static final long def_5269_throttling = 100; /** Field description */ public static Map<Integer, PortThrottlingData> throttling = new ConcurrentHashMap<Integer, PortThrottlingData>(10); protected long accept_counter = 0; private Selector selector = null; private boolean stopping = false; private Timer timer = null; private ConcurrentLinkedQueue<ConnectionOpenListener> waiting = new ConcurrentLinkedQueue<ConnectionOpenListener>(); /** * Creates a new <code>ConnectionOpenThread</code> instance. * */ private ConnectionOpenThread() { timer = new Timer("Connections open timer", true); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { for (PortThrottlingData portData : throttling.values()) { portData.lastSecondConnections = 0; } } }, 1000, 1000); try { selector = Selector.open(); } catch (Exception e) { log.log(Level.SEVERE, "Server I/O error, can't continue my work.", e); stopping = true; } // end of try-catch } /** * Method description * * * @return */ public static ConnectionOpenThread getInstance() { // Long new_throttling = Long.getLong("new-connections-throttling"); // if (new_throttling != null) { // throttling = new_throttling; // log.log(Level.WARNING, "New connections throttling set to: {0}", throttling); if (acceptThread == null) { acceptThread = new ConnectionOpenThread(); Thread thrd = new Thread(acceptThread); thrd.setName("ConnectionOpenThread"); thrd.start(); if (log.isLoggable(Level.FINER)) { log.finer("ConnectionOpenThread started."); } } // end of if (acceptThread == null) return acceptThread; } /** * Method description * * * @param al */ public void addConnectionOpenListener(ConnectionOpenListener al) { waiting.offer(al); selector.wakeup(); } /** * Method description * * * @param al */ public void removeConnectionOpenListener(ConnectionOpenListener al) { for (SelectionKey key : selector.keys()) { if (al == key.attachment()) { try { key.cancel(); SelectableChannel channel = key.channel(); channel.close(); } catch (Exception e) { log.log(Level.WARNING, "Exception during removing connection listener.", e); } break; } } } /** * Method description * */ @Override public void run() { while ( !stopping) { try { selector.select(); // Set<SelectionKey> selected_keys = selector.selectedKeys(); // for (SelectionKey sk : selected_keys) { for (Iterator i = selector.selectedKeys().iterator(); i.hasNext(); ) { SelectionKey sk = (SelectionKey) i.next(); i.remove(); SocketChannel sc = null; if ((sk.readyOps() & SelectionKey.OP_ACCEPT) != 0) { ServerSocketChannel nextReady = (ServerSocketChannel) sk.channel(); sc = nextReady.accept(); if (log.isLoggable(Level.FINEST)) { log.finest("OP_ACCEPT"); } PortThrottlingData port_throttling = throttling.get(nextReady.socket().getLocalPort()); if (port_throttling != null) { ++port_throttling.lastSecondConnections; if (port_throttling.lastSecondConnections > port_throttling.throttling) { if (log.isLoggable(Level.FINER)) { log.log(Level.FINER, "New connections throttling level exceeded, closing: {0}", sc); } sc.close(); sc = null; } } else { // Hm, this should not happen actually log.log(Level.WARNING, "Throttling not configured for port: {0}", nextReady.socket().getLocalPort()); } } // end of if (sk.readyOps() & SelectionKey.OP_ACCEPT) if ((sk.readyOps() & SelectionKey.OP_CONNECT) != 0) { sk.cancel(); sc = (SocketChannel) sk.channel(); if (log.isLoggable(Level.FINEST)) { log.finest("OP_CONNECT"); } } // end of if (sk.readyOps() & SelectionKey.OP_ACCEPT) if (sc != null) { // We have to catch exception here as sometimes socket is closed // or connection is broken before we start configuring it here // then whatever we do on the socket it throws an exception try { sc.configureBlocking(false); sc.socket().setSoLinger(false, 0); sc.socket().setReuseAddress(true); if (log.isLoggable(Level.FINER)) { log.log(Level.FINER, "Registered new client socket: {0}", sc); } ConnectionOpenListener al = (ConnectionOpenListener) sk.attachment(); sc.socket().setTrafficClass(al.getTrafficClass()); sc.socket().setReceiveBufferSize(al.getReceiveBufferSize()); al.accept(sc); } catch (java.net.SocketException e) { log.log(Level.INFO, "Socket closed instantly after it had been opened?", e); } } else { log.warning("Can't obtain socket channel from selection key."); } // end of if (sc != null) else ++accept_counter; } addAllWaiting(); } catch (IOException e) { log.log(Level.SEVERE, "Server I/O error.", e); // stopping = true; } // end of catch catch (Exception e) { log.log(Level.SEVERE, "Other service exception.", e); // stopping = true; } // end of catch } } /** * Method description * */ public void start() { Thread t = new Thread(this); t.setName("ConnectionOpenThread"); t.start(); } /** * Method description * */ public void stop() { stopping = true; selector.wakeup(); } private void addAllWaiting() throws IOException { ConnectionOpenListener al = null; while ((al = waiting.poll()) != null) { try { addPort(al); } catch (Exception e) { log.log(Level.WARNING, "Error: {0} creating connection for: {1}", new Object[] { e, al }); } // end of try-catch } // end of for () } private void addISA(InetSocketAddress isa, ConnectionOpenListener al) throws IOException { switch (al.getConnectionType()) { case accept : long port_throttling = getThrottlingForPort(isa.getPort()); throttling.put(isa.getPort(), new PortThrottlingData(port_throttling)); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Setting up throttling for the port {0} to {1} connections per second.", new Object[] { isa.getPort(), port_throttling }); } if (log.isLoggable(Level.FINEST)) { log.finest("Setting up 'accept' channel..."); } ServerSocketChannel ssc = ServerSocketChannel.open(); ssc.socket().setReceiveBufferSize(al.getReceiveBufferSize()); ssc.configureBlocking(false); ssc.socket().bind(isa); ssc.register(selector, SelectionKey.OP_ACCEPT, al); break; case connect : if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Setting up ''connect'' channel for: {0}/{1}", new Object[] { isa.getAddress(), isa.getPort() }); } SocketChannel sc = SocketChannel.open(); sc.socket().setReceiveBufferSize(al.getReceiveBufferSize()); sc.socket().setTrafficClass(al.getTrafficClass()); sc.configureBlocking(false); sc.connect(isa); sc.register(selector, SelectionKey.OP_CONNECT, al); break; default : log.log(Level.WARNING, "Unknown connection type: {0}", al.getConnectionType()); break; } // end of switch (al.getConnectionType()) } private void addPort(ConnectionOpenListener al) throws IOException { if ((al.getIfcs() == null) || (al.getIfcs().length == 0) || al.getIfcs()[0].equals("ifc") || al.getIfcs()[0].equals("*")) { addISA(new InetSocketAddress(al.getPort()), al); } else { for (String ifc : al.getIfcs()) { addISA(new InetSocketAddress(ifc, al.getPort()), al); } // end of for () } // end of if (ip == null || ip.equals("")) else } private long getThrottlingForPort(int port) { long result = def_5222_throttling; switch (port) { case 5223 : result = def_5223_throttling; break; case 5269 : result = def_5269_throttling; break; case 5280 : result = def_5280_throttling; break; } String throttling_prop = System.getProperty("new-connections-throttling"); if (throttling != null) { String[] all_ports_thr = throttling_prop.split(","); for (String port_thr : all_ports_thr) { String[] port_thr_ar = port_thr.split(":"); if (port_thr_ar.length == 2) { try { int port_no = Integer.parseInt(port_thr_ar[0]); if (port_no == port) { return Long.parseLong(port_thr_ar[1]); } } catch (Exception e) { // bad configuration log.log(Level.WARNING, "Connections throttling configuration error, bad format, " + "check the documentation for a correct syntax, " + "port throttling config: {0}", port_thr); } } else { // bad configuration log.log(Level.WARNING, "Connections throttling configuration error, bad format, " + "check the documentation for a correct syntax, " + "port throttling config: {0}", port_thr); } } } return result; } private class PortThrottlingData { /** Field description */ protected long lastSecondConnections = 0; /** Field description */ protected long throttling; /** * Constructs ... * * * @param throttling_prop */ private PortThrottlingData(long throttling_prop) { throttling = throttling_prop; } } } // ConnectionOpenThread //~ Formatted in Sun Code Convention
package net.bytebuddy.asm; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import net.bytebuddy.description.annotation.AnnotationDescription; import net.bytebuddy.description.method.MethodDescription; import net.bytebuddy.description.method.ParameterDescription; import net.bytebuddy.description.method.ParameterList; import net.bytebuddy.description.type.TypeDescription; import net.bytebuddy.dynamic.ClassFileLocator; import net.bytebuddy.implementation.bytecode.StackSize; import org.objectweb.asm.*; import java.io.IOException; import java.lang.annotation.*; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; public class Advice implements AsmVisitorWrapper.ForDeclaredMethods.MethodVisitorWrapper { /** * The dispatcher for instrumenting the instrumented method upon entering. */ private final Dispatcher.Resolved.ForMethodEnter methodEnter; /** * The dispatcher for instrumenting the instrumented method upon exiting. */ private final Dispatcher.Resolved.ForMethodExit methodExit; /** * The binary representation of the class containing the advice methods. */ private final byte[] binaryRepresentation; /** * Creates a new advice. * * @param methodEnter The dispatcher for instrumenting the instrumented method upon entering. * @param methodExit The dispatcher for instrumenting the instrumented method upon exiting. * @param binaryRepresentation The binary representation of the class containing the advice methods. */ protected Advice(Dispatcher.Resolved.ForMethodEnter methodEnter, Dispatcher.Resolved.ForMethodExit methodExit, byte[] binaryRepresentation) { this.methodEnter = methodEnter; this.methodExit = methodExit; this.binaryRepresentation = binaryRepresentation; } /** * Implements advice where every matched method is advised by the given type's advisory methods. The advises binary representation is * accessed by querying the class loader of the supplied class for a class file. * * @param type The type declaring the advice. * @return A method visitor wrapper representing the supplied advice. */ public static AsmVisitorWrapper.ForDeclaredMethods.MethodVisitorWrapper to(Class<?> type) { return to(type, ClassFileLocator.ForClassLoader.of(type.getClassLoader())); } /** * Implements advice where every matched method is advised by the given type's advisory methods. * * @param type The type declaring the advice. * @param classFileLocator The class file locator for locating the advisory class's class file. * @return A method visitor wrapper representing the supplied advice. */ public static AsmVisitorWrapper.ForDeclaredMethods.MethodVisitorWrapper to(Class<?> type, ClassFileLocator classFileLocator) { return to(new TypeDescription.ForLoadedType(type), classFileLocator); } /** * Implements advice where every matched method is advised by the given type's advisory methods. * * @param typeDescription A description of the type declaring the advice. * @param classFileLocator The class file locator for locating the advisory class's class file. * @return A method visitor wrapper representing the supplied advice. */ public static AsmVisitorWrapper.ForDeclaredMethods.MethodVisitorWrapper to(TypeDescription typeDescription, ClassFileLocator classFileLocator) { try { Dispatcher methodEnter = Dispatcher.Inactive.INSTANCE, methodExit = Dispatcher.Inactive.INSTANCE; for (MethodDescription.InDefinedShape methodDescription : typeDescription.getDeclaredMethods()) { methodEnter = resolve(OnMethodEnter.class, methodEnter, methodDescription); methodExit = resolve(OnMethodExit.class, methodExit, methodDescription); } if (!methodEnter.isAlive() && !methodExit.isAlive()) { throw new IllegalArgumentException("No advice defined by " + typeDescription); } Dispatcher.Resolved.ForMethodEnter resolved = methodEnter.asMethodEnter(); return new Advice(methodEnter.asMethodEnter(), methodExit.asMethodExitTo(resolved), classFileLocator.locate(typeDescription.getName()).resolve()); } catch (IOException exception) { throw new IllegalStateException("Error reading class file of " + typeDescription, exception); } } /** * Checks if a given method represents advise and does some basic validation. * * @param annotation The annotation that indicates a given type of advise. * @param dispatcher Any previous dispatcher. * @param methodDescription A description of the method considered as advise. * @return A dispatcher for the given method or the supplied dispatcher if the given method is not intended to be used as advise. */ private static Dispatcher resolve(Class<? extends Annotation> annotation, Dispatcher dispatcher, MethodDescription.InDefinedShape methodDescription) { if (methodDescription.getDeclaredAnnotations().isAnnotationPresent(annotation)) { if (dispatcher.isAlive()) { throw new IllegalStateException("Duplicate advice for " + dispatcher + " and " + methodDescription); } else if (!methodDescription.isStatic()) { throw new IllegalStateException("Advice for " + methodDescription + " is not static"); } return new Dispatcher.Active(methodDescription); } else { return dispatcher; } } @Override public MethodVisitor wrap(TypeDescription instrumentedType, MethodDescription.InDefinedShape methodDescription, MethodVisitor methodVisitor) { if (methodDescription.isAbstract() || methodDescription.isNative()) { throw new IllegalStateException("Cannot advice abstract or native method " + methodDescription); } return methodExit.isSkipThrowable() ? new AdviceVisitor.WithoutExceptionHandling(methodVisitor, methodDescription, methodEnter, methodExit, binaryRepresentation) : new AdviceVisitor.WithExceptionHandling(methodVisitor, methodDescription, methodEnter, methodExit, binaryRepresentation); } @Override public boolean equals(Object other) { if (this == other) return true; if (other == null || getClass() != other.getClass()) return false; Advice advice = (Advice) other; return methodEnter.equals(advice.methodEnter) && methodExit.equals(advice.methodExit) && Arrays.equals(binaryRepresentation, advice.binaryRepresentation); } @Override public int hashCode() { int result = methodEnter.hashCode(); result = 31 * result + methodExit.hashCode(); result = 31 * result + Arrays.hashCode(binaryRepresentation); return result; } @Override public String toString() { return "Advice{" + "methodEnter=" + methodEnter + ", methodExit=" + methodExit + ", binaryRepresentation=<" + binaryRepresentation.length + " bytes>" + '}'; } /** * A method visitor that weaves the advise methods' byte codes. */ protected abstract static class AdviceVisitor extends MethodVisitor { /** * Indicates a zero offset. */ private static final int NO_OFFSET = 0; /** * A description of the instrumented method. */ protected final MethodDescription.InDefinedShape instrumentedMethod; /** * The dispatcher to be used for method entry. */ private final Dispatcher.Resolved.ForMethodEnter methodEnter; /** * The dispatcher to be used for method exit. */ private final Dispatcher.Resolved.ForMethodExit methodExit; /** * A reader for traversing the advise methods' class file. */ private final ClassReader classReader; /** * Creates an advise visitor. * * @param methodVisitor The method visitor for the instrumented method. * @param instrumentedMethod A description of the instrumented method. * @param methodEnter The dispatcher to be used for method entry. * @param methodExit The dispatcher to be used for method exit. * @param binaryRepresentation The binary representation of the advise methods' class file. */ protected AdviceVisitor(MethodVisitor methodVisitor, MethodDescription.InDefinedShape instrumentedMethod, Dispatcher.Resolved.ForMethodEnter methodEnter, Dispatcher.Resolved.ForMethodExit methodExit, byte[] binaryRepresentation) { super(Opcodes.ASM5, methodVisitor); this.instrumentedMethod = instrumentedMethod; this.methodEnter = methodEnter; this.methodExit = methodExit; this.classReader = new ClassReader(binaryRepresentation); } @Override public void visitCode() { super.visitCode(); onMethodStart(); } /** * Writes the advise for entering the instrumented method. */ protected abstract void onMethodStart(); @Override public void visitVarInsn(int opcode, int offset) { super.visitVarInsn(opcode, offset < instrumentedMethod.getStackSize() ? offset : offset + methodEnter.getEnterType().getStackSize().getSize()); } @Override @SuppressFBWarnings(value = "SF_SWITCH_NO_DEFAULT", justification = "Switch is supposed to fall through") public void visitInsn(int opcode) { switch (opcode) { case Opcodes.RETURN: onMethodExit(); break; case Opcodes.IRETURN: onMethodExit(Opcodes.ISTORE, Opcodes.ILOAD); break; case Opcodes.FRETURN: onMethodExit(Opcodes.FSTORE, Opcodes.FLOAD); break; case Opcodes.DRETURN: onMethodExit(Opcodes.DSTORE, Opcodes.DLOAD); break; case Opcodes.LRETURN: onMethodExit(Opcodes.LSTORE, Opcodes.LLOAD); break; case Opcodes.ARETURN: onMethodExit(Opcodes.ASTORE, Opcodes.ALOAD); break; } mv.visitInsn(opcode); } /** * Writes the advise for the instrumented method's end. * * @param store The return type's store instruction. * @param load The return type's load instruction. */ private void onMethodExit(int store, int load) { variable(store); mv.visitInsn(Opcodes.ACONST_NULL); variable(Opcodes.ASTORE, instrumentedMethod.getReturnType().getStackSize().getSize()); onMethodExit(); variable(load); } /** * Writes the advise for exiting the instrumented method. */ protected abstract void onMethodExit(); /** * Access the first variable after the instrumented variables and return type are stored. * * @param opcode The opcode for accessing the variable. */ protected void variable(int opcode) { variable(opcode, NO_OFFSET); } /** * Access the first variable after the instrumented variables and return type are stored. * * @param opcode The opcode for accessing the variable. * @param offset The additional offset of the variable. */ protected void variable(int opcode, int offset) { mv.visitVarInsn(opcode, instrumentedMethod.getStackSize() + methodEnter.getEnterType().getStackSize().getSize() + offset); } @Override public void visitMaxs(int maxStack, int maxLocals) { onMethodEnd(); super.visitMaxs(maxStack, maxLocals); } /** * Writes the advise for completing the instrumented method. */ protected abstract void onMethodEnd(); /** * Appends the enter advise's byte code. */ protected void appendEnter() { append(methodEnter); } /** * Appends the exit advise's byte code. */ protected void appendExit() { append(methodExit); } /** * Appends the byte code of the supplied dispatcher. * * @param dispatcher The dispatcher for which the byte code should be appended. */ private void append(Dispatcher.Resolved dispatcher) { classReader.accept(new CodeCopier(dispatcher), ClassReader.SKIP_DEBUG); } /** * A visitor for copying an advise method's byte code. */ protected class CodeCopier extends ClassVisitor { /** * The dispatcher to use. */ private final Dispatcher.Resolved dispatcher; /** * Creates a new code copier. * * @param dispatcher The dispatcher to use. */ protected CodeCopier(Dispatcher.Resolved dispatcher) { super(Opcodes.ASM5); this.dispatcher = dispatcher; } @Override public MethodVisitor visitMethod(int modifiers, String internalName, String descriptor, String signature, String[] exception) { return dispatcher.apply(internalName, descriptor, mv, instrumentedMethod); } @Override public String toString() { return "Advice.AdviceVisitor.CodeCopier{" + "outer=" + AdviceVisitor.this + ", dispatcher=" + dispatcher + '}'; } } /** * An advise visitor that captures exceptions by weaving try-catch blocks around user code. */ protected static class WithExceptionHandling extends AdviceVisitor { /** * Indicates that any throwable should be captured. */ private static final String ANY_THROWABLE = null; /** * The label indicating the start of the exception handler. */ private final Label handler; /** * The current label that indicates the next section that terminates user code. */ private Label userEnd; /** * Creates a new advise visitor that captures exception by weaving try-catch blocks around user code. * * @param methodVisitor The method visitor for the instrumented method. * @param instrumentedMethod A description of the instrumented method. * @param methodEnter The dispatcher to be used for method entry. * @param methodExit The dispatcher to be used for method exit. * @param binaryRepresentation The binary representation of the advise methods' class file. */ protected WithExceptionHandling(MethodVisitor methodVisitor, MethodDescription.InDefinedShape instrumentedMethod, Dispatcher.Resolved.ForMethodEnter methodEnter, Dispatcher.Resolved.ForMethodExit methodExit, byte[] binaryRepresentation) { super(methodVisitor, instrumentedMethod, methodEnter, methodExit, binaryRepresentation); handler = new Label(); } @Override protected void onMethodStart() { appendEnter(); Label userStart = new Label(); userEnd = new Label(); mv.visitTryCatchBlock(userStart, userEnd, handler, null); mv.visitLabel(userStart); } @Override protected void onMethodExit() { mv.visitLabel(userEnd); appendExit(); Label userStart = new Label(); userEnd = new Label(); mv.visitTryCatchBlock(userStart, userEnd, handler, ANY_THROWABLE); mv.visitLabel(userStart); } @Override protected void onMethodEnd() { mv.visitLabel(userEnd); mv.visitLabel(handler); variable(Opcodes.ASTORE, instrumentedMethod.getReturnType().getStackSize().getSize()); storeDefaultReturn(); appendExit(); variable(Opcodes.ALOAD, instrumentedMethod.getReturnType().getStackSize().getSize()); mv.visitInsn(Opcodes.ATHROW); } /** * Stores a default return value in the designated slot of the local variable array. */ private void storeDefaultReturn() { if (instrumentedMethod.getReturnType().represents(boolean.class) || instrumentedMethod.getReturnType().represents(byte.class) || instrumentedMethod.getReturnType().represents(short.class) || instrumentedMethod.getReturnType().represents(char.class) || instrumentedMethod.getReturnType().represents(int.class)) { mv.visitInsn(Opcodes.ICONST_0); variable(Opcodes.ISTORE); } else if (instrumentedMethod.getReturnType().represents(long.class)) { mv.visitInsn(Opcodes.LCONST_0); variable(Opcodes.LSTORE); } else if (instrumentedMethod.getReturnType().represents(float.class)) { mv.visitInsn(Opcodes.FCONST_0); variable(Opcodes.FSTORE); } else if (instrumentedMethod.getReturnType().represents(double.class)) { mv.visitInsn(Opcodes.DCONST_0); variable(Opcodes.DSTORE); } else if (!instrumentedMethod.getReturnType().represents(void.class)) { mv.visitInsn(Opcodes.ACONST_NULL); variable(Opcodes.ASTORE); } } @Override public String toString() { return "Advice.AdviceVisitor.WithExceptionHandling{" + "instrumentedMethod=" + instrumentedMethod + '}'; } } /** * An advise visitor that does not capture exceptions. */ protected static class WithoutExceptionHandling extends AdviceVisitor { /** * Creates a new advise visitor that does not capture exceptions. * * @param methodVisitor The method visitor for the instrumented method. * @param instrumentedMethod A description of the instrumented method. * @param methodEnter The dispatcher to be used for method entry. * @param methodExit The dispatcher to be used for method exit. * @param binaryRepresentation The binary representation of the advise methods' class file. */ protected WithoutExceptionHandling(MethodVisitor methodVisitor, MethodDescription.InDefinedShape instrumentedMethod, Dispatcher.Resolved.ForMethodEnter methodEnter, Dispatcher.Resolved.ForMethodExit methodExit, byte[] binaryRepresentation) { super(methodVisitor, instrumentedMethod, methodEnter, methodExit, binaryRepresentation); } @Override protected void onMethodStart() { appendEnter(); } @Override protected void onMethodExit() { appendExit(); } @Override protected void onMethodEnd() { /* do nothing */ } @Override public String toString() { return "Advice.AdviceVisitor.WithoutExceptionHandling{" + "instrumentedMethod=" + instrumentedMethod + '}'; } } } /** * A dispatcher for implementing advise. */ protected interface Dispatcher { /** * Indicates that a method does not represent advise and does not need to be visited. */ MethodVisitor IGNORE_METHOD = null; /** * Returns {@code true} if this dispatcher is alive. * * @return {@code true} if this dispatcher is alive. */ boolean isAlive(); /** * Resolves this dispatcher as a dispatcher for entering a method. * * @return This dispatcher as a dispatcher for entering a method. */ Resolved.ForMethodEnter asMethodEnter(); /** * Resolves this dispatcher as a dispatcher for exiting a method. * * @param dispatcher The dispatcher for entering a method. * @return This dispatcher as a dispatcher for exiting a method. */ Resolved.ForMethodExit asMethodExitTo(Resolved.ForMethodEnter dispatcher); /** * Represents a resolved dispatcher. */ interface Resolved { /** * Applies this dispatcher for a method that is discovered in the advice class's class file. * * @param internalName The discovered method's internal name. * @param descriptor The discovered method's descriptor. * @param methodVisitor The method visitor for writing the instrumented method. * @param instrumentedMethod A description of the instrumented method. * @return A method visitor for reading the discovered method or {@code null} if the discovered method is of no interest. */ MethodVisitor apply(String internalName, String descriptor, MethodVisitor methodVisitor, MethodDescription.InDefinedShape instrumentedMethod); /** * Represents a resolved dispatcher for entering a method. */ interface ForMethodEnter extends Resolved { /** * Returns the type that this dispatcher supplies as a result of its advise or a description of {@code void} if * no type is supplied as a result of the enter advise. * * @return The type that this dispatcher supplies as a result of its advise or a description of {@code void}. */ TypeDescription getEnterType(); } /** * Represents a resolved dispatcher for exiting a method. */ interface ForMethodExit extends Resolved { /** * Indicates if this advise requires to be called when the instrumented method terminates exceptionally. * * @return {@code true} if this advise requires to be called when the instrumented method terminates exceptionally. */ boolean isSkipThrowable(); } } /** * An implementation for inactive devise that does not write any byte code. */ enum Inactive implements Dispatcher, Resolved.ForMethodEnter, Resolved.ForMethodExit { /** * The singleton instance. */ INSTANCE; @Override public boolean isAlive() { return false; } @Override public boolean isSkipThrowable() { return true; } @Override public TypeDescription getEnterType() { return TypeDescription.VOID; } @Override public Resolved.ForMethodEnter asMethodEnter() { return this; } @Override public Resolved.ForMethodExit asMethodExitTo(Resolved.ForMethodEnter dispatcher) { return this; } @Override public MethodVisitor apply(String internalName, String descriptor, MethodVisitor methodVisitor, MethodDescription.InDefinedShape instrumentedMethod) { return IGNORE_METHOD; } @Override public String toString() { return "Advice.Dispatcher.Inactive." + name(); } } /** * A dispatcher for active advise. */ class Active implements Dispatcher { /** * The advise method. */ protected final MethodDescription.InDefinedShape adviseMethod; /** * Creates a dispatcher for active advise. * * @param adviseMethod The advise method. */ protected Active(MethodDescription.InDefinedShape adviseMethod) { this.adviseMethod = adviseMethod; } @Override public boolean isAlive() { return true; } @Override public Dispatcher.Resolved.ForMethodEnter asMethodEnter() { return new Resolved.ForMethodEnter(adviseMethod); } @Override public Dispatcher.Resolved.ForMethodExit asMethodExitTo(Dispatcher.Resolved.ForMethodEnter dispatcher) { return new Resolved.ForMethodExit(adviseMethod, dispatcher.getEnterType()); } @Override public boolean equals(Object other) { return this == other || !(other == null || getClass() != other.getClass()) && adviseMethod.equals(((Active) other).adviseMethod); } @Override public int hashCode() { return adviseMethod.hashCode(); } @Override public String toString() { return "Advice.Dispatcher.Active{" + "adviseMethod=" + adviseMethod + '}'; } /** * A resolved version of a dispatcher. */ protected abstract static class Resolved implements Dispatcher.Resolved { /** * Indicates a read-only mapping for an offset. */ private static final boolean READ_ONLY = true; /** * The represented advise method. */ protected final MethodDescription.InDefinedShape adviseMethod; /** * An unresolved mapping of offsets of the advise method based on the annotations discovered on each method parameter. */ protected final Map<Integer, OffsetMapping> offsetMappings; /** * Creates a new resolved version of a dispatcher. * * @param adviseMethod The represented advise method. * @param factory An unresolved mapping of offsets of the advise method based on the annotations discovered on each method parameter. */ protected Resolved(MethodDescription.InDefinedShape adviseMethod, OffsetMapping.Factory... factory) { this.adviseMethod = adviseMethod; offsetMappings = new HashMap<Integer, OffsetMapping>(); for (ParameterDescription.InDefinedShape parameterDescription : adviseMethod.getParameters()) { OffsetMapping offsetMapping = OffsetMapping.Factory.UNDEFINED; for (OffsetMapping.Factory aFactory : factory) { OffsetMapping possible = aFactory.make(parameterDescription); if (possible != null) { if (offsetMapping == null) { offsetMapping = possible; } else { throw new IllegalStateException(parameterDescription + " is bound to both " + possible + " and " + offsetMapping); } } } offsetMappings.put(parameterDescription.getOffset(), offsetMapping == null ? new OffsetMapping.ForParameter(parameterDescription.getIndex(), READ_ONLY, parameterDescription.getType().asErasure()) : offsetMapping); } } @Override public MethodVisitor apply(String internalName, String descriptor, MethodVisitor methodVisitor, MethodDescription.InDefinedShape instrumentedMethod) { return adviseMethod.getInternalName().equals(internalName) && adviseMethod.getDescriptor().equals(descriptor) ? apply(methodVisitor, instrumentedMethod) : IGNORE_METHOD; } /** * Applies a resolution for a given instrumented method. * * @param methodVisitor A method visitor for writing byte code to the instrumented method. * @param instrumentedMethod A description of the instrumented method. * @return A method visitor for visiting the advise method's byte code. */ protected abstract MethodVisitor apply(MethodVisitor methodVisitor, MethodDescription.InDefinedShape instrumentedMethod); @Override public boolean equals(Object other) { if (this == other) return true; if (other == null || getClass() != other.getClass()) return false; Resolved resolved = (Resolved) other; return adviseMethod.equals(resolved.adviseMethod) && offsetMappings.equals(resolved.offsetMappings); } @Override public int hashCode() { int result = adviseMethod.hashCode(); result = 31 * result + offsetMappings.hashCode(); return result; } /** * Represents an offset mapping for an advise method to an alternative offset. */ interface OffsetMapping { /** * Resolves an offset mapping to a given target offset. * * @param instrumentedMethod The instrumented method for which the mapping is to be resolved. * @param additionalSize The additional size to consider before writing to any slot. * @return A suitable target mapping. */ Target resolve(MethodDescription.InDefinedShape instrumentedMethod, StackSize additionalSize); /** * A target offset of an offset mapping. */ interface Target { /** * Checks if this target supports a given opcode. * * @param opcode The opcode to check for its legitimacy. * @return {@code true} if this target supports the given opcode. */ boolean supports(int opcode); /** * Returns the mapped offset. * * @return The mapped offset. */ int getOffset(); /** * A read-write target mapping. */ class ReadWrite implements Target { /** * The mapped offset. */ private final int offset; /** * Creates a new read-write target mapping. * * @param offset The mapped offset. */ protected ReadWrite(int offset) { this.offset = offset; } @Override public boolean supports(int opcode) { return true; } @Override public int getOffset() { return offset; } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; ReadWrite readWrite = (ReadWrite) object; return offset == readWrite.offset; } @Override public int hashCode() { return offset; } @Override public String toString() { return "Advice.Dispatcher.Active.Resolved.OffsetMapping.Target.ReadWrite{" + "offset=" + offset + '}'; } } /** * A read-only target mapping. */ class ReadOnly implements Target { /** * The mapped offset. */ private final int offset; /** * Creates a new read-only target mapping. * * @param offset The mapped offset. */ protected ReadOnly(int offset) { this.offset = offset; } @Override public boolean supports(int opcode) { switch (opcode) { case Opcodes.ISTORE: case Opcodes.LSTORE: case Opcodes.FSTORE: case Opcodes.DSTORE: case Opcodes.ASTORE: return false; default: return true; } } @Override public int getOffset() { return offset; } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; ReadOnly readOnly = (ReadOnly) object; return offset == readOnly.offset; } @Override public int hashCode() { return offset; } @Override public String toString() { return "Advice.Dispatcher.Active.Resolved.OffsetMapping.Target.ReadOnly{" + "offset=" + offset + '}'; } } } /** * Represents a factory for creating a {@link OffsetMapping} for a given parameter. */ interface Factory { /** * Indicates that an offset mapping is undefined. */ OffsetMapping UNDEFINED = null; /** * Creates a new offset mapping for the supplied parameter if possible. * * @param parameterDescription The parameter description for which to resolve an offset mapping. * @return A resolved offset mapping or {@code null} if no mapping can be resolved for this parameter. */ OffsetMapping make(ParameterDescription.InDefinedShape parameterDescription); } /** * An offset mapping for a given parameter of the instrumented method. */ class ForParameter implements OffsetMapping { /** * The index of the parameter. */ private final int index; /** * Determines if the parameter is to be treated as read-only. */ private final boolean readOnly; /** * The type expected by the advise method. */ private final TypeDescription targetType; /** * Creates a new offset mapping for a parameter. * * @param argument The annotation for which the mapping is to be created. * @param targetType Determines if the parameter is to be treated as read-only. */ protected ForParameter(Argument argument, TypeDescription targetType) { this(argument.value(), argument.readOnly(), targetType); } /** * Creates a new offset mapping for a parameter of the instrumented method. * * @param index The index of the parameter. * @param readOnly Determines if the parameter is to be treated as read-only. * @param targetType The type expected by the advise method. */ protected ForParameter(int index, boolean readOnly, TypeDescription targetType) { this.index = index; this.readOnly = readOnly; this.targetType = targetType; } @Override public Target resolve(MethodDescription.InDefinedShape instrumentedMethod, StackSize additionalSize) { ParameterList<?> parameters = instrumentedMethod.getParameters(); if (parameters.size() <= index) { throw new IllegalStateException(instrumentedMethod + " does not define an index " + index); } else if (!readOnly && !parameters.get(index).getType().asErasure().equals(targetType)) { throw new IllegalStateException("read-only " + targetType + " is not equal to type of " + parameters.get(index)); } else if (readOnly && !parameters.get(index).getType().asErasure().isAssignableTo(targetType)) { throw new IllegalStateException(targetType + " is not assignable to " + parameters.get(index)); } return readOnly ? new Target.ReadOnly(parameters.get(index).getOffset()) : new Target.ReadWrite(parameters.get(index).getOffset()); } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; ForParameter that = (ForParameter) object; return index == that.index && readOnly == that.readOnly && targetType.equals(that.targetType); } @Override public int hashCode() { int result = index; result = 31 * result + (readOnly ? 1 : 0); result = 31 * result + targetType.hashCode(); return result; } @Override public String toString() { return "Advice.Dispatcher.Active.Resolved.OffsetMapping.ForParameter{" + "index=" + index + ", readOnly=" + readOnly + ", targetType=" + targetType + '}'; } /** * A factory for creating a {@link ForParameter} offset mapping. */ protected enum Factory implements OffsetMapping.Factory { /** * The singleton instance. */ INSTANCE; @Override public OffsetMapping make(ParameterDescription.InDefinedShape parameterDescription) { AnnotationDescription.Loadable<Argument> annotation = parameterDescription.getDeclaredAnnotations().ofType(Argument.class); return annotation == null ? UNDEFINED : new ForParameter(annotation.loadSilent(), parameterDescription.getType().asErasure()); } @Override public String toString() { return "Advice.Dispatcher.Active.Resolved.OffsetMapping.ForParameter.Factory." + name(); } } } /** * An offset mapping that provides access to the {@code this} reference of the instrumented method. */ class ForThisReference implements OffsetMapping { /** * The offset of the this reference in a Java method. */ private static final int THIS_REFERENCE = 0; /** * Determines if the parameter is to be treated as read-only. */ private final boolean readOnly; /** * The type that the advise method expects for the {@code this} reference. */ private final TypeDescription targetType; /** * Creates a new offset mapping for a {@code this} reference. * * @param readOnly Determines if the parameter is to be treated as read-only. * @param targetType The type that the advise method expects for the {@code this} reference. */ protected ForThisReference(boolean readOnly, TypeDescription targetType) { this.readOnly = readOnly; this.targetType = targetType; } @Override public Target resolve(MethodDescription.InDefinedShape instrumentedMethod, StackSize additionalSize) { if (instrumentedMethod.isStatic()) { throw new IllegalStateException("Cannot map this reference for static method " + instrumentedMethod); } else if (!readOnly && !instrumentedMethod.getDeclaringType().equals(targetType)) { throw new IllegalStateException("Declaring type of " + instrumentedMethod + " is not equal to read-only " + targetType); } else if (readOnly && !instrumentedMethod.getDeclaringType().isAssignableTo(targetType)) { throw new IllegalStateException("Declaring type of " + instrumentedMethod + " is not assignable to " + targetType); } return readOnly ? new Target.ReadOnly(THIS_REFERENCE) : new Target.ReadWrite(THIS_REFERENCE); } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; ForThisReference that = (ForThisReference) object; return readOnly == that.readOnly && targetType.equals(that.targetType); } @Override public int hashCode() { int result = (readOnly ? 1 : 0); result = 31 * result + targetType.hashCode(); return result; } @Override public String toString() { return "Advice.Dispatcher.Active.Resolved.OffsetMapping.ForThisReference{" + "readOnly=" + readOnly + ", targetType=" + targetType + '}'; } /** * A factory for creating a {@link ForThisReference} offset mapping. */ protected enum Factory implements OffsetMapping.Factory { /** * The singleton instance. */ INSTANCE; @Override public OffsetMapping make(ParameterDescription.InDefinedShape parameterDescription) { AnnotationDescription.Loadable<This> annotation = parameterDescription.getDeclaredAnnotations().ofType(This.class); return annotation == null ? UNDEFINED : new ForThisReference(annotation.loadSilent().readOnly(), parameterDescription.getType().asErasure()); } @Override public String toString() { return "Advice.Dispatcher.Active.Resolved.OffsetMapping.ForThisReference.Factory." + name(); } } } /** * An offset mapping that provides access to the value that is returned by the enter advise. */ enum ForEnterValue implements OffsetMapping { /** * Enables writing to the mapped offset. */ WRITABLE(false), /** * Only allows for reading the mapped offset. */ READ_ONLY(true); /** * Determines if the parameter is to be treated as read-only. */ private final boolean readOnly; /** * Creates a new offset mapping for an enter value. * * @param readOnly Determines if the parameter is to be treated as read-only. */ ForEnterValue(boolean readOnly) { this.readOnly = readOnly; } /** * Resolves an offset mapping for an enter value. * * @param readOnly {@code true} if the value is to be treated as read-only. * @return An appropriate offset mapping. */ public static OffsetMapping of(boolean readOnly) { return readOnly ? READ_ONLY : WRITABLE; } @Override public Target resolve(MethodDescription.InDefinedShape instrumentedMethod, StackSize additionalSize) { return readOnly ? new Target.ReadOnly(instrumentedMethod.getStackSize()) : new Target.ReadWrite(instrumentedMethod.getStackSize()); } @Override public String toString() { return "Advice.Dispatcher.Active.Resolved.OffsetMapping.ForEnterValue." + name(); } /** * A factory for creating a {@link ForEnterValue} offset mapping. */ protected static class Factory implements OffsetMapping.Factory { /** * The supplied type of the enter method. */ private final TypeDescription enterType; /** * Creates a new factory for creating a {@link ForEnterValue} offset mapping. * * @param enterType The supplied type of the enter method. */ protected Factory(TypeDescription enterType) { this.enterType = enterType; } @Override public OffsetMapping make(ParameterDescription.InDefinedShape parameterDescription) { AnnotationDescription.Loadable<Enter> annotation = parameterDescription.getDeclaredAnnotations().ofType(Enter.class); if (annotation != null) { boolean readOnly = annotation.loadSilent().readOnly(); if (!readOnly && !enterType.equals(parameterDescription.getType().asErasure())) { throw new IllegalStateException("read-only type of " + parameterDescription + " does not equal " + enterType); } else if (readOnly && !enterType.isAssignableTo(parameterDescription.getType().asErasure())) { throw new IllegalStateException("Cannot assign the type of " + parameterDescription + " to supplied type " + enterType); } return ForEnterValue.of(readOnly); } else { return UNDEFINED; } } @Override public boolean equals(Object other) { return this == other || !(other == null || getClass() != other.getClass()) && enterType.equals(((Factory) other).enterType); } @Override public int hashCode() { return enterType.hashCode(); } @Override public String toString() { return "Advice.Dispatcher.Active.Resolved.OffsetMapping.ForEnterValue.Factory{" + "enterType=" + enterType + '}'; } } } /** * An offset mapping that provides access to the value that is returned by the instrumented method. */ class ForReturnValue implements OffsetMapping { /** * Determines if the parameter is to be treated as read-only. */ private final boolean readOnly; /** * The type that the advise method expects for the {@code this} reference. */ private final TypeDescription targetType; /** * Creates an offset mapping for accessing the return type of the instrumented method. * * @param readOnly Determines if the parameter is to be treated as read-only. * @param targetType The expected target type of the return type. */ protected ForReturnValue(boolean readOnly, TypeDescription targetType) { this.readOnly = readOnly; this.targetType = targetType; } @Override public Target resolve(MethodDescription.InDefinedShape instrumentedMethod, StackSize additionalSize) { if (!readOnly && !instrumentedMethod.getReturnType().asErasure().equals(targetType)) { throw new IllegalStateException("read-only return type of " + instrumentedMethod + " is not equal to " + targetType); } else if (readOnly && !instrumentedMethod.getReturnType().asErasure().isAssignableTo(targetType)) { throw new IllegalStateException("Cannot assign return type of " + instrumentedMethod + " to " + targetType); } return readOnly ? new Target.ReadOnly(instrumentedMethod.getStackSize() + additionalSize.getSize()) : new Target.ReadWrite(instrumentedMethod.getStackSize() + additionalSize.getSize()); } @Override public boolean equals(Object other) { if (this == other) return true; if (other == null || getClass() != other.getClass()) return false; ForReturnValue that = (ForReturnValue) other; return readOnly == that.readOnly && targetType.equals(that.targetType); } @Override public int hashCode() { return (readOnly ? 1 : 0) + 31 * targetType.hashCode(); } @Override public String toString() { return "Advice.Dispatcher.Active.Resolved.OffsetMapping.ForReturnValue{" + "readOnly=" + readOnly + ", targetType=" + targetType + '}'; } /** * A factory for creating a {@link ForReturnValue} offset mapping. */ protected enum Factory implements OffsetMapping.Factory { /** * The singleton instance. */ INSTANCE; @Override public OffsetMapping make(ParameterDescription.InDefinedShape parameterDescription) { AnnotationDescription.Loadable<Return> annotation = parameterDescription.getDeclaredAnnotations().ofType(Return.class); return annotation == null ? UNDEFINED : new ForReturnValue(annotation.loadSilent().readOnly(), parameterDescription.getType().asErasure()); } @Override public String toString() { return "Advice.Dispatcher.Active.Resolved.OffsetMapping.ForReturnValue.Factory." + name(); } } } /** * An offset mapping for accessing a {@link Throwable} of the instrumented method. */ enum ForThrowable implements OffsetMapping, Factory { /** * The singleton instance. */ INSTANCE; @Override public OffsetMapping make(ParameterDescription.InDefinedShape parameterDescription) { if (parameterDescription.getDeclaredAnnotations().isAnnotationPresent(Thrown.class)) { if (!parameterDescription.getType().represents(Throwable.class)) { throw new IllegalStateException("Parameter must be of type Throwable for " + parameterDescription); } return this; } else { return UNDEFINED; } } @Override public Target resolve(MethodDescription.InDefinedShape instrumentedMethod, StackSize additionalSize) { return new Target.ReadWrite(instrumentedMethod.getStackSize() + additionalSize.getSize() + instrumentedMethod.getReturnType().getStackSize().getSize()); } @Override public String toString() { return "Advice.Dispatcher.Active.Resolved.OffsetMapping.ForThrowable." + name(); } } class Illegal implements Factory { private final List<? extends Class<? extends Annotation>> annotations; //@SafeVarargs protected Illegal(Class<? extends Annotation>... annotation) { this(Arrays.asList(annotation)); } protected Illegal(List<? extends Class<? extends Annotation>> annotations) { this.annotations = annotations; } @Override public OffsetMapping make(ParameterDescription.InDefinedShape parameterDescription) { for (Class<? extends Annotation> annotation : annotations) { if (parameterDescription.getDeclaredAnnotations().isAnnotationPresent(annotation)) { throw new IllegalStateException("Illegal annotation " + annotation + " for " + parameterDescription); } } return UNDEFINED; } @Override public boolean equals(Object other) { if (this == other) return true; if (other == null || getClass() != other.getClass()) return false; Illegal illegal = (Illegal) other; return annotations.equals(illegal.annotations); } @Override public int hashCode() { return annotations.hashCode(); } @Override public String toString() { return "Advice.Dispatcher.Active.Resolved.OffsetMapping.Illegal{" + "annotations=" + annotations + '}'; } } } /** * A resolved dispatcher for implementing method enter advise. */ protected static class ForMethodEnter extends Resolved implements Dispatcher.Resolved.ForMethodEnter { /** * Creates a new resolved dispatcher for implementing method enter advise. * * @param adviseMethod The represented advise method. */ @SuppressWarnings("all") // In absence of @SafeVarargs for Java 6 protected ForMethodEnter(MethodDescription.InDefinedShape adviseMethod) { super(adviseMethod, OffsetMapping.ForParameter.Factory.INSTANCE, OffsetMapping.ForThisReference.Factory.INSTANCE, new OffsetMapping.Illegal(Thrown.class, Enter.class, Return.class)); } @Override public TypeDescription getEnterType() { return adviseMethod.getReturnType().asErasure(); } @Override protected MethodVisitor apply(MethodVisitor methodVisitor, MethodDescription.InDefinedShape instrumentedMethod) { Map<Integer, OffsetMapping.Target> offsetMappings = new HashMap<Integer, OffsetMapping.Target>(); for (Map.Entry<Integer, OffsetMapping> entry : this.offsetMappings.entrySet()) { offsetMappings.put(entry.getKey(), entry.getValue().resolve(instrumentedMethod, StackSize.ZERO)); } return new CodeTranslationVisitor.ReturnValueRetaining(methodVisitor, instrumentedMethod, adviseMethod, offsetMappings); } @Override public String toString() { return "Advice.Dispatcher.Active.Resolved.ForMethodEnter{" + "adviseMethod=" + adviseMethod + ", offsetMappings=" + offsetMappings + '}'; } } /** * A resolved dispatcher for implementing method exit advise. */ protected static class ForMethodExit extends Resolved implements Dispatcher.Resolved.ForMethodExit { /** * The additional stack size to consider when accessing the local variable array. */ private final StackSize additionalSize; /** * Creates a new resolved dispatcher for implementing method exit advise. * * @param adviseMethod The represented advise method. * @param enterType The type of the value supplied by the enter advise method or a description of {@code void} if * no such value exists. */ @SuppressWarnings("all") // In absence of @SafeVarargs for Java 6 protected ForMethodExit(MethodDescription.InDefinedShape adviseMethod, TypeDescription enterType) { super(adviseMethod, OffsetMapping.ForParameter.Factory.INSTANCE, OffsetMapping.ForThisReference.Factory.INSTANCE, new OffsetMapping.ForEnterValue.Factory(enterType), OffsetMapping.ForReturnValue.Factory.INSTANCE, adviseMethod.getDeclaredAnnotations().ofType(OnMethodExit.class).loadSilent().onThrowable() ? OffsetMapping.ForThrowable.INSTANCE : new OffsetMapping.Illegal(Thrown.class)); additionalSize = enterType.getStackSize(); } @Override public boolean isSkipThrowable() { return !adviseMethod.getDeclaredAnnotations().ofType(OnMethodExit.class).loadSilent().onThrowable(); } @Override protected MethodVisitor apply(MethodVisitor methodVisitor, MethodDescription.InDefinedShape instrumentedMethod) { Map<Integer, OffsetMapping.Target> offsetMappings = new HashMap<Integer, OffsetMapping.Target>(); for (Map.Entry<Integer, OffsetMapping> entry : this.offsetMappings.entrySet()) { offsetMappings.put(entry.getKey(), entry.getValue().resolve(instrumentedMethod, additionalSize)); } return new CodeTranslationVisitor.ReturnValueDiscarding(methodVisitor, instrumentedMethod, adviseMethod, offsetMappings, additionalSize); } @Override public boolean equals(Object other) { return this == other || !(other == null || getClass() != other.getClass()) && super.equals(other) && additionalSize == ((Resolved.ForMethodExit) other).additionalSize; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + additionalSize.hashCode(); return result; } @Override public String toString() { return "Advice.Dispatcher.Active.Resolved.ForMethodExit{" + "adviseMethod=" + adviseMethod + ", offsetMappings=" + offsetMappings + ", additionalSize=" + additionalSize + '}'; } } } /** * A visitor for translating an advise method's byte code for inlining into the instrumented method. */ protected abstract static class CodeTranslationVisitor extends MethodVisitor { /** * Indicates that an annotation should not be read. */ private static final AnnotationVisitor IGNORE_ANNOTATION = null; /** * The instrumented method. */ protected final MethodDescription.InDefinedShape instrumentedMethod; /** * The advise method. */ protected final MethodDescription.InDefinedShape adviseMethod; /** * A mapping of offsets to resolved target offsets in the instrumented method. */ private final Map<Integer, Resolved.OffsetMapping.Target> offsetMappings; /** * A label indicating the end of the advise byte code. */ protected final Label endOfMethod; /** * Creates a new code translation visitor. * * @param methodVisitor A method visitor for writing the instrumented method's byte code. * @param instrumentedMethod The instrumented method. * @param adviseMethod The advise method. * @param offsetMappings A mapping of offsets to resolved target offsets in the instrumented method. */ protected CodeTranslationVisitor(MethodVisitor methodVisitor, MethodDescription.InDefinedShape instrumentedMethod, MethodDescription.InDefinedShape adviseMethod, Map<Integer, Resolved.OffsetMapping.Target> offsetMappings) { super(Opcodes.ASM5, methodVisitor); this.instrumentedMethod = instrumentedMethod; this.adviseMethod = adviseMethod; this.offsetMappings = offsetMappings; endOfMethod = new Label(); } @Override public void visitParameter(String name, int modifiers) { /* do nothing */ } @Override public AnnotationVisitor visitAnnotationDefault() { return IGNORE_ANNOTATION; } @Override public AnnotationVisitor visitAnnotation(String descriptor, boolean visible) { return IGNORE_ANNOTATION; } @Override public AnnotationVisitor visitTypeAnnotation(int typeReference, TypePath typePath, String descriptor, boolean visible) { return IGNORE_ANNOTATION; } @Override public AnnotationVisitor visitParameterAnnotation(int index, String descriptor, boolean visible) { return IGNORE_ANNOTATION; } @Override public void visitAttribute(Attribute attr) { /* do nothing */ } @Override public void visitCode() { /* do nothing */ } @Override public void visitFrame(int type, int nLocal, Object[] local, int nStack, Object[] stack) { /* do nothing */ } @Override public void visitLineNumber(int line, Label start) { /* do nothing */ } @Override public void visitEnd() { mv.visitLabel(endOfMethod); } @Override public void visitMaxs(int maxStack, int maxLocals) { /* do nothing */ } @Override public void visitVarInsn(int opcode, int offset) { Resolved.OffsetMapping.Target target = offsetMappings.get(offset); if (target != null) { if (!target.supports(opcode)) { throw new IllegalStateException("Cannot write to read-only variable " + target); } offset = target.getOffset(); } else { offset = adjust(offset + instrumentedMethod.getStackSize() - adviseMethod.getStackSize()); } super.visitVarInsn(opcode, offset); } /** * Adjusts the offset of a variable instruction within the advise method such that no arguments to * the instrumented method are overridden. * * @param offset The original offset. * @return The adjusted offset. */ protected abstract int adjust(int offset); @Override public abstract void visitInsn(int opcode); /** * A code translation visitor that retains the return value of the represented advise method. */ protected static class ReturnValueRetaining extends CodeTranslationVisitor { /** * Creates a new code translation visitor that retains the return value of the enter advise. * * @param methodVisitor A method visitor for writing the instrumented method's byte code. * @param instrumentedMethod The instrumented method. * @param adviseMethod The advise method. * @param offsetMappings A mapping of offsets of the advise methods to their corresponding offsets in the instrumented method. */ protected ReturnValueRetaining(MethodVisitor methodVisitor, MethodDescription.InDefinedShape instrumentedMethod, MethodDescription.InDefinedShape adviseMethod, Map<Integer, Resolved.OffsetMapping.Target> offsetMappings) { super(methodVisitor, instrumentedMethod, adviseMethod, offsetMappings); } @Override public void visitInsn(int opcode) { switch (opcode) { case Opcodes.RETURN: break; case Opcodes.IRETURN: mv.visitVarInsn(Opcodes.ISTORE, instrumentedMethod.getStackSize()); break; case Opcodes.LRETURN: mv.visitVarInsn(Opcodes.LSTORE, instrumentedMethod.getStackSize()); break; case Opcodes.ARETURN: mv.visitVarInsn(Opcodes.ASTORE, instrumentedMethod.getStackSize()); break; case Opcodes.FRETURN: mv.visitVarInsn(Opcodes.FSTORE, instrumentedMethod.getStackSize()); break; case Opcodes.DRETURN: mv.visitVarInsn(Opcodes.DSTORE, instrumentedMethod.getStackSize()); break; default: mv.visitInsn(opcode); return; } mv.visitJumpInsn(Opcodes.GOTO, endOfMethod); } @Override protected int adjust(int offset) { return offset; } @Override public String toString() { return "Advice.Dispatcher.Active.CodeTranslationVisitor.ReturnValueRetaining{" + "instrumentedMethod=" + instrumentedMethod + ", adviseMethod=" + adviseMethod + '}'; } } /** * A code translation visitor that discards the return value of the represented advise method. */ protected static class ReturnValueDiscarding extends CodeTranslationVisitor { /** * An additional size of the local variable array to consider when writing or reading values. */ private final StackSize additionalVariableSize; /** * Creates a new code translation visitor that retains the return value of the enter advise. * * @param methodVisitor A method visitor for writing the instrumented method's byte code. * @param instrumentedMethod The instrumented method. * @param adviseMethod The advise method. * @param offsetMappings A mapping of offsets of the advise methods to their corresponding offsets in the instrumented method. * @param additionalVariableSize An additional size of the local variable array to consider when writing or reading values. */ protected ReturnValueDiscarding(MethodVisitor methodVisitor, MethodDescription.InDefinedShape instrumentedMethod, MethodDescription.InDefinedShape adviseMethod, Map<Integer, Resolved.OffsetMapping.Target> offsetMappings, StackSize additionalVariableSize) { super(methodVisitor, instrumentedMethod, adviseMethod, offsetMappings); this.additionalVariableSize = additionalVariableSize; } @Override public void visitInsn(int opcode) { switch (opcode) { case Opcodes.RETURN: break; case Opcodes.IRETURN: case Opcodes.ARETURN: case Opcodes.FRETURN: mv.visitInsn(Opcodes.POP); break; case Opcodes.LRETURN: case Opcodes.DRETURN: mv.visitInsn(Opcodes.POP2); break; default: mv.visitInsn(opcode); return; } mv.visitJumpInsn(Opcodes.GOTO, endOfMethod); } @Override protected int adjust(int offset) { return offset + instrumentedMethod.getReturnType().getStackSize().getSize() + additionalVariableSize.getSize() + 1; } @Override public String toString() { return "Advice.Dispatcher.Active.CodeTranslationVisitor.ReturnValueDiscarding{" + "instrumentedMethod=" + instrumentedMethod + ", adviseMethod=" + adviseMethod + ", additionalVariableSize=" + additionalVariableSize + '}'; } } } } } /** * <p> * Indicates that this method should be inlined before the matched method is invoked. Any class must declare * at most one method with this annotation. The annotated method must be static. When instrumenting constructors, * the {@code this} values can only be accessed for writing fields but not for reading fields or invoking methods. * </p> * <p> * The annotated method can return a value that is made accessible to another method annotated by {@link OnMethodExit}. * </p> * * @see Advice * @see Argument * @see This */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface OnMethodEnter { /* empty */ } /** * <p> * Indicates that this method should be inlined before the matched method is invoked. Any class must declare * at most one method with this annotation. The annotated method must be static. * </p> * <p> * The annotated method can imply to not be invoked when the instrumented method terminates exceptionally by * setting the {@link OnMethodExit#onThrowable()} property. * </p> * * @see Advice * @see Argument * @see This * @see Enter * @see Return * @see Thrown */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface OnMethodExit { /** * Indicates that the advise method should also be called when a method terminates exceptionally. * * @return {@code true} if the advise method should be invoked when a method terminates exceptionally. */ boolean onThrowable() default true; } /** * Indicates that the annotated parameter should be mapped to the parameter with index {@link Argument#value()} of * the instrumented method. * * @see Advice * @see OnMethodEnter * @see OnMethodExit */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.PARAMETER) public @interface Argument { /** * Returns the index of the mapped parameter. * * @return The index of the mapped parameter. */ int value(); /** * Indicates if it is possible to write to this parameter. If this property is set to {@code false}, the annotated * type must be equal to the parameter of the instrumented method. If this property is set to {@code true}, the * annotated parameter can be any super type of the instrumented methods parameter. * * @return {@code true} if this parameter is read-only. */ boolean readOnly() default true; } /** * Indicates that the annotated parameter should be mapped to the {@code this} reference of the instrumented method. * * @see Advice * @see OnMethodEnter * @see OnMethodExit */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.PARAMETER) public @interface This { /** * Indicates if it is possible to write to this parameter. If this property is set to {@code false}, the annotated * type must be equal to the parameter of the instrumented method. If this property is set to {@code true}, the * annotated parameter can be any super type of the instrumented methods parameter. * * @return {@code true} if this parameter is read-only. */ boolean readOnly() default true; } /** * Indicates that the annotated parameter should be mapped to the value that is returned by the advise method that is annotated * by {@link OnMethodEnter}. * * @see Advice * @see OnMethodExit */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.PARAMETER) public @interface Enter { /** * Indicates if it is possible to write to this parameter. If this property is set to {@code false}, the annotated * type must be equal to the parameter of the instrumented method. If this property is set to {@code true}, the * annotated parameter can be any super type of the instrumented methods parameter. * * @return {@code true} if this parameter is read-only. */ boolean readOnly() default true; } /** * Indicates that the annotated parameter should be mapped to the return value of the instrumented method. If the instrumented * method terminates exceptionally, the type's default value is assigned to the parameter, i.e. {@code 0} for numeric types * and {@code null} for reference types. * * @see Advice * @see OnMethodExit */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.PARAMETER) public @interface Return { /** * Indicates if it is possible to write to this parameter. If this property is set to {@code false}, the annotated * type must be equal to the parameter of the instrumented method. If this property is set to {@code true}, the * annotated parameter can be any super type of the instrumented methods parameter. * * @return {@code true} if this parameter is read-only. */ boolean readOnly() default true; } /** * Indicates that the annotated parameter should be mapped to the return value of the instrumented method. For this to be valid, * the parameter must be of type {@link Throwable}. If the instrumented method terminates regularly, {@code null} is assigned to * the annotated parameter. * * @see Advice * @see OnMethodExit */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.PARAMETER) public @interface Thrown { /* empty */ } }
package dr.evomodel.operators; import dr.evolution.tree.MutableTree; import dr.evolution.tree.NodeRef; import dr.evomodel.tree.TreeModel; import dr.inference.operators.MCMCOperator; import dr.inference.operators.OperatorFailedException; import dr.math.MathUtils; import dr.xml.*; /** * Implements branch exchange operations. There is a NARROW and WIDE variety. * The narrow exchange is very similar to a rooted-tree nearest-neighbour * interchange but with the restriction that node height must remain consistent. * <p/> * KNOWN BUGS: WIDE operator cannot be used on trees with 4 or less tips! */ public class ExchangeOperator extends AbstractTreeOperator { public static final String NARROW_EXCHANGE = "narrowExchange"; public static final String WIDE_EXCHANGE = "wideExchange"; public static final String INTERMEDIATE_EXCHANGE = "intermediateExchange"; public static final int NARROW = 0; public static final int WIDE = 1; public static final int INTERMEDIATE = 2; private static final int MAX_TRIES = 100; private int mode = NARROW; private final TreeModel tree; private double[] distances; public ExchangeOperator(int mode, TreeModel tree, double weight) { this.mode = mode; this.tree = tree; setWeight(weight); } public double doOperation() throws OperatorFailedException { final int tipCount = tree.getExternalNodeCount(); double hastingsRatio = 0; switch( mode ) { case NARROW: narrow(); break; case WIDE: wide(); break; case INTERMEDIATE: hastingsRatio = intermediate(); break; } assert tree.getExternalNodeCount() == tipCount : "Lost some tips in " + ((mode == NARROW) ? "NARROW mode." : "WIDE mode."); return hastingsRatio; } /** * WARNING: Assumes strictly bifurcating tree. */ public void narrow() throws OperatorFailedException { final int nNodes = tree.getNodeCount(); final NodeRef root = tree.getRoot(); NodeRef i = tree.getNode(MathUtils.nextInt(nNodes)); while( root == i || tree.getParent(i) == root ) { i = tree.getNode(MathUtils.nextInt(nNodes)); } final NodeRef iParent = tree.getParent(i); final NodeRef iGrandParent = tree.getParent(iParent); NodeRef iUncle = tree.getChild(iGrandParent, 0); if( iUncle == iParent ) { iUncle = tree.getChild(iGrandParent, 1); } assert tree.getNodeHeight(i) < tree.getNodeHeight(iGrandParent); if( tree.getNodeHeight(iUncle) < tree.getNodeHeight(iParent) ) { eupdate(i, iUncle, iParent, iGrandParent); // tree.pushTreeChangedEvent(iParent); // tree.pushTreeChangedEvent(iGrandParent); return; } // System.out.println("tries = " + tries); throw new OperatorFailedException( "Couldn't find valid narrow move on this tree!!"); } /** * WARNING: Assumes strictly bifurcating tree. */ public void wide() throws OperatorFailedException { final int nodeCount = tree.getNodeCount(); final NodeRef root = tree.getRoot(); NodeRef i = root; while( root == i ) { i = tree.getNode(MathUtils.nextInt(nodeCount)); } NodeRef j = i; // tree.getNode(MathUtils.nextInt(nodeCount)); while( j == i || j == root ) { j = tree.getNode(MathUtils.nextInt(nodeCount)); } final NodeRef iP = tree.getParent(i); final NodeRef jP = tree.getParent(j); if( (iP != jP) && (i != jP) && (j != iP) && (tree.getNodeHeight(j) < tree.getNodeHeight(iP)) && (tree.getNodeHeight(i) < tree.getNodeHeight(jP)) ) { eupdate(i, j, iP, jP); // System.out.println("tries = " + tries+1); return; } throw new OperatorFailedException( "Couldn't find valid wide move on this tree!"); } /** * @deprecated WARNING: SHOULD NOT BE USED! * WARNING: Assumes strictly bifurcating tree. */ public double intermediate() throws OperatorFailedException { final int nodeCount = tree.getNodeCount(); final NodeRef root = tree.getRoot(); for(int tries = 0; tries < MAX_TRIES; ++tries) { NodeRef i, j; NodeRef[] possibleNodes; do { // get a random node i = root; // tree.getNode(MathUtils.nextInt(nodeCount)); // if (root != i) { // possibleNodes = tree.getNodes(); // check if we got the root while( root == i ) { // if so get another one till we haven't got anymore the // root i = tree.getNode(MathUtils.nextInt(nodeCount)); // if (root != i) { // possibleNodes = tree.getNodes(); } possibleNodes = tree.getNodes(); // get another random node // NodeRef j = tree.getNode(MathUtils.nextInt(nodeCount)); j = getRandomNode(possibleNodes, i); // check if they are the same and if the new node is the root } while( j == null || j == i || j == root ); double forward = getWinningChance(indexOf(possibleNodes, j)); // possibleNodes = getPossibleNodes(j); calcDistances(possibleNodes, j); forward += getWinningChance(indexOf(possibleNodes, i)); // get the parent of both of them final NodeRef iP = tree.getParent(i); final NodeRef jP = tree.getParent(j); // check if both parents are equal -> we are siblings :) (this // wouldnt effect a change on topology) // check if I m your parent or vice versa (this would destroy the // tree) // check if you are younger then my father // check if I m younger then your father if( (iP != jP) && (i != jP) && (j != iP) && (tree.getNodeHeight(j) < tree.getNodeHeight(iP)) && (tree.getNodeHeight(i) < tree.getNodeHeight(jP)) ) { // if 1 & 2 are false and 3 & 4 are true then we found a valid // candidate exchangeNodes(tree, i, j, iP, jP); // possibleNodes = getPossibleNodes(i); calcDistances(possibleNodes, i); double backward = getWinningChance(indexOf(possibleNodes, j)); // possibleNodes = getPossibleNodes(j); calcDistances(possibleNodes, j); backward += getWinningChance(indexOf(possibleNodes, i)); // System.out.println("tries = " + tries+1); return Math.log(Math.min(1, (backward) / (forward))); // return 0.0; } } throw new OperatorFailedException( "Couldn't find valid wide move on this tree!"); } /* why not use Arrays.asList(a).indexOf(n) ? */ private int indexOf(NodeRef[] a, NodeRef n) { for(int i = 0; i < a.length; i++) { if( a[i] == n ) { return i; } } return -1; } private double getWinningChance(int index) { double sum = 0; for(int i = 0; i < distances.length; i++) { sum += (1.0 / distances[i]); } return (1.0 / distances[index]) / sum; } private void calcDistances(NodeRef[] nodes, NodeRef ref) { distances = new double[nodes.length]; for(int i = 0; i < nodes.length; i++) { distances[i] = getNodeDistance(ref, nodes[i]) + 1; } } private NodeRef getRandomNode(NodeRef[] nodes, NodeRef ref) { calcDistances(nodes, ref); double sum = 0; for(int i = 0; i < distances.length; i++) { sum += 1.0 / distances[i]; } double randomValue = MathUtils.nextDouble() * sum; NodeRef n = null; for(int i = 0; i < distances.length; i++) { randomValue -= 1.0 / distances[i]; if( randomValue <= 0 ) { n = nodes[i]; break; } } return n; } private int getNodeDistance(NodeRef i, NodeRef j) { int count = 0; while( i != j ) { count++; if( tree.getNodeHeight(i) < tree.getNodeHeight(j) ) { i = tree.getParent(i); } else { j = tree.getParent(j); } } return count; } public int getMode() { return mode; } public String getOperatorName() { return ((mode == NARROW) ? "Narrow" : "Wide") + " Exchange" + "(" + tree.getId() + ")"; } /* exchange subtrees whose root are i and j */ private void eupdate(NodeRef i, NodeRef j, NodeRef iP, NodeRef jP) throws OperatorFailedException { tree.beginTreeEdit(); tree.removeChild(iP, i); tree.removeChild(jP, j); tree.addChild(jP, i); tree.addChild(iP, j); try { tree.endTreeEdit(); } catch( MutableTree.InvalidTreeException ite ) { throw new OperatorFailedException(ite.toString()); } } public double getMinimumAcceptanceLevel() { if( mode == NARROW ) { return 0.05; } else { return 0.01; } } public double getMinimumGoodAcceptanceLevel() { if( mode == NARROW ) { return 0.05; } else { return 0.01; } } public String getPerformanceSuggestion() { if( MCMCOperator.Utils.getAcceptanceProbability(this) < getMinimumAcceptanceLevel() ) { return ""; } else if( MCMCOperator.Utils.getAcceptanceProbability(this) > getMaximumAcceptanceLevel() ) { return ""; } else { return ""; } } public static XMLObjectParser NARROW_EXCHANGE_PARSER = new AbstractXMLObjectParser() { public String getParserName() { return NARROW_EXCHANGE; } public Object parseXMLObject(XMLObject xo) throws XMLParseException { TreeModel treeModel = (TreeModel) xo.getChild(TreeModel.class); final double weight = xo.getDoubleAttribute("weight"); return new ExchangeOperator(NARROW, treeModel, weight); } // AbstractXMLObjectParser implementation public String getParserDescription() { return "This element represents a narrow exchange operator. " + "This operator swaps a random subtree with its uncle."; } public Class getReturnType() { return ExchangeOperator.class; } public XMLSyntaxRule[] getSyntaxRules() { return rules; } private final XMLSyntaxRule[] rules = { AttributeRule.newDoubleRule("weight"), new ElementRule(TreeModel.class)}; }; public static XMLObjectParser WIDE_EXCHANGE_PARSER = new AbstractXMLObjectParser() { public String getParserName() { return WIDE_EXCHANGE; } public Object parseXMLObject(XMLObject xo) throws XMLParseException { TreeModel treeModel = (TreeModel) xo.getChild(TreeModel.class); double weight = xo.getDoubleAttribute("weight"); return new ExchangeOperator(WIDE, treeModel, weight); } // AbstractXMLObjectParser implementation public String getParserDescription() { return "This element represents a wide exchange operator. " + "This operator swaps two random subtrees."; } public Class getReturnType() { return ExchangeOperator.class; } public XMLSyntaxRule[] getSyntaxRules() { return rules; } private final XMLSyntaxRule[] rules;{ rules = new XMLSyntaxRule[]{ AttributeRule.newDoubleRule("weight"), new ElementRule(TreeModel.class)}; } }; public static XMLObjectParser INTERMEDIATE_EXCHANGE_PARSER = new AbstractXMLObjectParser() { public String getParserName() { return INTERMEDIATE_EXCHANGE; } public Object parseXMLObject(XMLObject xo) throws XMLParseException { TreeModel treeModel = (TreeModel) xo.getChild(TreeModel.class); double weight = xo.getDoubleAttribute("weight"); return new ExchangeOperator(INTERMEDIATE, treeModel, weight); } // AbstractXMLObjectParser implementation public String getParserDescription() { return "This element represents a intermediate exchange operator. " + "This operator swaps two random subtrees."; } public Class getReturnType() { return ExchangeOperator.class; } public XMLSyntaxRule[] getSyntaxRules() { return rules; } private final XMLSyntaxRule[] rules = { AttributeRule.newDoubleRule("weight"), new ElementRule(TreeModel.class)}; }; }
package edu.mit.streamjit.impl.compiler; import com.google.common.base.Function; import com.google.common.base.Functions; import com.google.common.base.Joiner; import static com.google.common.base.Preconditions.*; import com.google.common.collect.FluentIterable; import edu.mit.streamjit.impl.compiler.types.MethodType; import com.google.common.collect.ImmutableList; import com.google.common.collect.Sets; import com.google.common.primitives.Shorts; import edu.mit.streamjit.impl.compiler.insts.Instruction; import edu.mit.streamjit.impl.compiler.types.RegularType; import edu.mit.streamjit.impl.compiler.types.VoidType; import edu.mit.streamjit.util.IntrusiveList; import java.io.PrintWriter; import java.util.List; import java.util.Set; /** * Method represents an executable element of a class file (instance method, * class (static) method, instance initializer (constructor), or class (static) * initializer). * * Methods may be resolved or unresolved. Resolved methods have basic blocks, * while unresolved methods are just declarations for generating call * instructions. Methods mirroring actual methods of live Class objects are * created unresolved, while mutable Methods are created resolved but with an * empty list of basic blocks. * @author Jeffrey Bosboom <jeffreybosboom@gmail.com> * @since 3/6/2013 */ public class Method extends Value implements Accessible, Parented<Klass> { @IntrusiveList.Next private Method next; @IntrusiveList.Previous private Method previous; @ParentedList.Parent private Klass parent; private final Set<Modifier> modifiers; /** * Lazily initialized during resolution. */ private ImmutableList<Argument> arguments; /** * Lazily initialized during resolution. */ private ParentedList<Method, BasicBlock> basicBlocks; private final ParentedList<Method, LocalVariable> localVariables; public Method(java.lang.reflect.Method method, Klass parent) { super(parent.getParent().types().getMethodType(method), method.getName()); //parent is set by our parent adding us to its list prior to making it //unmodifiable. (We can't add ourselves and have the list wrapped //unmodifiable later because it's stored in a final field.) this.modifiers = Sets.immutableEnumSet(Modifier.fromMethodBits(Shorts.checkedCast(method.getModifiers()))); //We're unresolved, so we don't have arguments or basic blocks. this.localVariables = null; } public Method(java.lang.reflect.Constructor<?> ctor, Klass parent) { super(parent.getParent().types().getMethodType(ctor), "<init>"); //parent is set by our parent adding us to its list prior to making it //unmodifiable. (We can't add ourselves and have the list wrapped //unmodifiable later because it's stored in a final field.) this.modifiers = Sets.immutableEnumSet(Modifier.fromMethodBits(Shorts.checkedCast(ctor.getModifiers()))); //We're unresolved, so we don't have arguments or basic blocks. this.localVariables = null; } public Method(String name, MethodType type, Set<Modifier> modifiers, Klass parent) { super(type, name); if (name.equals("<init>")) checkArgument(type.getReturnType().equals(type.getTypeFactory().getType(parent))); if (name.equals("<clinit>")) { checkArgument(type.getReturnType() instanceof VoidType); checkArgument(type.getParameterTypes().size() == 0); checkArgument(modifiers.contains(Modifier.STATIC)); } this.modifiers = modifiers; this.arguments = buildArguments(); this.basicBlocks = new ParentedList<>(this, BasicBlock.class); this.localVariables = new ParentedList<>(this, LocalVariable.class); parent.methods().add(this); } public boolean isMutable() { return getParent().isMutable(); } public boolean isResolved() { return basicBlocks != null; } /** * Returns true iff this method can be resolved. This method is safe to * call at all times after this Method's construction is complete, even if * this method has already been resolved. * @return true iff this method can be resolved */ public boolean isResolvable() { //Abstract methods don't have code; native methods have code, but not of //a form we can parse. return !modifiers().contains(Modifier.ABSTRACT) && !modifiers.contains(Modifier.NATIVE); } public void resolve() { checkState(isResolvable(), "cannot resolve %s", this); if (isResolved()) return; this.arguments = buildArguments(); this.basicBlocks = new ParentedList<>(this, BasicBlock.class); MethodResolver.resolve(this); } @Override public MethodType getType() { return (MethodType)super.getType(); } public Set<Modifier> modifiers() { return modifiers; } public ImmutableList<Argument> arguments() { checkState(isResolved(), "not resolved: %s", this); return arguments; } public Argument getArgument(String name) { for (Argument a : arguments()) if (a.getName().equals(name)) return a; return null; } public List<BasicBlock> basicBlocks() { checkState(isResolved(), "not resolved: %s", this); return basicBlocks; } public List<LocalVariable> localVariables() { checkState(localVariables != null, "mirrors live Class object: %s", this); return localVariables; } public LocalVariable getLocalVariable(String name) { for (LocalVariable v : localVariables()) if (v.getName().equals(name)) return v; return null; } public boolean isConstructor() { return getName().equals("<init>"); } public boolean hasReceiver() { return !(modifiers().contains(Modifier.STATIC) || isConstructor()); } @Override public Access getAccess() { return Access.fromModifiers(modifiers()); } @Override public void setAccess(Access access) { modifiers().removeAll(Access.allAccessModifiers()); modifiers().addAll(access.modifiers()); } @Override public void setName(String name) { checkState(isMutable(), "can't change name of method on immutable class %s", getParent()); super.setName(name); } @Override public Klass getParent() { return parent; } public Method removeFromParent() { checkState(getParent() != null); getParent().methods().remove(this); return this; } public void eraseFromParent() { removeFromParent(); for (BasicBlock b : ImmutableList.copyOf(basicBlocks)) b.eraseFromParent(); } @Override public String toString() { return modifiers.toString() + " " + getName() + " " +getType(); } public void dump(PrintWriter writer) { writer.write(Joiner.on(' ').join(modifiers())); writer.write(" "); writer.write(getType().getReturnType().toString()); writer.write(" "); writer.write(getName()); writer.write("("); String argString; if (isResolved()) argString = Joiner.on(", ").join(FluentIterable.from(arguments()).transform(new Function<Argument, String>() { @Override public String apply(Argument input) { return input.getType()+" "+input.getName(); } })); else argString = Joiner.on(", ").join(FluentIterable.from(getType().getParameterTypes()).transform(Functions.toStringFunction())); writer.write(argString); writer.write(")"); if (!isResolved()) { writer.write(";"); writer.println(); writer.flush(); return; } writer.write(" {"); writer.println(); if (isMutable()) { for (LocalVariable v : localVariables()) { writer.write("\t"); writer.write(v.toString()); writer.write(";"); writer.println(); } if (!localVariables.isEmpty()) writer.println(); } for (BasicBlock b : basicBlocks()) { writer.write(b.getName()); writer.write(": "); writer.println(); for (Instruction i : b.instructions()) { writer.write("\t"); writer.write(i.toString()); writer.println(); } } writer.write("}"); writer.println(); writer.flush(); } private ImmutableList<Argument> buildArguments() { ImmutableList<RegularType> paramTypes = getType().getParameterTypes(); ImmutableList.Builder<Argument> builder = ImmutableList.builder(); for (int i = 0; i < paramTypes.size(); ++i) { String name = (i == 0 && hasReceiver()) ? "this" : "arg"+i; builder.add(new Argument(this, paramTypes.get(i), name)); } return builder.build(); } }
package ui.components; import javafx.scene.input.KeyCode; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.Optional; import java.util.function.IntConsumer; /** * A very specialized ListView subclass that: * * - can be navigated with the arrow keys and Enter * - supports an event for item selection * - provides methods for retaining selection of an item (not by index) * after its contents are changed * * It depends on the functionality of ScrollableListView to ensure that * navigation scrolls the list properly. The Up, Down, and Enter key events * should not be separately bound on it. * * An item is considered selected when: * * - it is highlighted with the arrow keys, but only when the Shift key is not down * - Enter is pressed when it is highlighted * - it is clicked * * @param <T> The type of the item in the list */ public abstract class NavigableListView<T> extends ScrollableListView<T> { private static final Logger logger = LogManager.getLogger(NavigableListView.class.getName()); // Tracks the index of the item in the list which should be currently selected private Optional<Integer> selectedIndex = Optional.empty(); // Used for saving and restoring selection by item. // selectedIndex should be used to get the currently-selected item, through the provided getter. private Optional<T> lastSelectedItem = Optional.empty(); // Indicates that saveSelection was called, in the event that saveSelection itself fails // (when nothing is selected, both should be no-ops) private boolean saveSelectionCalled = false; private IntConsumer onItemSelected = i -> {}; public NavigableListView() { setupKeyEvents(); setupMouseEvents(); } /** * Should be called before making changes to the item list of this list view if * it's important that selection is retained after. */ public void saveSelection() { if (getSelectionModel().getSelectedItem() != null) { lastSelectedItem = Optional.of(getSelectionModel().getSelectedItem()); } saveSelectionCalled = true; } public void restoreSelection() { if (!lastSelectedItem.isPresent()) { if (!saveSelectionCalled) { throw new IllegalStateException("saveSelection must be called before restoreSelection"); } else { saveSelectionCalled = false; return; // No-op } } saveSelectionCalled = false; // Find index of previously-selected item int index = -1; int i = 0; for (T item : getItems()) { if (areItemsEqual(item, lastSelectedItem.get())) { index = i; break; } i++; } boolean itemFound = index > -1; if (itemFound) { // Select that item getSelectionModel().clearAndSelect(index); selectedIndex = Optional.of(index); // Do not trigger event; selection did not conceptually change } else { // The item disappeared if (getItems().size() == 0) { // No more items in the list selectedIndex = Optional.empty(); } else { // The list is non-empty, so we can be sure that we're selecting something // The current index is the same as the next, due to the item disappearing int lastIndex = getItems().size() - 1; int nextIndex = Math.min(selectedIndex.get(), lastIndex); getSelectionModel().clearAndSelect(nextIndex); selectedIndex = Optional.of(nextIndex); // The next item will be considered selected onItemSelected.accept(nextIndex); } } } abstract boolean areItemsEqual(T item1, T item2); private void setupMouseEvents() { setOnMouseClicked(e -> { int currentlySelected = getSelectionModel().getSelectedIndex(); // The currently-selected index is sometimes -1 when an issue is clicked. // When this happens we ignore this event. if (currentlySelected != -1) { selectedIndex = Optional.of(currentlySelected); logger.info("Mouse click on item index " + selectedIndex.get()); onItemSelected.accept(selectedIndex.get()); } }); } private void setupKeyEvents() { setOnKeyPressed(e -> { if (e.isControlDown()) { return; } if (e.getCode() == KeyCode.ENTER) { e.consume(); if (selectedIndex.isPresent()) { logger.info("Enter key selection on item " + selectedIndex.get()); onItemSelected.accept(selectedIndex.get()); } } if (e.getCode() == KeyCode.UP || e.getCode() == KeyCode.DOWN || e.getCode() == KeyboardShortcuts.UP_ISSUE || e.getCode() == KeyboardShortcuts.DOWN_ISSUE) { e.consume(); handleUpDownKeys(e.getCode() == KeyCode.DOWN || e.getCode() == KeyboardShortcuts.DOWN_ISSUE); assert selectedIndex.isPresent() : "handleUpDownKeys doesn't set selectedIndex!"; if (!e.isShiftDown()) { logger.info("Enter key selection on item index " + selectedIndex.get()); onItemSelected.accept(selectedIndex.get()); } } if (e.getCode() == KeyboardShortcuts.FIRST_ISSUE) { e.consume(); selectFirstItem(); } if (e.getCode() == KeyboardShortcuts.LAST_ISSUE) { e.consume(); selectLastItem(); } }); } private void handleUpDownKeys(boolean isDownKey) { // Nothing is selected or the list is empty; do nothing if (!selectedIndex.isPresent()) return; if (getItems().size() == 0) return; // Compute new index and clamp it within range int newIndex = selectedIndex.get() + (isDownKey ? 1 : -1); newIndex = Math.min(Math.max(0, newIndex), getItems().size() - 1); // Update selection state and our selection model getSelectionModel().clearAndSelect(newIndex); selectedIndex = Optional.of(newIndex); // Ensure that the newly-selected item is in view scrollAndShow(newIndex); } public void setOnItemSelected(IntConsumer callback) { onItemSelected = callback; } public void selectFirstItem() { requestFocus(); if (getItems().size() == 0) return; getSelectionModel().clearAndSelect(0); scrollAndShow(0); selectedIndex = Optional.of(0); onItemSelected.accept(selectedIndex.get()); } public void selectLastItem() { requestFocus(); if (getItems().size() == 0) return; getSelectionModel().clearAndSelect(getItems().size() - 1); scrollAndShow(getItems().size() - 1); selectedIndex = Optional.of(getItems().size() - 1); onItemSelected.accept(selectedIndex.get()); } public void selectNextItem() { requestFocus(); if (selectedIndex.get() < getItems().size() - 1) { getSelectionModel().clearAndSelect(selectedIndex.get() + 1); scrollAndShow(selectedIndex.get() + 1); selectedIndex = Optional.of(selectedIndex.get() + 1); onItemSelected.accept(selectedIndex.get()); } } public Optional<T> getSelectedItem() { return selectedIndex.map(getItems()::get); } }
package edu.uw.easysrl.syntax.parser; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import com.google.common.collect.HashBasedTable; import com.google.common.collect.Table; import edu.uw.easysrl.dependencies.ResolvedDependency; import edu.uw.easysrl.main.InputReader.InputToParser; import edu.uw.easysrl.main.InputReader.InputWord; import edu.uw.easysrl.semantics.lexicon.Lexicon; import edu.uw.easysrl.syntax.grammar.Category; import edu.uw.easysrl.syntax.grammar.SyntaxTreeNode; import edu.uw.easysrl.syntax.grammar.SyntaxTreeNode.SyntaxTreeNodeLeaf; import edu.uw.easysrl.syntax.tagger.POSTagger; import edu.uw.easysrl.syntax.training.PipelineTrainer.LabelClassifier; import edu.uw.easysrl.util.Util.Scored; public abstract class SRLParser { private final POSTagger tagger; private SRLParser(final POSTagger tagger) { this.tagger = tagger; } public final List<CCGandSRLparse> parseTokens(final List<InputWord> tokens) { return parseTokens2(tagger.tag(tokens)); } protected abstract List<CCGandSRLparse> parseTokens2(List<InputWord> tokens); public static class BackoffSRLParser extends SRLParser { private final SRLParser[] parsers; private final AtomicInteger backoffs = new AtomicInteger(); public BackoffSRLParser(final SRLParser... parsers) { super(parsers[0].tagger); this.parsers = parsers; } @Override protected List<CCGandSRLparse> parseTokens2(final List<InputWord> tokens) { for (final SRLParser parser : parsers) { final List<CCGandSRLparse> parses = parser.parseTokens(tokens); if (parses != null) { return parses; } else { backoffs.getAndIncrement(); } } return null; } @Override public int getMaxSentenceLength() { return parsers[parsers.length - 1].getMaxSentenceLength(); } } public abstract int getMaxSentenceLength(); public static class SemanticParser extends SRLParser { private final SRLParser parser; private final Lexicon lexicon; public SemanticParser(final SRLParser parser, final Lexicon lexicon) { super(parser.tagger); this.parser = parser; this.lexicon = lexicon; } @Override protected List<CCGandSRLparse> parseTokens2(final List<InputWord> tokens) { List<CCGandSRLparse> parse = parser.parseTokens(tokens); if (parse != null) { parse = parse.stream().map(x -> x.addSemantics(lexicon)).collect(Collectors.toList()); } return parse; } @Override public int getMaxSentenceLength() { return parser.getMaxSentenceLength(); } } public static class JointSRLParser extends SRLParser { private final Parser parser; public JointSRLParser(final Parser parser, final POSTagger tagger) { super(tagger); this.parser = parser; } @Override protected List<CCGandSRLparse> parseTokens2(final List<InputWord> tokens) { final List<Scored<SyntaxTreeNode>> parses = parser.doParsing(new InputToParser(tokens, null, null, false)); if (parses == null) { return null; } else { return parses .stream() .map(x -> new CCGandSRLparse(x.getObject(), x.getObject().getAllLabelledDependencies(), tokens)) .collect(Collectors.toList()); } } @Override public int getMaxSentenceLength() { return parser.getMaxSentenceLength(); } } public static class CCGandSRLparse implements Serializable { private static final long serialVersionUID = 1L; private final SyntaxTreeNode ccgParse; private final Collection<ResolvedDependency> dependencyParse; private final List<InputWord> words; private final Table<Integer, Integer, ResolvedDependency> headToArgNumberToDependency = HashBasedTable.create(); private final List<SyntaxTreeNodeLeaf> leaves; private CCGandSRLparse(final SyntaxTreeNode ccgParse, final Collection<ResolvedDependency> dependencyParse, final List<InputWord> words) { super(); this.ccgParse = ccgParse; this.dependencyParse = dependencyParse; this.words = words; for (final ResolvedDependency dep : dependencyParse) { headToArgNumberToDependency.put(dep.getHead(), dep.getArgNumber(), dep); } this.leaves = ccgParse.getLeaves(); } public SyntaxTreeNode getCcgParse() { return ccgParse; } public Collection<ResolvedDependency> getDependencyParse() { return dependencyParse; } public SyntaxTreeNodeLeaf getLeaf(final int wordIndex) { return leaves.get(wordIndex); } public List<ResolvedDependency> getOrderedDependenciesAtPredicateIndex(final int wordIndex) { final Category c = getLeaf(wordIndex).getCategory(); final List<ResolvedDependency> result = new ArrayList<>(); for (int i = 1; i <= c.getNumberOfArguments(); i++) { result.add(headToArgNumberToDependency.get(wordIndex, i)); } return result; } public CCGandSRLparse addSemantics(final Lexicon lexicon) { return new CCGandSRLparse(ccgParse.addSemantics(lexicon, this), dependencyParse, words); } } public static class PipelineSRLParser extends JointSRLParser { public PipelineSRLParser(final Parser parser, final LabelClassifier classifier, final POSTagger tagger) { super(parser, tagger); this.classifier = classifier; } private final LabelClassifier classifier; @Override public List<CCGandSRLparse> parseTokens2(final List<InputWord> tokens) { final List<CCGandSRLparse> parse = super.parseTokens2(tokens); if (parse == null) { return null; } return parse.stream().map(x -> addDependencies(tokens, x)).collect(Collectors.toList()); } private CCGandSRLparse addDependencies(final List<InputWord> tokens, final CCGandSRLparse parse) { final Collection<ResolvedDependency> result = new ArrayList<>(); for (final ResolvedDependency dep : parse.getDependencyParse()) { if (dep.getArgumentIndex() != dep.getHead()) { result.add(dep.overwriteLabel(classifier.classify(dep.dropLabel(), tokens))); } } return new CCGandSRLparse(parse.getCcgParse(), result, tokens); } } }
package com.bryanjswift.simplenote; import java.text.DateFormat; import java.text.SimpleDateFormat; /** * Hold constants for the SimpleNote application */ public class Constants { /** Name of stored preferences */ public static final String PREFS_NAME = "SimpleNotePrefs"; /** Logging tag prefix */ public static final String TAG = "SimpleNote:"; // Note Default Values public static final long DEFAULT_ID = -1L; public static final String DEFAULT_KEY = "__SN__DEFAULT__KEY__"; // Dates public static final DateFormat serverDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // Message Codes public static final int MESSAGE_UPDATE_NOTE = 12398; public static final int MESSAGE_UPDATE_FINISHED = 9732145; // Activity for result request Codes public static final String REQUEST_KEY = "ActivityRequest"; public static final int REQUEST_LOGIN = 32568; public static final int REQUEST_EDIT = 9138171; // Notifications public static final int NOTIFICATION_CREDENTIALS = 98074121; // API Base URL public static final String API_BASE_URL = "https://simple-note.appspot.com/api"; public static final String API_LOGIN_URL = API_BASE_URL + "/login"; // POST public static final String API_NOTES_URL = API_BASE_URL + "/index"; // GET public static final String API_NOTE_URL = API_BASE_URL + "/note"; // GET public static final String API_UPDATE_URL = API_BASE_URL + "/note"; // POST public static final String API_DELETE_URL = API_BASE_URL + "/delete"; // GET public static final String API_SEARCH_URL = API_BASE_URL + "/search"; // GET }
package com.chenzuhuang.zomail.core; import java.util.Properties; import javax.mail.Authenticator; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMessage.RecipientType; public class MailUtil { private static XMLUtil xmlUtil = XMLUtil.getXMLUtil(MailUtil.class.getClassLoader().getResourceAsStream("zomail.xml")); private static String fromEmail = xmlUtil.getParam("email"); private static String password = xmlUtil.getParam("password"); private static String auth = xmlUtil.getParam("auth"); private static String host = xmlUtil.getParam("host"); public static boolean sendEmail(String toEmail, String title, String content, String contentType){ Properties properties = System.getProperties(); properties.put("mail.smtp.auth", auth); properties.put("mail.smtp.host", host); Session session = Session.getInstance(properties, new Authenticator(){ @Override public PasswordAuthentication getPasswordAuthentication(){ return new PasswordAuthentication(fromEmail, password); } }); MimeMessage message = new MimeMessage(session); try { message.setFrom(new InternetAddress(fromEmail)); message.setRecipient(RecipientType.TO, new InternetAddress(toEmail)); message.setSubject(title); //On different system, you may use different encoding. //String new_content = new String(content.getBytes("GBK"), "utf-8"); message.setContent(content, "text/html;charset=utf-8"); Transport.send(message); } catch (MessagingException e) { e.printStackTrace(); return false; } return true; } /* public static void main(String[] args) { sendEmail("564923716@qq.com","title", "<p>content</p>","text/html;charset=utf-8"); } */ }
/* created 26 Oct 2008 for new cDVSTest chip * adapted apr 2011 for cDVStest30 chip by tobi * adapted 25 oct 2011 for SeeBetter10/11 chips by tobi * */ package eu.seebetter.ini.chips.sbret10; import ch.unizh.ini.jaer.chip.retina.*; import com.sun.opengl.util.j2d.TextRenderer; import eu.seebetter.ini.chips.*; import eu.seebetter.ini.chips.config.*; import eu.seebetter.ini.chips.sbret10.SBret10.SBret10Config.*; import eu.seebetter.ini.chips.seebetter20.SeeBetter20; import java.awt.event.ActionEvent; import java.awt.geom.Point2D.Float; import java.util.Observer; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JRadioButton; import net.sf.jaer.aemonitor.*; import net.sf.jaer.biasgen.*; import net.sf.jaer.biasgen.VDAC.VPot; import net.sf.jaer.chip.*; import net.sf.jaer.event.*; import net.sf.jaer.hardwareinterface.*; import java.awt.BorderLayout; import java.awt.Font; import java.awt.Insets; import java.awt.Rectangle; import java.beans.PropertyChangeSupport; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.math.BigInteger; import java.nio.FloatBuffer; import java.text.ParseException; import java.util.*; import javax.media.opengl.GL; import javax.media.opengl.GLAutoDrawable; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.BoxLayout; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JCheckBoxMenuItem; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTabbedPane; import javax.swing.border.TitledBorder; import net.sf.jaer.Description; import net.sf.jaer.biasgen.Pot.Sex; import net.sf.jaer.biasgen.Pot.Type; import net.sf.jaer.biasgen.coarsefine.AddressedIPotCF; import net.sf.jaer.biasgen.coarsefine.ShiftedSourceBiasCF; import net.sf.jaer.biasgen.coarsefine.ShiftedSourceControlsCF; import net.sf.jaer.graphics.AEViewer; import net.sf.jaer.graphics.RetinaRenderer; import net.sf.jaer.hardwareinterface.usb.cypressfx2.CypressFX2; import net.sf.jaer.util.ParameterControlPanel; import net.sf.jaer.util.filter.LowpassFilter2d; /** * Describes retina and its event extractor and bias generator. * Two constructors ara available, the vanilla constructor is used for event playback and the *one with a HardwareInterface parameter is useful for live capture. * {@link #setHardwareInterface} is used when the hardware interface is constructed after the retina object. *The constructor that takes a hardware interface also constructs the biasgen interface. * <p> * SeeBetter 10 and 11 feature several arrays of pixels, a fully configurable bias generator, * and a configurable output selector for digital and analog current and voltage outputs for characterization. * The output is word serial and includes an intensity neuron which rides onto the other addresses. * <p> * SeeBetter 10 and 11 are built in UMC18 CIS process and has 14.5u pixels. * * @author tobi */ @Description("SBret version 1.0") public class SBret10 extends AETemporalConstastRetina { /** Describes size of array of pixels on the chip, in the pixels address space */ public static class PixelArray extends Rectangle { int pitch; /** Makes a new description. Assumes that Extractor already right shifts address to remove even and odd distinction of addresses. * * @param pitch pitch of pixels in raw AER address space * @param x left corner origin x location of pixel in its address space * @param y bottom origin of array in its address space * @param width width in pixels * @param height height in pixels. */ public PixelArray(int pitch, int x, int y, int width, int height) { super(x, y, width, height); this.pitch = pitch; } } public static final PixelArray EntirePixelArray = new PixelArray(1, 0, 0, 240, 180); // following define bit masks for various hardware data types. // The hardware interface translateEvents method packs the raw device data into 32 bit 'addresses' and timestamps. // timestamps are unwrapped and timestamp resets are handled in translateEvents. Addresses are filled with either AE or ADC data. // AEs are filled in according the XMASK, YMASK, XSHIFT, YSHIFT below. /** * bit masks/shifts for cDVS AE data */ public static final int POLMASK = 1, XSHIFT = Integer.bitCount(POLMASK), XMASK = 255 << XSHIFT, // 8 bits YSHIFT = 16, // so that y addresses don't overlap ADC bits and cause fake ADC events Integer.bitCount(POLMASK | XMASK), YMASK = 255 << YSHIFT; // 6 bits /* * data type fields */ /** data type is either timestamp or data (AE address or ADC reading) */ public static final int DATA_TYPE_MASK = 0xc000, DATA_TYPE_ADDRESS = 0x0000, DATA_TYPE_TIMESTAMP = 0x4000, DATA_TYPE_WRAP = 0x8000, DATA_TYPE_TIMESTAMP_RESET = 0xd000; /** Address-type refers to data if is it an "address". This data is either an AE address or ADC reading.*/ public static final int ADDRESS_TYPE_MASK = 0x2000, EVENT_ADDRESS_MASK = POLMASK | XMASK | YMASK, ADDRESS_TYPE_EVENT = 0x0000, ADDRESS_TYPE_ADC = 0x2000; /** For ADC data, the data is defined by the ADC channel and whether it is the first ADC value from the scanner. */ public static final int ADC_TYPE_MASK = 0x1000, ADC_DATA_MASK = 0x3ff, ADC_START_BIT = 0x1000, ADC_READCYCLE_MASK = 0x0C00; public static final int MAX_ADC = (int) ((1 << 10) - 1); private FrameEventPacket frameEventPacket = new FrameEventPacket(PolarityADCSampleEvent.class); private SBret10DisplayMethod sbretDisplayMethod = null; private boolean displayIntensity; private int exposureB; private int exposureC; private int frameTime; private boolean displayLogIntensityChangeEvents; private boolean ignoreReadout; private boolean snapshot = false; private boolean resetOnReadout = false; SBret10DisplayControlPanel displayControlPanel = null; private IntensityFrameData frameData = new IntensityFrameData(); private SBret10Config config; /** Creates a new instance of cDVSTest20. */ public SBret10() { setName("SBret10"); setEventClass(PolarityADCSampleEvent.class); setSizeX(EntirePixelArray.width*EntirePixelArray.pitch); setSizeY(EntirePixelArray.height*EntirePixelArray.pitch); setNumCellTypes(3); // two are polarity and last is intensity setPixelHeightUm(18.5f); setPixelWidthUm(18.5f); setEventExtractor(new SBret10Extractor(this)); setBiasgen(config = new SBret10.SBret10Config(this)); displayIntensity = getPrefs().getBoolean("displayIntensity", true); displayLogIntensityChangeEvents = getPrefs().getBoolean("displayLogIntensityChangeEvents", true); setRenderer((new SBret10Renderer(this))); sbretDisplayMethod = new SBret10DisplayMethod(this); getCanvas().addDisplayMethod(sbretDisplayMethod); getCanvas().setDisplayMethod(sbretDisplayMethod); } @Override public void onDeregistration() { unregisterControlPanel(); getAeViewer().removeHelpItem(help1); } JComponent help1 = null; @Override public void onRegistration() { registerControlPanel(); help1 = getAeViewer().addHelpURLItem("https://svn.ini.uzh.ch/repos/tobi/tretina/pcb/cDVSTest/cDVSTest.pdf", "cDVSTest PCB design", "shows pcb design"); } private void registerControlPanel() { try { AEViewer viewer = getAeViewer(); // must do lazy install here because viewer hasn't been registered with this chip at this point //JPanel imagePanel = viewer.getImagePanel(); JFrame controlFrame = new JFrame("SBret10 display controls"); JPanel imagePanel = new JPanel(); imagePanel.add((displayControlPanel = new eu.seebetter.ini.chips.sbret10.SBret10DisplayControlPanel(this)), BorderLayout.SOUTH); imagePanel.revalidate(); controlFrame.getContentPane().add(imagePanel); controlFrame.pack(); controlFrame.setVisible(true); } catch (Exception e) { log.warning("could not register control panel: " + e); } } private void unregisterControlPanel() { try { AEViewer viewer = getAeViewer(); // must do lazy install here because viewer hasn't been registered with this chip at this point JPanel imagePanel = viewer.getImagePanel(); imagePanel.remove(displayControlPanel); imagePanel.revalidate(); } catch (Exception e) { log.warning("could not unregister control panel: " + e); } } /** Creates a new instance of cDVSTest10 * @param hardwareInterface an existing hardware interface. This constructor is preferred. It makes a new cDVSTest10Biasgen object to talk to the on-chip biasgen. */ public SBret10(HardwareInterface hardwareInterface) { this(); setHardwareInterface(hardwareInterface); } // int pixcnt=0; // TODO debug /** The event extractor. Each pixel has two polarities 0 and 1. * * <p> *The bits in the raw data coming from the device are as follows. * <p> *Bit 0 is polarity, on=1, off=0<br> *Bits 1-9 are x address (max value 320)<br> *Bits 10-17 are y address (max value 240) <br> *<p> */ public class SBret10Extractor extends RetinaExtractor { private int firstFrameTs = 0; private short[] countX; private short[] countY; private int pixCnt=0; // TODO debug boolean ignore = false; public SBret10Extractor(SBret10 chip) { super(chip); resetCounters(); } private void resetCounters(){ int numReadoutTypes = 3; if(countX == null || countY == null){ countX = new short[numReadoutTypes]; countY = new short[numReadoutTypes]; } Arrays.fill(countX, 0, numReadoutTypes, (short)0); Arrays.fill(countY, 0, numReadoutTypes, (short)0); } private void lastADCevent(){ if (resetOnReadout){ config.nChipReset.set(true); } ignore = false; } /** extracts the meaning of the raw events. *@param in the raw events, can be null *@return out the processed events. these are partially processed in-place. empty packet is returned if null is supplied as in. */ @Override synchronized public EventPacket extractPacket(AEPacketRaw in) { if (out == null) { out = new FrameEventPacket(chip.getEventClass()); } else { out.clear(); } if (in == null) { return out; } int n = in.getNumEvents(); //addresses.length; int[] datas = in.getAddresses(); int[] timestamps = in.getTimestamps(); OutputEventIterator outItr = out.outputIterator(); // at this point the raw data from the USB IN packet has already been digested to extract timestamps, including timestamp wrap events and timestamp resets. // The datas array holds the data, which consists of a mixture of AEs and ADC values. // Here we extract the datas and leave the timestamps alone. for (int i = 0; i < n; i++) { // TODO implement skipBy int data = datas[i]; if ((data & ADDRESS_TYPE_MASK) == ADDRESS_TYPE_EVENT) { if(!ignore){ PolarityADCSampleEvent e = (PolarityADCSampleEvent) outItr.nextOutput(); e.adcSample = -1; // TODO hack to mark as not an ADC sample e.startOfFrame = false; e.address = data; e.timestamp = (timestamps[i]); e.polarity = (data & 1) == 1 ? PolarityADCSampleEvent.Polarity.On : PolarityADCSampleEvent.Polarity.Off; e.x = (short) (chip.getSizeX()-1-((data & XMASK) >>> XSHIFT)); e.y = (short) ((data & YMASK) >>> YSHIFT); //System.out.println(data); } } else if ((data & ADDRESS_TYPE_MASK) == ADDRESS_TYPE_ADC) { PolarityADCSampleEvent e = (PolarityADCSampleEvent) outItr.nextOutput(); e.adcSample = data & ADC_DATA_MASK; int sampleType = (data & ADC_READCYCLE_MASK)>>Integer.numberOfTrailingZeros(ADC_READCYCLE_MASK); switch(sampleType){ case 0: e.readoutType = PolarityADCSampleEvent.Type.A; break; case 1: e.readoutType = PolarityADCSampleEvent.Type.B; //log.info("got B event"); break; case 2: e.readoutType = PolarityADCSampleEvent.Type.C; //log.info("got C event"); break; case 3: log.warning("Event with cycle null was sent out!"); break; default: log.warning("Event with unknown cycle was sent out!"); } e.timestamp = (timestamps[i]); e.address = data; e.startOfFrame = (data & ADC_START_BIT) == ADC_START_BIT; if(e.startOfFrame){ //if(pixCnt!=129600) System.out.println("New frame, pixCnt was incorrectly "+pixCnt+" instead of 129600 but this could happen at end of file"); if(ignoreReadout){ ignore = true; } //System.out.println("SOF - pixcount: "+pixCnt); resetCounters(); pixCnt=0; if(snapshot){ snapshot = false; config.adc.setAdcEnabled(false); } frameTime = e.timestamp - firstFrameTs; firstFrameTs = e.timestamp; } if(e.isB() && countX[1] == 0 && countY[2] == 0){ exposureB = e.timestamp-firstFrameTs; } if(e.isC() && countX[2] == 0 && countY[2] == 0){ exposureC = e.timestamp-firstFrameTs; } if(!(countY[sampleType]<chip.getSizeY())){ countY[sampleType] = 0; countX[sampleType]++; } e.x=(short)(chip.getSizeX()-1-countX[sampleType]); e.y=(short)(chip.getSizeY()-1-countY[sampleType]); countY[sampleType]++; pixCnt++; if(((config.useC.isSet() && e.isC()) || (!config.useC.isSet() && e.isB())) && e.x == (short)(chip.getSizeX()-1) && e.y == (short)(chip.getSizeY()-1)){ lastADCevent(); } //System.out.println("New ADC event: type "+sampleType+", x "+e.x+", y "+e.y); } } /* if (gotAEREvent) { lastEventTime = System.currentTimeMillis(); } else if (config.autoResetEnabled && config.nChipReset.isSet() && System.currentTimeMillis() - lastEventTime > AUTO_RESET_TIMEOUT_MS && getAeViewer() != null && getAeViewer().getPlayMode() == AEViewer.PlayMode.LIVE) { config.resetChip(); }*/ return out; } // extractPacket } // extractor /** overrides the Chip setHardware interface to construct a biasgen if one doesn't exist already. * Sets the hardware interface and the bias generators hardware interface *@param hardwareInterface the interface */ @Override public void setHardwareInterface(final HardwareInterface hardwareInterface) { this.hardwareInterface = hardwareInterface; SBret10.SBret10Config bg; try { if (getBiasgen() == null) { setBiasgen(bg = new SBret10.SBret10Config(this)); // now we can addConfigValue the control panel } else { getBiasgen().setHardwareInterface((BiasgenHardwareInterface) hardwareInterface); } } catch (ClassCastException e) { log.warning(e.getMessage() + ": probably this chip object has a biasgen but the hardware interface doesn't, ignoring"); } } /** * Describes ConfigurableIPots as well as the other configuration bits which control, for example, which * outputs are selected. These are all configured by a single shared shift register. * <p> * With Rx=82k, measured Im=2uA. With Rx=27k, measured Im=8uA. * <p> * cDVSTest has a pair of shared shifted sources, one for n-type and one for p-type. These sources supply a regulated voltaqe near the power rail. * The shifted sources are programmed by bits at the start of the global shared shift register. * They are not used on this SeeBetter10/11 chip. * * @author tobi */ public class SBret10Config extends SBretCPLDConfig { // extends Config to give us containers for various configuration data /** VR for handling all configuration changes in firmware */ public static final byte VR_WRITE_CONFIG = (byte) 0xB8; ArrayList<HasPreference> hasPreferencesList = new ArrayList<HasPreference>(); ChipConfigChain chipConfigChain = null; private ShiftedSourceBiasCF ssn, ssp; private ShiftedSourceBiasCF[] ssBiases = new ShiftedSourceBiasCF[2]; // private VPot thermometerDAC; int address = 0; JPanel bPanel; JTabbedPane bgTabbedPane; // portA private PortBit runCpld = new PortBit(SBret10.this, "a3", "runCpld", "(A3) Set high to run CPLD which enables event capture, low to hold logic in reset", true); private PortBit extTrigger = new PortBit(SBret10.this, "a1", "extTrigger", "(A1) External trigger to debug APS statemachine", false); // portC private PortBit runAdc = new PortBit(SBret10.this, "c0", "runAdc", "(C0) High to run ADC", true); // portE /** Bias generator power down bit */ PortBit powerDown = new PortBit(SBret10.this, "e2", "powerDown", "(E2) High to disable master bias and tie biases to default rails", false); PortBit nChipReset = new PortBit(SBret10.this, "e3", "nChipReset", "(E3) Low to reset AER circuits and hold pixels in reset, High to run", true); // shouldn't need to manipulate from host // CPLD shift register contents specified here by CPLDInt and CPLDBit private CPLDInt exposureB = new CPLDInt(SBret10.this, 15, 0, "exposureB", "time between reset and readout of a pixel", 0); private CPLDInt exposureC = new CPLDInt(SBret10.this, 31, 16, "exposureC", "time between reset and readout of a pixel for a second time (min 240!)", 240); private CPLDInt colSettle = new CPLDInt(SBret10.this, 47, 32, "colSettle", "time to settle a column select before readout", 0); private CPLDInt rowSettle = new CPLDInt(SBret10.this, 63, 48, "rowSettle", "time to settle a row select before readout", 0); private CPLDInt resSettle = new CPLDInt(SBret10.this, 79, 64, "resSettle", "time to settle a reset before readout", 0); private CPLDInt frameDelay = new CPLDInt(SBret10.this, 95, 80, "frameDelay", "time between two frames", 0); private CPLDInt padding = new CPLDInt(SBret10.this, 109, 96, "pad", "used to zeros", 0); private CPLDBit testPixAPSread = new CPLDBit(SBret10.this, 110, "testPixAPSread", "enables continuous scanning of testpixel", false); private CPLDBit useC = new CPLDBit(SBret10.this, 111, "useC", "enables a second readout", false); // lists of ports and CPLD config private ADC adc; // private Scanner scanner; private ApsReadoutControl apsReadoutControl; // other options private boolean autoResetEnabled; // set in loadPreferences /** Creates a new instance of SeeBetterConfig for cDVSTest with a given hardware interface *@param chip the chip this biasgen belongs to */ public SBret10Config(Chip chip) { super(chip); setName("SBret10Biasgen"); // port bits addConfigValue(nChipReset); addConfigValue(powerDown); addConfigValue(runAdc); addConfigValue(runCpld); addConfigValue(extTrigger); // cpld shift register stuff addConfigValue(exposureB); addConfigValue(exposureC); addConfigValue(resSettle); addConfigValue(rowSettle); addConfigValue(colSettle); addConfigValue(frameDelay); addConfigValue(padding); addConfigValue(testPixAPSread); addConfigValue(useC); // masterbias getMasterbias().setKPrimeNFet(55e-3f); // estimated from tox=42A, mu_n=670 cm^2/Vs // TODO fix for UMC18 process getMasterbias().setMultiplier(4); // =45 correct for dvs320 getMasterbias().setWOverL(4.8f / 2.4f); // masterbias has nfet with w/l=2 at output getMasterbias().addObserver(this); // changes to masterbias come back to update() here // shifted sources (not used on SeeBetter10/11) ssn = new ShiftedSourceBiasCF(this); ssn.setSex(Pot.Sex.N); ssn.setName("SSN"); ssn.setTooltipString("n-type shifted source that generates a regulated voltage near ground"); ssn.addObserver(this); ssn.setAddress(21); ssp = new ShiftedSourceBiasCF(this); ssp.setSex(Pot.Sex.P); ssp.setName("SSP"); ssp.setTooltipString("p-type shifted source that generates a regulated voltage near Vdd"); ssp.addObserver(this); ssp.setAddress(20); ssBiases[1] = ssn; ssBiases[0] = ssp; // DAC object for simple voltage DAC final float Vdd = 1.8f; setPotArray(new AddressedIPotArray(this)); try { addAIPot("DiffBn,n,normal,differencing amp"); // at input end of shift register addAIPot("OnBn,n,normal,DVS brighter threshold"); addAIPot("OffBn,n,normal,DVS darker threshold"); addAIPot("ApsCasEpc,p,cascode,cascode between APS und DVS"); addAIPot("DiffCasBnc,n,cascode,differentiator cascode bias"); addAIPot("ApsROSFBn,n,normal,APS readout source follower bias"); addAIPot("LocalBufBn,n,normal,Local buffer bias"); // TODO what's this? addAIPot("PixInvBn,n,normal,Pixel request inversion static inverter bias"); addAIPot("PrBp,p,normal,Photoreceptor bias current"); addAIPot("PrSFBp,p,normal,Photoreceptor follower bias current (when used in pixel type)"); addAIPot("RefrBp,p,normal,DVS refractory period current"); addAIPot("AEPdBn,n,normal,Request encoder pulldown static current"); addAIPot("LcolTimeoutBn,n,normal,No column request timeout"); addAIPot("AEPuXBp,p,normal,AER column pullup"); addAIPot("AEPuYBp,p,normal,AER row pullup"); addAIPot("IFThrBn,n,normal,Integrate and fire intensity neuron threshold"); addAIPot("IFRefrBn,n,normal,Integrate and fire intensity neuron refractory period bias current"); addAIPot("PadFollBn,n,normal,Follower-pad buffer bias current"); addAIPot("apsOverflowLevel,n,normal,special overflow level bias "); addAIPot("biasBuffer,n,normal,special buffer bias "); } catch (Exception e) { throw new Error(e.toString()); } // on-chip configuration chain chipConfigChain = new ChipConfigChain(chip); chipConfigChain.addObserver(this); // adc adc = new ADC(); adc.addObserver(this); // control of log readout apsReadoutControl = new ApsReadoutControl(); setBatchEditOccurring(true); loadPreferences(); setBatchEditOccurring(false); try { sendOnchipConfig(); } catch (HardwareInterfaceException ex) { Logger.getLogger(SBret10.class.getName()).log(Level.SEVERE, null, ex); } byte[] b = formatConfigurationBytes(this); } // constructor /** Quick addConfigValue of an addressed pot from a string description, comma delimited * * @param s , e.g. "Amp,n,normal,DVS ON threshold"; separate tokens for name,sex,type,tooltip\nsex=n|p, type=normal|cascode * @throws ParseException Error */ private void addAIPot(String s) throws ParseException { try { String d = ","; StringTokenizer t = new StringTokenizer(s, d); if (t.countTokens() != 4) { throw new Error("only " + t.countTokens() + " tokens in pot " + s + "; use , to separate tokens for name,sex,type,tooltip\nsex=n|p, type=normal|cascode"); } String name = t.nextToken(); String a; a = t.nextToken(); Sex sex = null; if (a.equalsIgnoreCase("n")) { sex = Sex.N; } else if (a.equalsIgnoreCase("p")) { sex = Sex.P; } else { throw new ParseException(s, s.lastIndexOf(a)); } a = t.nextToken(); Type type = null; if (a.equalsIgnoreCase("normal")) { type = Type.NORMAL; } else if (a.equalsIgnoreCase("cascode")) { type = Type.CASCODE; } else { throw new ParseException(s, s.lastIndexOf(a)); } String tip = t.nextToken(); /* public ConfigurableIPot32(SeeBetterConfig biasgen, String name, int shiftRegisterNumber, Type type, Sex sex, boolean lowCurrentModeEnabled, boolean enabled, int bitValue, int bufferBitValue, int displayPosition, String tooltipString) { */ getPotArray().addPot(new AddressedIPotCF(this, name, address++, type, sex, false, true, AddressedIPotCF.maxCoarseBitValue / 2, AddressedIPotCF.maxFineBitValue, address, tip)); } catch (Exception e) { throw new Error(e.toString()); } } /** Sends everything on the on-chip shift register * * @throws HardwareInterfaceException * @return false if not sent because bytes are not yet initialized */ private boolean sendOnchipConfig() throws HardwareInterfaceException { log.info("Send whole OnChip Config"); //biases if(getPotArray() == null){ return false; } AddressedIPotArray ipots = (AddressedIPotArray) potArray; Iterator i = ipots.getShiftRegisterIterator(); while(i.hasNext()){ AddressedIPot iPot = (AddressedIPot) i.next(); if(!sendAIPot(iPot))return false; } //shifted sources for (ShiftedSourceBiasCF ss : ssBiases) { if(!sendAIPot(ss))return false; } //diagnose SR sendChipConfig(); return true; } public boolean sendChipConfig() throws HardwareInterfaceException{ String onChipConfigBits = chipConfigChain.getBitString(); byte[] onChipConfigBytes = bitString2Bytes(onChipConfigBits); if(onChipConfigBits == null){ return false; } else { BigInteger bi = new BigInteger(onChipConfigBits); //System.out.println("Send on chip config (length "+onChipConfigBits.length+" bytes): "+String.format("%0"+(onChipConfigBits.length<<1)+"X", bi)); log.info("Send on chip config: "+onChipConfigBits); sendConfig(CMD_CHIP_CONFIG, 0, onChipConfigBytes); return true; } } /** * @return the autoResetEnabled */ public boolean isAutoResetEnabled() { return autoResetEnabled; } /** * @param autoResetEnabled the autoResetEnabled to set */ public void setAutoResetEnabled(boolean autoResetEnabled) { if (this.autoResetEnabled != autoResetEnabled) { setChanged(); } this.autoResetEnabled = autoResetEnabled; notifyObservers(); } private byte[] bitString2Bytes(String bitString) { int nbits = bitString.length(); // compute needed number of bytes int nbytes = (nbits % 8 == 0) ? (nbits / 8) : (nbits / 8 + 1); // 4->1, 8->1, 9->2 // for simplicity of following, left pad with 0's right away to get integral byte string int npad = nbytes * 8 - nbits; String pad = new String(new char[npad]).replace("\0", "0"); bitString = pad + bitString; byte[] byteArray = new byte[nbytes]; int bit = 0; for (int bite = 0; bite < nbytes; bite++) { // for each byte for (int i = 0; i < 8; i++) { // iterate over each bit of this byte byteArray[bite] = (byte) ((0xff & byteArray[bite]) << 1); // first left shift previous value, with 0xff to avoid sign extension if (bitString.charAt(bit) == '1') { // if there is a 1 at this position of string (starting from left side) // this conditional and loop structure ensures we count in bytes and that we left shift for each bit position in the byte, padding on the right with 0's byteArray[bite] |= 1; // put a 1 at the lsb of the byte } bit++; // go to next bit of string to the right } } return byteArray; } /** Command sent to firmware by vendor request */ public class ConfigCmd { short code; String name; public ConfigCmd(int code, String name) { this.code = (short) code; this.name = name; } @Override public String toString() { return "ConfigCmd{" + "code=" + code + ", name=" + name + '}'; } } /** Vendor request command understood by the firmware in connection with VENDOR_REQUEST_SEND_BIAS_BYTES */ public final ConfigCmd CMD_IPOT = new ConfigCmd(1, "IPOT"), CMD_AIPOT = new ConfigCmd(2, "AIPOT"), CMD_SCANNER = new ConfigCmd(3, "SCANNER"), CMD_CHIP_CONFIG = new ConfigCmd(4, "CHIP"), CMD_SETBIT = new ConfigCmd(5, "SETBIT"), CMD_CPLD_CONFIG = new ConfigCmd(8, "CPLD"); public final String[] CMD_NAMES = {"IPOT", "AIPOT", "SCANNER", "CHIP", "SET_BIT", "CPLD_CONFIG"}; final byte[] emptyByteArray = new byte[0]; /** Sends complete configuration to hardware by calling several updates with objects * * @param biasgen this object * @throws HardwareInterfaceException on some error */ @Override public void sendConfiguration(Biasgen biasgen) throws HardwareInterfaceException { if (isBatchEditOccurring()) { log.info("batch edit occurring, not sending configuration yet"); return; } log.info("sending full configuration"); if (!sendOnchipConfig()) { return; } sendCPLDConfig(); for (PortBit b : portBits) { update(b, null); } } private boolean sendAIPot(AddressedIPot pot) throws HardwareInterfaceException{ byte[] bytes = pot.getBinaryRepresentation(); if (bytes == null) { return false; // not ready yet, called by super } String hex = String.format("%02X%02X%02X",bytes[2],bytes[1],bytes[0]); //log.info("Send AIPot for "+pot.getName()+" with value "+hex); sendConfig(CMD_AIPOT, 0, bytes); // the usual packing of ipots with other such as shifted sources, on-chip voltage dac, and diagnotic mux output and extra configuration return true; } /** Momentarily puts the pixels and on-chip AER logic in reset and then releases the reset. * */ private void resetChip() { log.info("resetting AER communication"); nChipReset.set(false); nChipReset.set(true); } /** The central point for communication with HW from biasgen. All objects in SeeBetterConfig are Observables * and addConfigValue SeeBetterConfig.this as Observer. They then call notifyObservers when their state changes. * Objects such as ADC store preferences for ADC, and update should update the hardware registers accordingly. * @param observable IPot, Scanner, etc * @param object notifyChange - not used at present */ @Override synchronized public void update(Observable observable, Object object) { // thread safe to ensure gui cannot retrigger this while it is sending something // sends a vendor request depending on type of update // vendor request is always VR_CONFIG // value is the type of update // index is sometimes used for 16 bitmask updates // bytes are the rest of data if (isBatchEditOccurring()) { return; } // log.info("update with " + observable); try { if (observable instanceof IPot || observable instanceof VPot) { // must send all of the onchip shift register values to replace shift register contents sendOnchipConfig(); } else if (observable instanceof OutputMux || observable instanceof OnchipConfigBit) { sendChipConfig(); } else if (observable instanceof ChipConfigChain) { sendChipConfig(); } else if (observable instanceof Masterbias) { powerDown.set(getMasterbias().isPowerDownEnabled()); } else if (observable instanceof TriStateablePortBit) { // tristateable should come first before configbit since it is subclass TriStateablePortBit b = (TriStateablePortBit) observable; byte[] bytes = {(byte) ((b.isSet() ? (byte) 1 : (byte) 0) | (b.isHiZ() ? (byte) 2 : (byte) 0))}; sendConfig(CMD_SETBIT, b.getPortbit(), bytes); // sends value=CMD_SETBIT, index=portbit with (port(b=0,d=1,e=2)<<8)|bitmask(e.g. 00001000) in MSB/LSB, byte[0]= OR of value (1,0), hiZ=2/0, bit is set if tristate, unset if driving port } else if (observable instanceof PortBit) { PortBit b = (PortBit) observable; byte[] bytes = {b.isSet() ? (byte) 1 : (byte) 0}; sendConfig(CMD_SETBIT, b.getPortbit(), bytes); // sends value=CMD_SETBIT, index=portbit with (port(b=0,d=1,e=2)<<8)|bitmask(e.g. 00001000) in MSB/LSB, byte[0]=value (1,0) } else if (observable instanceof CPLDConfigValue) { sendCPLDConfig(); } else if (observable instanceof ADC) { sendCPLDConfig(); // CPLD register updates on device side save and restore the RUN_ADC flag // update(runAdc, null); } else if (observable instanceof AddressedIPot) { sendAIPot((AddressedIPot)observable); } else { super.update(observable, object); // super (SeeBetterConfig) handles others, e.g. masterbias } } catch (HardwareInterfaceException e) { log.warning("On update() caught " + e.toString()); } } private void sendCPLDConfig() throws HardwareInterfaceException { byte[] bytes = cpldConfig.getBytes(); log.info("Send CPLD Config: "+cpldConfig.toString()); sendConfig(CMD_CPLD_CONFIG, 0, bytes); } /** convenience method for sending configuration to hardware. Sends vendor request VR_WRITE_CONFIG with subcommand cmd, index index and bytes bytes. * * @param cmd the subcommand to set particular configuration, e.g. CMD_CPLD_CONFIG * @param index unused * @param bytes the payload * @throws HardwareInterfaceException */ void sendConfig(ConfigCmd cmd, int index, byte[] bytes) throws HardwareInterfaceException { // StringBuilder sb = new StringBuilder(String.format("sending config cmd=0x%X (%s) index=0x%X with %d bytes", cmd.code, cmd.name, index, bytes.length)); if (bytes == null || bytes.length == 0) { } else { int max = 50; if (bytes.length < max) { max = bytes.length; } // sb.append(" = "); // for (int i = 0; i < max; i++) { // sb.append(String.format("%X, ", bytes[i])); // log.info(sb.toString()); } // end debug if (bytes == null) { bytes = emptyByteArray; } // log.info(String.format("sending command vendor request cmd=%d, index=%d, and %d bytes", cmd, index, bytes.length)); if (getHardwareInterface() != null && getHardwareInterface() instanceof CypressFX2) { ((CypressFX2) getHardwareInterface()).sendVendorRequest(VR_WRITE_CONFIG, (short) (0xffff & cmd.code), (short) (0xffff & index), bytes); // & to prevent sign extension for negative shorts } } /** * Convenience method for sending configuration to hardware. Sends vendor request VENDOR_REQUEST_SEND_BIAS_BYTES with subcommand cmd, index index and empty byte array. * * @param cmd the subcommand * @param index data * @throws HardwareInterfaceException */ void sendConfig(ConfigCmd cmd, int index) throws HardwareInterfaceException { sendConfig(cmd, index, emptyByteArray); } @Override public void loadPreferences() { super.loadPreferences(); if (hasPreferencesList != null) { for (HasPreference hp : hasPreferencesList) { hp.loadPreference(); } } if (ssBiases != null) { for (ShiftedSourceBiasCF ss : ssBiases) { ss.loadPreferences(); } } // if (thermometerDAC != null) { // thermometerDAC.loadPreferences(); setAutoResetEnabled(getPrefs().getBoolean("autoResetEnabled", false)); } @Override public void storePreferences() { super.storePreferences(); for (HasPreference hp : hasPreferencesList) { hp.storePreference(); } if (ssBiases != null) { for (ShiftedSourceBiasCF ss : ssBiases) { ss.storePreferences(); } } // if (thermometerDAC != null) { // thermometerDAC.storePreferences(); getPrefs().putBoolean("autoResetEnabled", autoResetEnabled); } /** * * Overrides the default method to addConfigValue the custom control panel for configuring the SBret10 output muxes * and many other chip and board controls. * * @return a new panel for controlling this chip and board configuration */ @Override public JPanel buildControlPanel() { // if(displayControlPanel!=null) return displayControlPanel; bPanel = new JPanel(); bPanel.setLayout(new BorderLayout()); // add a reset button on top of everything final Action resetChipAction = new AbstractAction("Reset chip") { {putValue(Action.SHORT_DESCRIPTION, "Resets the pixels and the AER logic momentarily");} @Override public void actionPerformed(ActionEvent evt) { resetChip(); } }; final Action autoResetAction = new AbstractAction("Enable automatic chip reset") { {putValue(Action.SHORT_DESCRIPTION, "Enables reset after no activity when nChipReset is inactive"); putValue(Action.SELECTED_KEY,isAutoResetEnabled());} @Override public void actionPerformed(ActionEvent e) { setAutoResetEnabled(!autoResetEnabled); } }; JPanel specialButtons = new JPanel(); specialButtons.setLayout(new BoxLayout(specialButtons, BoxLayout.X_AXIS)); specialButtons.add(new JButton(resetChipAction)); specialButtons.add(new JCheckBoxMenuItem(autoResetAction)); bPanel.add(specialButtons, BorderLayout.NORTH); bgTabbedPane = new JTabbedPane(); setBatchEditOccurring(true); // stop updates on building panel JPanel combinedBiasShiftedSourcePanel = new JPanel(); combinedBiasShiftedSourcePanel.setLayout(new BoxLayout(combinedBiasShiftedSourcePanel, BoxLayout.Y_AXIS)); combinedBiasShiftedSourcePanel.add(super.buildControlPanel()); combinedBiasShiftedSourcePanel.add(new ShiftedSourceControlsCF(ssn)); combinedBiasShiftedSourcePanel.add(new ShiftedSourceControlsCF(ssp)); bgTabbedPane.addTab("Biases", combinedBiasShiftedSourcePanel); bgTabbedPane.addTab("Output MUX control", chipConfigChain.buildMuxControlPanel()); JPanel apsReadoutPanel = new JPanel(); apsReadoutPanel.setLayout(new BoxLayout(apsReadoutPanel, BoxLayout.Y_AXIS)); bgTabbedPane.add("APS Readout", apsReadoutPanel); apsReadoutPanel.add(new ParameterControlPanel(adc)); apsReadoutPanel.add(new ParameterControlPanel(apsReadoutControl)); JPanel chipConfigPanel = chipConfigChain.getChipConfigPanel(); bgTabbedPane.addTab("Chip configuration", chipConfigPanel); bPanel.add(bgTabbedPane, BorderLayout.CENTER); // only select panel after all added try { bgTabbedPane.setSelectedIndex(getPrefs().getInt("SBret10.bgTabbedPaneSelectedIndex", 0)); } catch (IndexOutOfBoundsException e) { bgTabbedPane.setSelectedIndex(0); } // add listener to store last selected tab bgTabbedPane.addMouseListener( new java.awt.event.MouseAdapter() { @Override public void mouseClicked(java.awt.event.MouseEvent evt) { tabbedPaneMouseClicked(evt); } }); setBatchEditOccurring(false); return bPanel; } private void tabbedPaneMouseClicked(java.awt.event.MouseEvent evt) { getPrefs().putInt("SBret10.bgTabbedPaneSelectedIndex", bgTabbedPane.getSelectedIndex()); } /** Controls the APS intensity readout by wrapping the relevant bits */ public class ApsReadoutControl implements Observer { private PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this); public final String EVENT_TESTPIXEL = "testpixelEnabled"; public ApsReadoutControl() { rowSettle.addObserver(this); colSettle.addObserver(this); exposureB.addObserver(this); exposureC.addObserver(this); resSettle.addObserver(this); frameDelay.addObserver(this); testPixAPSread.addObserver(this); useC.addObserver(this); } public void setColSettleCC(int cc) { colSettle.set(cc); } public void setRowSettleCC(int cc) { rowSettle.set(cc); } public void setResSettleCC(int cc) { resSettle.set(cc); } public void setFrameDelayCC(int cc){ frameDelay.set(cc); } public void setExposureBDelayCC(int cc){ exposureB.set(cc); } public void setExposureCDelayCC(int cc){ exposureC.set(cc); } public boolean isTestpixelEnabled() { return SBret10Config.this.testPixAPSread.isSet(); } public void setTestpixelEnabled(boolean testpixel) { SBret10Config.this.testPixAPSread.set(testpixel); } public boolean isUseC() { return SBret10Config.this.useC.isSet(); } public void setUseC(boolean useC) { SBret10Config.this.useC.set(useC); } public int getColSettleCC() { return colSettle.get(); } public int getRowSettleCC() { return rowSettle.get(); } public int getResSettleCC() { return resSettle.get(); } public int getFrameDelayCC() { return frameDelay.get(); } public int getExposureBDelayCC() { return exposureB.get(); } public int getExposureCDelayCC() { return exposureC.get(); } @Override public void update(Observable o, Object arg) { setChanged(); notifyObservers(arg); if (o == testPixAPSread) { getPropertyChangeSupport().firePropertyChange(EVENT_TESTPIXEL, null, testPixAPSread.isSet()); } } /** * @return the propertyChangeSupport */ public PropertyChangeSupport getPropertyChangeSupport() { return propertyChangeSupport; } } public class ADC extends Observable implements Observer { ; int channel = getPrefs().getInt("ADC.channel", 3); public final String EVENT_ADC_ENABLED = "adcEnabled", EVENT_ADC_CHANNEL = "adcChannel"; private PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this); public ADC() { runAdc.addObserver(this); } public boolean isAdcEnabled() { return runAdc.isSet(); } public boolean isResetOnReadout() { return resetOnReadout; } public void setResetOnReadout(boolean reset) { resetOnReadout = reset; } public void setAdcEnabled(boolean yes) { if(resetOnReadout){ nChipReset.set(false); try { Thread.sleep(10); } catch (InterruptedException ex) { Logger.getLogger(SBret10.class.getName()).log(Level.SEVERE, null, ex); } } runAdc.set(yes); } @Override public void update(Observable o, Object arg) { setChanged(); notifyObservers(arg); if (o == runAdc) { propertyChangeSupport.firePropertyChange(EVENT_ADC_ENABLED, null, runAdc.isSet()); } // TODO } /** * @return the propertyChangeSupport */ public PropertyChangeSupport getPropertyChangeSupport() { return propertyChangeSupport; } } /** * Formats bits represented in a string as '0' or '1' as a byte array to be sent over the interface to the firmware, for loading * in big endian bit order, in order of the bytes sent starting with byte 0. * <p> * Because the firmware writes integral bytes it is important that the * bytes sent to the device are padded with leading bits * (at msbs of first byte) that are finally shifted out of the on-chip shift register. * * Therefore <code>bitString2Bytes</code> should only be called ONCE, after the complete bit string has been assembled, unless it is known * the other bits are an integral number of bytes. * * @param bitString in msb to lsb order from left end, where msb will be in msb of first output byte * @return array of bytes to send */ public class ChipConfigChain extends Observable implements HasPreference, Observer { Chip sbChip; //Config Bits OnchipConfigBit resetCalib = new OnchipConfigBit(SBret10.this, "resetCalib", 0, "turn the calibration neuron off", true), typePCalib = new OnchipConfigBit(SBret10.this, "typePCalib", 1, "make the calibration neuron P type", false), resetTestpixel = new OnchipConfigBit(SBret10.this, "resetTestpixel", 2, "keept the testpixel in reset", true), hotPixelSuppression = new OnchipConfigBit(SBret10.this, "hotPixelSuppression", 3, "keept turn the hot pixel suppression on", false), nArow = new OnchipConfigBit(SBret10.this, "nArow", 4, "use nArow in the AER state machine", false), useAout = new OnchipConfigBit(SBret10.this, "useAout", 5, "turn the pads for the analog MUX outputs on", true) ; OnchipConfigBit[] configBits = {resetCalib, typePCalib, resetTestpixel, hotPixelSuppression, nArow, useAout}; int TOTAL_CONFIG_BITS = 24; //Muxes OutputMux[] amuxes = {new AnalogOutputMux(1), new AnalogOutputMux(2), new AnalogOutputMux(3)}; OutputMux[] dmuxes = {new DigitalOutputMux(1), new DigitalOutputMux(2), new DigitalOutputMux(3), new DigitalOutputMux(4)}; OutputMux[] bmuxes = {new DigitalOutputMux(0)}; ArrayList<OutputMux> muxes = new ArrayList(); MuxControlPanel controlPanel = null; public ChipConfigChain(Chip chip){ this.sbChip = chip; hasPreferencesList.add(this); for (OnchipConfigBit b : configBits) { b.addObserver(this); } muxes.addAll(Arrays.asList(bmuxes)); muxes.addAll(Arrays.asList(dmuxes)); // 4 digital muxes, first in list since at end of chain - bits must be sent first, before any biasgen bits muxes.addAll(Arrays.asList(amuxes)); // finally send the 3 voltage muxes for (OutputMux m : muxes) { m.addObserver(this); m.setChip(chip); } bmuxes[0].setName("BiasOutMux"); bmuxes[0].put(0,"IFThrBn"); bmuxes[0].put(1,"AEPuYBp"); bmuxes[0].put(2,"AEPuXBp"); bmuxes[0].put(3,"LColTimeout"); bmuxes[0].put(4,"AEPdBn"); bmuxes[0].put(5,"RefrBp"); bmuxes[0].put(6,"PrSFBp"); bmuxes[0].put(7,"PrBp"); bmuxes[0].put(8,"PixInvBn"); bmuxes[0].put(9,"LocalBufBn"); bmuxes[0].put(10,"ApsROSFBn"); bmuxes[0].put(11,"DiffCasBnc"); bmuxes[0].put(12,"ApsCasBpc"); bmuxes[0].put(13,"OffBn"); bmuxes[0].put(14,"OnBn"); bmuxes[0].put(15,"DiffBn"); dmuxes[0].setName("DigMux3"); dmuxes[1].setName("DigMux2"); dmuxes[2].setName("DigMux1"); dmuxes[3].setName("DigMux0"); for (int i = 0; i < 4; i++) { dmuxes[i].put(0, "AY179right"); dmuxes[i].put(1, "Acol"); dmuxes[i].put(2, "ColArbTopA"); dmuxes[i].put(3, "ColArbTopR"); dmuxes[i].put(4, "FF1"); dmuxes[i].put(5, "FF2"); dmuxes[i].put(6, "Rcarb"); dmuxes[i].put(7, "Rcol"); dmuxes[i].put(8, "Rrow"); dmuxes[i].put(9, "RxarbE"); dmuxes[i].put(10, "nAX0"); dmuxes[i].put(11, "nArowBottom"); dmuxes[i].put(12, "nArowTop"); dmuxes[i].put(13, "nRxOn"); } dmuxes[0].put(14, "AY179"); dmuxes[0].put(15, "RY179"); dmuxes[1].put(14, "AY179"); dmuxes[1].put(15, "RY179"); dmuxes[2].put(14, "biasCalibSpike"); dmuxes[2].put(15, "nRY179right"); dmuxes[3].put(14, "nResetRxCol"); dmuxes[3].put(15, "nRYtestpixel"); amuxes[0].setName("AnaMux2"); amuxes[1].setName("AnaMux1"); amuxes[2].setName("AnaMux0"); for (int i = 0; i < 3; i++) { amuxes[i].put(0, "on"); amuxes[i].put(1, "off"); amuxes[i].put(2, "vdiff"); amuxes[i].put(3, "nResetPixel"); amuxes[i].put(4, "pr"); amuxes[i].put(5, "pd"); } amuxes[0].put(6, "apsgate"); amuxes[0].put(7, "apsout"); amuxes[1].put(6, "apsgate"); amuxes[1].put(7, "apsout"); amuxes[2].put(6, "calibNeuron"); amuxes[2].put(7, "nTimeout_AI"); } class SBret10OutputMap extends OutputMap { HashMap<Integer, String> nameMap = new HashMap<Integer, String>(); void put(int k, int v, String name) { put(k, v); nameMap.put(k, name); } void put(int k, String name) { nameMap.put(k, name); } } class VoltageOutputMap extends SBret10OutputMap { final void put(int k, int v) { put(k, v, "Voltage " + k); } VoltageOutputMap() { put(0, 1); put(1, 3); put(2, 5); put(3, 7); put(4, 9); put(5, 11); put(6, 13); put(7, 15); } } class DigitalOutputMap extends SBret10OutputMap { DigitalOutputMap() { for (int i = 0; i < 16; i++) { put(i, i, "DigOut " + i); } } } class AnalogOutputMux extends OutputMux { AnalogOutputMux(int n) { super(sbChip, 4, 8, (OutputMap)(new VoltageOutputMap())); setName("Voltages" + n); } } class DigitalOutputMux extends OutputMux { DigitalOutputMux(int n) { super(sbChip, 4, 16, (OutputMap)(new DigitalOutputMap())); setName("LogicSignals" + n); } } public String getBitString(){ //System.out.print("dig muxes "); String dMuxBits = getMuxBitString(dmuxes); //System.out.print("config bits "); String configBits = getConfigBitString(); //System.out.print("analog muxes "); String aMuxBits = getMuxBitString(amuxes); //System.out.print("bias muxes "); String bMuxBits = getMuxBitString(bmuxes); String chipConfigChain = (dMuxBits + configBits + aMuxBits + bMuxBits); //System.out.println("On chip config chain: "+chipConfigChain); return chipConfigChain; // returns bytes padded at end } String getMuxBitString(OutputMux[] muxs){ StringBuilder s = new StringBuilder(); for (OutputMux m : muxs) { s.append(m.getBitString()); } //System.out.println(s); return s.toString(); } String getConfigBitString() { StringBuilder s = new StringBuilder(); for (int i = 0; i < TOTAL_CONFIG_BITS - configBits.length; i++) { s.append("0"); } for (int i = configBits.length - 1; i >= 0; i s.append(configBits[i].isSet() ? "1" : "0"); } //System.out.println(s); return s.toString(); } public MuxControlPanel buildMuxControlPanel() { return new MuxControlPanel(muxes); } public JPanel getChipConfigPanel(){ JPanel chipConfigPanel = new JPanel(new BorderLayout()); //On-Chip config bits JPanel extraPanel = new JPanel(); extraPanel.setLayout(new BoxLayout(extraPanel, BoxLayout.Y_AXIS)); for (OnchipConfigBit b : configBits) { extraPanel.add(new JRadioButton(b.getAction())); } extraPanel.setBorder(new TitledBorder("Extra on-chip bits")); chipConfigPanel.add(extraPanel, BorderLayout.NORTH); //FX2 port bits JPanel portBitsPanel = new JPanel(); portBitsPanel.setLayout(new BoxLayout(portBitsPanel, BoxLayout.Y_AXIS)); for (PortBit p : portBits) { portBitsPanel.add(new JRadioButton(p.getAction())); } portBitsPanel.setBorder(new TitledBorder("Cypress FX2 port bits")); chipConfigPanel.add(portBitsPanel, BorderLayout.CENTER); return chipConfigPanel; } @Override public void loadPreference() { for (OnchipConfigBit b : configBits) { b.loadPreference(); } } @Override public void storePreference() { for (OnchipConfigBit b : configBits) { b.storePreference(); } } @Override public void update(Observable o, Object arg) { setChanged(); notifyObservers(arg); } } } /** * @return the displayLogIntensity */ public boolean isDisplayIntensity() { return displayIntensity; } /** * @return the displayLogIntensity */ public void takeSnapshot() { snapshot = true; config.adc.setAdcEnabled(true); } /** * @param displayLogIntensity the displayLogIntensity to set */ public void setDisplayIntensity(boolean displayIntensity) { this.displayIntensity = displayIntensity; getPrefs().putBoolean("displayIntensity", displayIntensity); getAeViewer().interruptViewloop(); } /** * @return the displayLogIntensityChangeEvents */ public boolean isDisplayLogIntensityChangeEvents() { return displayLogIntensityChangeEvents; } /** * @param displayLogIntensityChangeEvents the displayLogIntensityChangeEvents to set */ public void setDisplayLogIntensityChangeEvents(boolean displayLogIntensityChangeEvents) { this.displayLogIntensityChangeEvents = displayLogIntensityChangeEvents; getPrefs().putBoolean("displayLogIntensityChangeEvents", displayLogIntensityChangeEvents); getAeViewer().interruptViewloop(); } /** * @return the ignoreReadout */ public boolean isIgnoreReadout() { return ignoreReadout; } /** * @param displayLogIntensityChangeEvents the displayLogIntensityChangeEvents to set */ public void setIgnoreReadout(boolean ignoreReadout) { this.ignoreReadout = ignoreReadout; getPrefs().putBoolean("ignoreReadout", ignoreReadout); getAeViewer().interruptViewloop(); } /** * Displays data from SeeBetter test chip SeeBetter10/11. * @author Tobi */ public class SBret10DisplayMethod extends DVSWithIntensityDisplayMethod { private TextRenderer renderer = null; private TextRenderer exposureRenderer = null; public SBret10DisplayMethod(SBret10 chip) { super(chip.getCanvas()); } @Override public void display(GLAutoDrawable drawable) { if (renderer == null) { renderer = new TextRenderer(new Font("SansSerif", Font.PLAIN, 18), true, true); renderer.setColor(1, .2f, .2f, 0.4f); } if (exposureRenderer == null) { exposureRenderer = new TextRenderer(new Font("SansSerif", Font.PLAIN, 8), true, true); exposureRenderer.setColor(1, 1, 1, 1); } super.display(drawable); GL gl = drawable.getGL(); gl.glLineWidth(2f); gl.glColor3f(1, 1, 1); // draw boxes around arrays rect(gl, 0, 0, 240, 180, "apsDVS"); } private void rect(GL gl, float x, float y, float w, float h, String txt) { gl.glPushMatrix(); gl.glTranslatef(-.5f, -.5f, 0); gl.glLineWidth(2f); gl.glColor3f(1, 1, 1); gl.glBegin(GL.GL_LINE_LOOP); gl.glVertex2f(x, y); gl.glVertex2f(x + w, y); gl.glVertex2f(x + w, y + h); gl.glVertex2f(x, y + h); gl.glEnd(); // label arrays if (txt != null) { renderer.begin3DRendering(); renderer.draw3D(txt, x, y, 0, .4f); // x,y,z, scale factor renderer.end3DRendering(); if(displayIntensity){ exposureRenderer.begin3DRendering(); String frequency = ""; if(frameTime>0){ frequency = "("+(float)1000000/frameTime+" Hz)"; } String expC = ""; if(config.useC.isSet()){ expC = " ms, exposure 2: "+(float)exposureC/1000; } exposureRenderer.draw3D("exposure 1: "+(float)exposureB/1000+expC+" ms, frame period: "+(float)frameTime/1000+" ms "+frequency, x, h, 0, .4f); // x,y,z, scale factor exposureRenderer.end3DRendering(); } } gl.glPopMatrix(); } } public IntensityFrameData getFrameData() { return frameEventPacket.getFrameData(); } /** Extends EventPacket to add the log intensity frame data */ public class FrameEventPacket extends EventPacket { public FrameEventPacket(Class eventClass) { super(eventClass); } /** * @return the frameData */ public IntensityFrameData getFrameData() { return frameData; } @Override public boolean isEmpty() { if (!frameData.isNewData() && super.isEmpty()) { return true; } return false; } @Override public String toString() { return "FrameEventPacket{" + "frameData=" + frameData + " " + super.toString() + '}'; } } /** * Renders complex data from SeeBetter chip. * * @author tobi */ public class SBret10Renderer extends RetinaRenderer { private SBret10 cDVSChip = null; // private final float[] redder = {1, 0, 0}, bluer = {0, 0, 1}, greener={0,1,0}, brighter = {1, 1, 1}, darker = {-1, -1, -1}; private final float[] brighter = {0, 1, 0}, darker = {1, 0, 0}; private int sizeX = 1; private LowpassFilter2d agcFilter = new LowpassFilter2d(); // 2 lp values are min and max log intensities from each frame private boolean agcEnabled; /** PropertyChange */ public static final String AGC_VALUES = "AGCValuesChanged"; /** PropertyChange when value is changed */ public static final String APS_INTENSITY_GAIN = "apsIntensityGain", APS_INTENSITY_OFFSET = "apsIntensityOffset"; /** Control scaling and offset of display of log intensity values. */ int apsIntensityGain, apsIntensityOffset; public SBret10Renderer(SBret10 chip) { super(chip); cDVSChip = chip; agcEnabled = chip.getPrefs().getBoolean("agcEnabled", false); setAGCTauMs(chip.getPrefs().getFloat("agcTauMs", 1000)); apsIntensityGain = chip.getPrefs().getInt("apsIntensityGain", 1); apsIntensityOffset = chip.getPrefs().getInt("apsIntensityOffset", 0); } /** Overridden to make gray buffer special for bDVS array */ @Override protected void resetPixmapGrayLevel(float value) { checkPixmapAllocation(); final int n = 3 * chip.getNumPixels(); boolean madebuffer = false; if (grayBuffer == null || grayBuffer.capacity() != n) { grayBuffer = FloatBuffer.allocate(n); // BufferUtil.newFloatBuffer(n); madebuffer = true; } if (madebuffer || value != grayValue) { grayBuffer.rewind(); for (int y = 0; y < sizeY; y++) { for (int x = 0; x < sizeX; x++) { if(displayLogIntensityChangeEvents){ grayBuffer.put(0); grayBuffer.put(0); grayBuffer.put(0); } else { grayBuffer.put(grayValue); grayBuffer.put(grayValue); grayBuffer.put(grayValue); } } } grayBuffer.rewind(); } System.arraycopy(grayBuffer.array(), 0, pixmap.array(), 0, n); pixmap.rewind(); pixmap.limit(n); // pixmapGrayValue = grayValue; } @Override public synchronized void render(EventPacket packet) { checkPixmapAllocation(); resetSelectedPixelEventCount(); // TODO fix locating pixel with xsel ysel if (packet == null) { return; } this.packet = packet; if (packet.getEventClass() != PolarityADCSampleEvent.class) { log.warning("wrong input event class, got " + packet.getEventClass() + " but we need to have " + PolarityADCSampleEvent.class); return; } float[] pm = getPixmapArray(); sizeX = chip.getSizeX(); //log.info("pm : "+pm.length+", sizeX : "+sizeX); if (!accumulateEnabled) { resetFrame(.5f); } //String eventData = "NULL"; boolean putADCData=displayIntensity && !getAeViewer().isPaused(); // don't keep reputting the ADC data into buffer when paused and rendering packet over and over again String event = ""; try { step = 1f / (colorScale); for (Object obj : packet) { PolarityADCSampleEvent e = (PolarityADCSampleEvent) obj; //eventData = "address:"+Integer.toBinaryString(e.address)+"( x: "+Integer.toString(e.x)+", y: "+Integer.toString(e.y)+"), data "+Integer.toBinaryString(e.adcSample)+" ("+Integer.toString(e.adcSample)+")"; //System.out.println("Event: "+eventData); if (putADCData && e.isAdcSample()) { // hack to detect ADC sample events // ADC 'event' frameData.putEvent(e); //log.info("put "+e.toString()); } else if (!e.isAdcSample()) { // real AER event int type = e.getType(); if(frameData.useDVSExtrapolation){ frameData.updateDVScalib(e.x, e.y, type==0); } if(displayLogIntensityChangeEvents){ if (xsel >= 0 && ysel >= 0) { // find correct mouse pixel interpretation to make sounds for large pixels int xs = xsel, ys = ysel; if (e.x == xs && e.y == ys) { playSpike(type); } } int x = e.x, y = e.y; switch (e.polarity) { case On: changePixel(x, y, pm, brighter, step); break; case Off: changePixel(x, y, pm, darker, step); break; } } } } if (displayIntensity) { int minADC = Integer.MAX_VALUE; int maxADC = Integer.MIN_VALUE; for (int y = 0; y < EntirePixelArray.height; y++) { for (int x = 0; x < EntirePixelArray.width; x++) { //event = "ADC x "+x+", y "+y; int count = frameData.get(x, y); if (agcEnabled) { if (count < minADC) { minADC = count; } else if (count > maxADC) { maxADC = count; } } float v = adc01normalized(count); float[] vv = {v, v, v}; changePixel(x, y, pm, vv, 1); } } if (agcEnabled && (minADC > 0 && maxADC > 0)) { // don't adapt to first frame which is all zeros Float filter2d = agcFilter.filter2d(minADC, maxADC, frameData.getTimestamp()); // System.out.println("agc minmax=" + filter2d + " minADC=" + minADC + " maxADC=" + maxADC); getSupport().firePropertyChange(AGC_VALUES, null, filter2d); // inform listeners (GUI) of new AGC min/max filterd log intensity values } } autoScaleFrame(pm); } catch (IndexOutOfBoundsException e) { log.warning(e.toString() + ": ChipRenderer.render(), some event out of bounds for this chip type? Event: "+event);//log.warning(e.toString() + ": ChipRenderer.render(), some event out of bounds for this chip type? Event: "+eventData); } pixmap.rewind(); } /** Changes scanned pixel value according to scan-out order * * @param ind the pixel to change, which marches from LL corner to right, then to next row up and so on. Physically on chip this is actually from UL corner. * @param f the pixmap RGB array * @param c the colors * @param step the step size which multiplies each color component */ private void changeCDVSPixel(int ind, float[] f, float[] c, float step) { float r = c[0] * step, g = c[1] * step, b = c[2] * step; f[ind] += r; f[ind + 1] += g; f[ind + 2] += b; } /** Changes pixmap location for pixel affected by this event. * x,y refer to space of pixels */ private void changePixel(int x, int y, float[] f, float[] c, float step) { int ind = 3* (x + y * sizeX); changeCDVSPixel(ind, f, c, step); } public void setDisplayLogIntensityChangeEvents(boolean displayIntensityChangeEvents) { cDVSChip.setDisplayLogIntensityChangeEvents(displayIntensityChangeEvents); } public void setDisplayIntensity(boolean displayIntensity) { cDVSChip.setDisplayIntensity(displayIntensity); } public boolean isDisplayLogIntensityChangeEvents() { return cDVSChip.isDisplayLogIntensityChangeEvents(); } public boolean isDisplayIntensity() { return cDVSChip.isDisplayIntensity(); } private float adc01normalized(int count) { float v; if (!agcEnabled) { v = (float) (apsIntensityGain*count+apsIntensityOffset) / (float) MAX_ADC; } else { Float filter2d = agcFilter.getValue2d(); float offset = filter2d.x; float range = (filter2d.y - filter2d.x); v = ((count - offset)) / range; // System.out.println("offset="+offset+" range="+range+" count="+count+" v="+v); } if (v < 0) { v = 0; } else if (v > 1) { v = 1; } return v; } public float getAGCTauMs() { return agcFilter.getTauMs(); } public void setAGCTauMs(float tauMs) { if (tauMs < 10) { tauMs = 10; } agcFilter.setTauMs(tauMs); chip.getPrefs().putFloat("agcTauMs", tauMs); } /** * @return the agcEnabled */ public boolean isAgcEnabled() { return agcEnabled; } /** * @param agcEnabled the agcEnabled to set */ public void setAgcEnabled(boolean agcEnabled) { this.agcEnabled = agcEnabled; chip.getPrefs().putBoolean("agcEnabled", agcEnabled); } void applyAGCValues() { Float f = agcFilter.getValue2d(); setApsIntensityOffset(agcOffset()); setApsIntensityGain(agcGain()); } private int agcOffset() { return (int) agcFilter.getValue2d().x; } private int agcGain() { Float f = agcFilter.getValue2d(); float diff = f.y - f.x; if (diff < 1) { return 1; } int gain = (int) (SBret10.MAX_ADC / (f.y - f.x)); return gain; } /** * Value from 1 to MAX_ADC. Gain of 1, offset of 0 turns full scale ADC to 1. Gain of MAX_ADC makes a single count go full scale. * @return the apsIntensityGain */ public int getApsIntensityGain() { return apsIntensityGain; } /** * Value from 1 to MAX_ADC. Gain of 1, offset of 0 turns full scale ADC to 1. * Gain of MAX_ADC makes a single count go full scale. * @param apsIntensityGain the apsIntensityGain to set */ public void setApsIntensityGain(int apsIntensityGain) { int old = this.apsIntensityGain; if (apsIntensityGain < 1) { apsIntensityGain = 1; } else if (apsIntensityGain > MAX_ADC) { apsIntensityGain = MAX_ADC; } this.apsIntensityGain = apsIntensityGain; chip.getPrefs().putInt("apsIntensityGain", apsIntensityGain); if (chip.getAeViewer() != null) { chip.getAeViewer().interruptViewloop(); } getSupport().firePropertyChange(APS_INTENSITY_GAIN, old, apsIntensityGain); } /** * Value subtracted from ADC count before gain multiplication. Ranges from 0 to MAX_ADC. * @return the apsIntensityOffset */ public int getApsIntensityOffset() { return apsIntensityOffset; } /** * Sets value subtracted from ADC count before gain multiplication. Clamped between 0 to MAX_ADC. * @param apsIntensityOffset the apsIntensityOffset to set */ public void setApsIntensityOffset(int apsIntensityOffset) { int old = this.apsIntensityOffset; if (apsIntensityOffset < 0) { apsIntensityOffset = 0; } else if (apsIntensityOffset > MAX_ADC) { apsIntensityOffset = MAX_ADC; } this.apsIntensityOffset = apsIntensityOffset; chip.getPrefs().putInt("apsIntensityOffset", apsIntensityOffset); if (chip.getAeViewer() != null) { chip.getAeViewer().interruptViewloop(); } getSupport().firePropertyChange(APS_INTENSITY_OFFSET, old, apsIntensityOffset); } } /** * * Holds the frame of log intensity values to be display for a chip with log intensity readout. * Applies calibration values to get() the values and supplies put() and resetWriteCounter() to put the values. * * @author Tobi */ public static enum Read{A, B, C, DIFF_B, DIFF_C, HDR, LOG_HDR}; public class IntensityFrameData { /** The scanner is 240wide by 180 high */ public final int WIDTH = EntirePixelArray.width, HEIGHT = EntirePixelArray.height; // width is BDVS pixels not scanner registers private final int NUMSAMPLES = WIDTH * HEIGHT; private int timestamp = 0; // timestamp of starting sample private float[] data = new float[NUMSAMPLES]; private float[] bDiffData = new float[NUMSAMPLES]; private float[] cDiffData = new float[NUMSAMPLES]; private float[] hdrData = new float[NUMSAMPLES]; private float[] oldData = new float[NUMSAMPLES]; private float[] displayData = new float[NUMSAMPLES]; private float[] onCalib = new float[NUMSAMPLES]; private float[] offCalib = new float[NUMSAMPLES]; private float onGain = 0f; private float offGain = 0f; private int[] onCount = new int[NUMSAMPLES]; private int[] offCount = new int[NUMSAMPLES]; private int[] aData, bData, cData; private float minC, maxC, maxB; /** Readers should access the current reading buffer. */ private int writeCounterA = 0; private int writeCounterB = 0; private boolean useDVSExtrapolation = getPrefs().getBoolean("useDVSExtrapolation", false); private boolean invertADCvalues = getPrefs().getBoolean("invertADCvalues", true); // true by default for log output which goes down with increasing intensity private Read displayRead = Read.DIFF_B; public IntensityFrameData() { minC = Integer.MAX_VALUE; maxB = 0; maxC = 0; aData = new int[NUMSAMPLES]; bData = new int[NUMSAMPLES]; cData = new int[NUMSAMPLES]; Arrays.fill(aData, 0); Arrays.fill(bData, 0); Arrays.fill(cData, 0); Arrays.fill(hdrData, 0); Arrays.fill(bDiffData, 0); Arrays.fill(cDiffData, 0); Arrays.fill(onCalib, 0); Arrays.fill(offCalib, 0); Arrays.fill(onCount, 0); Arrays.fill(offCount, 0); Arrays.fill(data, 0); Arrays.fill(displayData, 0); Arrays.fill(oldData, 0); } private int index(int x, int y){ final int idx = y + HEIGHT * x; return idx; } /** Gets the sample at a given pixel address (not scanner address) * * @param x pixel x from left side of array * @param y pixel y from top of array on chip * @return value from ADC */ private int outputData; public int get(int x, int y) { final int idx = index(x,y); // values are written by row for each column (row parallel readout in this chip, with columns addressed one by one) switch (displayRead) { case A: outputData = aData[idx]; break; case B: outputData = bData[idx]; break; case C: outputData = cData[idx]; break; case DIFF_B: default: if(useDVSExtrapolation){ outputData = (int)displayData[idx]; }else{ outputData = (int)bDiffData[idx]; } break; case DIFF_C: if(useDVSExtrapolation){ outputData = (int)displayData[idx]; }else{ outputData = (int)cDiffData[idx]; } break; case HDR: case LOG_HDR: if(useDVSExtrapolation){ outputData = (int)displayData[idx]; }else{ outputData = (int)hdrData[idx]; } break; } if (invertADCvalues) { return MAX_ADC - outputData; } else { return outputData; } } private void putEvent(PolarityADCSampleEvent e) { if(!e.isAdcSample()) return; if(e.startOfFrame) { resetWriteCounter(); setTimestamp(e.timestamp); } putNextSampleValue(e.adcSample, e.readoutType, index(e.x, e.y)); } private void putNextSampleValue(int val, PolarityADCSampleEvent.Type type, int index) { float value = 0; float valueB = 0; switch(type){ case C: if (index >= cData.length) { //log.info("buffer overflowed - missing start frame bit? index "+index); return; } if (index == NUMSAMPLES-1) { updateDVSintensities(); } cData[index] = val; cDiffData[index] = aData[index]-cData[index]; if(config.useC.isSet()){ if(displayRead==Read.LOG_HDR){ value = (float)Math.log(cDiffData[index]/exposureC); valueB = (float)Math.log(bDiffData[index]/exposureB); }else{ value = cDiffData[index]/exposureC; valueB = bDiffData[index]/exposureB; } if(value<minC){ minC = value; } if(value>maxC){ maxC = value; } if(valueB > value){ value = valueB; } // value = value + bDiffData[index]/(2*exposureB); hdrData[index]=MAX_ADC/(maxB-minC)*(value-minC); // if(maxC-(1000/exposureB) > value){ // hdrData[index]=MAX_ADC/(maxB-minC)*(value-minC); // }else{ // value = bDiffData[index]/exposureB; // hdrData[index]=MAX_ADC/(maxB-minC)*(value-minC); } break; case B: if (index >= bData.length) { // log.info("buffer overflowed - missing start frame bit?"); return; } // if (index == NUMSAMPLES-1) { // updateDVSintensities(); bData[index] = val; bDiffData[index] = aData[index]-bData[index]; if(!config.useC.isSet()){ data[index] = bDiffData[index]; } if(config.useC.isSet()){ if(displayRead==Read.LOG_HDR){ value = (float)Math.log(bDiffData[index]/exposureB); }else{ value = bDiffData[index]/exposureB; } if(value>maxB){ maxB = value; } } break; case A: default: if (index >= aData.length) { // log.info("buffer overflowed - missing start frame bit?"); return; } aData[index] = val; break; } } private void updateDVSintensities(){ float difference = 1; for(int i = 0; i < NUMSAMPLES; i++){ difference = data[i]-oldData[i]; if(difference != 0){ if(onCount[i] > 0 && oldData[i] > 0){ onGain = (float)(99*onGain+((difference-Math.log(oldData[i])*offGain*offCount[i])/onCount[i]))/100; } else if(offCount[i] > 0 && oldData[i] > 0){ offGain = (float)(99*offGain+((difference+Math.log(oldData[i])*onGain*onCount[i])/offCount[i]))/100; } } } System.arraycopy(data, 0, displayData, 0, NUMSAMPLES); System.arraycopy(data, 0, oldData, 0, NUMSAMPLES); Arrays.fill(onCount, 0); Arrays.fill(offCount, 0); } public void updateDVScalib(int x, int y, boolean isOn){ final int idx = index(x,y); if(isOn){ onCount[idx]++; //System.out.println("On event - data: "+displayData[idx]+" + calib: "+onGain+" => "+onGain*Math.log(displayData[idx])); displayData[idx] = (float)(displayData[idx]+onGain*Math.log(displayData[idx])); //System.out.println("displayData: "+displayData[idx]); } else { offCount[idx]++; //System.out.println("Off event - data: "+displayData[idx]+" + calib: "+offGain+" => "+onGain*Math.log(displayData[idx])); displayData[idx] = (float)(displayData[idx]+offGain*Math.log(displayData[idx])); //System.out.println("displayData: "+displayData[idx]); } } /** * @return the timestamp */ public int getTimestamp() { return timestamp; } /** * Sets the buffer timestamp. * @param timestamp the timestamp to set */ public void setTimestamp(int timestamp) { this.timestamp = timestamp; } /** * @return the useDVSExtrapolation */ public boolean isUseDVSExtrapolation() { return useDVSExtrapolation; } /** * @param useDVSExtrapolation the useOffChipCalibration to set */ public void setUseDVSExtrapolation(boolean useDVSExtrapolation) { this.useDVSExtrapolation = useDVSExtrapolation; getPrefs().putBoolean("useDVSExtrapolation", useDVSExtrapolation); } private int getMean(int[] dataIn) { int mean = 0; for (int i = 0; i < dataIn.length; i++) { mean += dataIn[i]; } mean = mean / dataIn.length; return mean; } private void subtractMean(int[] dataIn, int[] dataOut) { int mean = getMean(dataIn); for (int i = 0; i < dataOut.length; i++) { dataOut[i] = dataIn[i] - mean; } } public void setDisplayRead(Read displayRead){ this.displayRead = displayRead; } public Read getDisplayRead(){ return displayRead; } /** * @return the invertADCvalues */ public boolean isInvertADCvalues() { return invertADCvalues; } /** * @param invertADCvalues the invertADCvalues to set */ public void setInvertADCvalues(boolean invertADCvalues) { this.invertADCvalues = invertADCvalues; getPrefs().putBoolean("invertADCvalues", invertADCvalues); } public boolean isNewData() { return true; // dataWrittenSinceLastSwap; // TODO not working yet } @Override public String toString() { return "IntensityFrameData{" + "WIDTH=" + WIDTH + ", HEIGHT=" + HEIGHT + ", NUMSAMPLES=" + NUMSAMPLES + ", timestamp=" + timestamp + ", writeCounter=" + writeCounterA + '}'; } public void resetWriteCounter() { minC = Integer.MAX_VALUE; maxC = 0; maxB = 0; writeCounterA = 0; writeCounterB = 0; } final String CALIB1_KEY = "IntensityFrameData.calibData1", CALIB2_KEY = "IntensityFrameData.calibData2"; private void putArray(int[] array, String key) { if (array == null || key == null) { log.warning("null array or key"); return; } try { // Serialize to a byte array ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(bos); out.writeObject(array); out.close(); // Get the bytes of the serialized object byte[] buf = bos.toByteArray(); getPrefs().putByteArray(key, buf); } catch (Exception e) { log.warning(e.toString()); } } private int[] getArray(String key) { int[] ret = null; try { byte[] bytes = getPrefs().getByteArray(key, null); if (bytes != null) { ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes)); ret = (int[]) in.readObject(); in.close(); } } catch (Exception e) { log.warning(e.toString()); } return ret; } } }
package com.cmgapps.android.util; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.net.Uri; import android.text.format.DateUtils; import android.util.Log; public class CMGAppRater { private static final String TAG = "CMGAppRater"; private static final String APP_RATE_FILE_NAME = "CMGAppRater"; private static final int LAUNCHES_UNTIL_PROMPT = 10; private static final long DAYS_UNTIL_PROMPT = 7 * DateUtils.DAY_IN_MILLIS; private static final long DAYS_UNTIL_REMIND_AGAIN = 2 * DateUtils.DAY_IN_MILLIS; private static final String FIRST_USE = "first_use"; private static final String USE_COUNT = "use_count"; private static final String DECLINED_RATE = "declined_rate"; private static final String TRACKING_VERSION = "tracking_version"; private static final String REMIND_LATER_DATE = "remind_later_date"; private static final String APP_RATED = "rated"; private static final boolean RATER_DEBUG = false; private final SharedPreferences mPref; private final Context mContext; public CMGAppRater(Context context) { mContext = context; mPref = context.getSharedPreferences(APP_RATE_FILE_NAME, Context.MODE_PRIVATE); if (BuildConfig.DEBUG) Log.d(TAG, ratePreferenceToString(mPref)); } public synchronized boolean checkForRating() { if (RATER_DEBUG) return true; if (mPref.getBoolean(DECLINED_RATE, false)) return false; if (mPref.getBoolean(APP_RATED, false)) return false; if (System.currentTimeMillis() < (mPref.getLong(FIRST_USE, System.currentTimeMillis()) + DAYS_UNTIL_PROMPT)) return false; if (mPref.getInt(USE_COUNT, 0) <= LAUNCHES_UNTIL_PROMPT) return false; if (System.currentTimeMillis() < (mPref.getLong(REMIND_LATER_DATE, System.currentTimeMillis()) + DAYS_UNTIL_REMIND_AGAIN)) return false; return true; } public synchronized void incrementUseCount() { Editor editor = mPref.edit(); int version_code = 0; try { version_code = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0).versionCode; } catch (NameNotFoundException exc) { Log.e(TAG, "PackageName not found: " + mContext.getPackageName()); } int tracking_version = mPref.getInt(TRACKING_VERSION, -1); if (tracking_version == -1) { tracking_version = version_code; editor.putInt(TRACKING_VERSION, tracking_version); } if (tracking_version == version_code) { if (mPref.getLong(FIRST_USE, 0L) == 0L) editor.putLong(FIRST_USE, System.currentTimeMillis()); editor.putInt(USE_COUNT, mPref.getInt(USE_COUNT, 0) + 1); } else { editor.putInt(TRACKING_VERSION, version_code).putLong(FIRST_USE, System.currentTimeMillis()).putInt(USE_COUNT, 1) .putBoolean(DECLINED_RATE, false).putLong(REMIND_LATER_DATE, 0L).putBoolean(APP_RATED, false); } editor.commit(); } @SuppressLint("StringFormatMatches") public void show() { final Editor editor = mPref.edit(); final PackageManager pm = mContext.getPackageManager(); String appName = null; try { ApplicationInfo ai = pm.getApplicationInfo(mContext.getPackageName(), 0); appName = (String) pm.getApplicationLabel(ai); } catch (final NameNotFoundException e) { Log.e(TAG, "Application with the package name '" + mContext.getPackageName() + "' can not be found"); appName = ""; } new AlertDialog.Builder(mContext).setTitle(R.string.dialog_cmgrate_title) .setMessage(mContext.getString(R.string.dialog_cmgrate_message, appName)).setCancelable(false) .setIcon(mContext.getApplicationInfo().icon) .setPositiveButton(mContext.getString(R.string.dialog_cmgrate_ok, appName), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { editor.putBoolean(APP_RATED, true); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + mContext.getPackageName())); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); mContext.startActivity(intent); editor.commit(); dialog.dismiss(); } }).setNegativeButton(R.string.dialog_cmgrate_no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { editor.putBoolean(DECLINED_RATE, true).commit(); dialog.dismiss(); } }).setNeutralButton(R.string.dialog_cmgrate_later, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { editor.putLong(REMIND_LATER_DATE, System.currentTimeMillis()).commit(); dialog.dismiss(); } }).show(); editor.commit(); } private static String ratePreferenceToString(SharedPreferences pref) { StringBuilder builder = new StringBuilder("CMG App Rater Preferences: "); builder.append(DECLINED_RATE).append(": ").append(pref.getBoolean(DECLINED_RATE, false)).append(", "); builder.append(APP_RATED).append(": ").append(pref.getBoolean(APP_RATED, false)).append(", "); builder.append(TRACKING_VERSION).append(": ").append(pref.getInt(TRACKING_VERSION, -1)).append(", "); builder.append(FIRST_USE).append(": ").append(pref.getLong(FIRST_USE, 0L)).append(", "); builder.append(USE_COUNT).append(": ").append(pref.getInt(USE_COUNT, 0)).append(", "); builder.append(REMIND_LATER_DATE).append(": ").append(pref.getLong(REMIND_LATER_DATE, 0)); return builder.toString(); } }
package com.ecyrd.jspwiki.ui; import com.ecyrd.jspwiki.TextUtil; /** * Abstract, immutable Command implementation class. All of the fields in this * class are <code>final</code>. This class is thread-safe. * @author Andrew Jaquith * @since 2.4.22 */ public abstract class AbstractCommand implements Command { private static final Command[] ALL_COMMANDS = new Command[] { PageCommand.ATTACH, PageCommand.COMMENT, PageCommand.CONFLICT, PageCommand.DELETE, PageCommand.DIFF, PageCommand.EDIT, PageCommand.INFO, PageCommand.NONE, PageCommand.OTHER, PageCommand.PREVIEW, PageCommand.RENAME, PageCommand.RSS, PageCommand.UPLOAD, PageCommand.VIEW, GroupCommand.DELETE_GROUP, GroupCommand.EDIT_GROUP, GroupCommand.VIEW_GROUP, WikiCommand.CREATE_GROUP, WikiCommand.ERROR, WikiCommand.FIND, WikiCommand.INSTALL, WikiCommand.LOGIN, WikiCommand.LOGOUT, WikiCommand.PREFS, RedirectCommand.REDIRECT }; private static final String HTTPS = "HTTPS: private static final String HTTP = "HTTP: private final String m_jsp; private final String m_jspFriendlyName; private final String m_urlPattern; private final String m_requestContext; private final String m_contentTemplate; private final Object m_target; protected AbstractCommand( String requestContext, String urlPattern, String contentTemplate, Object target ) { if ( requestContext == null || urlPattern == null ) { throw new IllegalArgumentException( "Request context, URL pattern and type must not be null." ); } m_requestContext = requestContext; if ( (urlPattern.toUpperCase().startsWith( HTTP ) || urlPattern.toUpperCase().endsWith( HTTPS ) ) ) { // For an HTTP/HTTPS url, pass it through without modification m_jsp = urlPattern; m_jspFriendlyName = "Special Page"; } else { // For local JSPs, take everything to the left of ?, then // delete all variables String jsp = urlPattern; int qPosition = urlPattern.indexOf( '?' ); if ( qPosition != -1 ) { jsp = jsp.substring( 0, qPosition ); } m_jsp = jsp.replaceAll( "\u0025[a-z|A-Z]", "" ); // Calculate the "friendly name" for the JSP if ( m_jsp.toUpperCase().endsWith( ".JSP" ) ) { m_jspFriendlyName = TextUtil.beautifyString( m_jsp.substring( 0, m_jsp.length() - 4 ) ); } else { m_jspFriendlyName = m_jsp; } } m_urlPattern = urlPattern; m_contentTemplate = contentTemplate; m_target = target; } /** * Returns a defensively-created array of all * static Commands. * @return the array of commands */ public static final Command[] allCommands() { return (Command[])ALL_COMMANDS.clone(); } /** * @see com.ecyrd.jspwiki.ui.Command#targetedCommand(Object) */ public abstract Command targetedCommand( Object target ); /** * @see com.ecyrd.jspwiki.ui.Command#getContentTemplate() */ public final String getContentTemplate() { return m_contentTemplate; } /** * @see com.ecyrd.jspwiki.ui.Command#getJSP() */ public final String getJSP() { return m_jsp; } /** * @see com.ecyrd.jspwiki.ui.Command#getName() */ public abstract String getName(); /** * @see com.ecyrd.jspwiki.ui.Command#getRequestContext() */ public final String getRequestContext() { return m_requestContext; } /** * @see com.ecyrd.jspwiki.ui.Command#getTarget() */ public final Object getTarget() { return m_target; } /** * @see com.ecyrd.jspwiki.ui.Command#getURLPattern() */ public final String getURLPattern() { return m_urlPattern; } /** * Returns the "friendly name" for this command's JSP, namely * a beatified version of the JSP's name without the .jsp suffix. * @return the friendly name */ protected final String getJSPFriendlyName() { return m_jspFriendlyName; } /** * Returns a String representation of the Command. * @see java.lang.Object#toString() */ public final String toString() { return "Command" + "[context=" + m_requestContext + "," + "urlPattern=" + m_urlPattern + "," + "jsp=" + m_jsp + ( m_target == null ? "" : ",target=" + m_target + m_target.toString() ) + "]"; } }
package com.epictodo.controller.json; import com.epictodo.model.Task; import com.google.gson.FieldNamingPolicy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; public class Storage { /** * This method instantiates a GSON Object. * Method will read JSON Object from memory and translates to JSON. * * @return Gson */ private static Gson instantiateObject() { GsonBuilder gson_builder = new GsonBuilder(); gson_builder.setPrettyPrinting() .serializeNulls() .disableHtmlEscaping() .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES); Gson _gson = gson_builder.create(); return _gson; } /** * This method saves ArrayList<Task> from memory object to Json file. * * @param file_name * @param array_list * @return boolean */ public static boolean saveToJson(String file_name, ArrayList<Task> array_list) { assert file_name.equalsIgnoreCase("storage.txt"); try { FileWriter file_writer = new FileWriter(file_name); Gson _gson = instantiateObject(); String json_result = _gson.toJson(array_list); if (array_list.isEmpty()) { file_writer.write(""); } else { file_writer.write(json_result); } file_writer.close(); } catch(IOException ex) { ex.printStackTrace(); return false; } return true; } /** * This method loads the Json file to ArrayList<Task> of memory objects * * @param file_name * @return ArrayList<Task> */ public static ArrayList<Task> loadDbFile(String file_name) { ArrayList<Task> _result = new ArrayList<Task>(); assert file_name.equalsIgnoreCase("storage.txt"); try { FileReader _reader = new FileReader(file_name); Gson _gson = instantiateObject(); TypeToken<ArrayList<Task>> type_token = new TypeToken<ArrayList<Task>>(){}; _result = _gson.fromJson(_reader, type_token.getType()); } catch(IOException ex) { ex.printStackTrace(); return null; } return _result; } }
package com.haskforce.parsing; import com.haskforce.parsing.jsonParser.JsonParser; import com.haskforce.parsing.srcExtsDatatypes.*; import com.intellij.lang.ASTNode; import com.intellij.lang.PsiBuilder; import com.intellij.lang.PsiParser; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.psi.tree.IElementType; import org.jetbrains.annotations.NotNull; import static com.haskforce.parsing.HaskellTypes2.*; // These can be imported as * when the old parser is removed. import static com.haskforce.psi.HaskellTypes.OPENPRAGMA; import static com.haskforce.psi.HaskellTypes.CLOSEPRAGMA; import static com.haskforce.psi.HaskellTypes.OPENCOM; import static com.haskforce.psi.HaskellTypes.CLOSECOM; import static com.haskforce.psi.HaskellTypes.CPPIF; import static com.haskforce.psi.HaskellTypes.CPPELSE; import static com.haskforce.psi.HaskellTypes.CPPENDIF; import static com.haskforce.psi.HaskellTypes.COMMENT; import static com.haskforce.psi.HaskellTypes.COMMENTTEXT; import static com.haskforce.psi.HaskellTypes.DOUBLEQUOTE; import static com.haskforce.psi.HaskellTypes.STRINGTOKEN; import static com.haskforce.psi.HaskellTypes.BADSTRINGTOKEN; import static com.haskforce.psi.HaskellTypes.MODULE; import static com.haskforce.psi.HaskellTypes.WHERE; import static com.haskforce.psi.HaskellTypes.PRAGMA; import static com.haskforce.psi.HaskellTypes.EQUALS; import static com.haskforce.psi.HaskellTypes.IMPORT; import static com.haskforce.psi.HaskellTypes.QUALIFIED; import static com.haskforce.psi.HaskellTypes.HIDING; import static com.haskforce.psi.HaskellTypes.PERIOD; import static com.haskforce.psi.HaskellTypes.DOUBLEPERIOD; import static com.haskforce.psi.HaskellTypes.RPAREN; import static com.haskforce.psi.HaskellTypes.LPAREN; import static com.haskforce.psi.HaskellTypes.RBRACKET; import static com.haskforce.psi.HaskellTypes.LBRACKET; import static com.haskforce.psi.HaskellTypes.AS; import static com.haskforce.psi.HaskellTypes.TYPE; import static com.haskforce.psi.HaskellTypes.DATA; import static com.haskforce.psi.HaskellTypes.IN; import static com.haskforce.psi.HaskellTypes.DOUBLECOLON; import static com.haskforce.psi.HaskellTypes.COLON; import static com.haskforce.psi.HaskellTypes.COMMA; import static com.haskforce.psi.HaskellTypes.RIGHTARROW; import static com.haskforce.psi.HaskellTypes.LEFTARROW; import static com.haskforce.psi.HaskellTypes.MINUS; import static com.haskforce.psi.HaskellTypes.DO; import static com.haskforce.psi.HaskellTypes.BACKSLASH; import static com.haskforce.psi.HaskellTypes.HASH; import static com.haskforce.psi.HaskellTypes.FOREIGN; import static com.haskforce.psi.HaskellTypes.EXPORTTOKEN; import static com.haskforce.psi.HaskellTypes.DOUBLEARROW; import static com.haskforce.psi.HaskellTypes.BACKTICK; import static com.haskforce.psi.HaskellTypes.INSTANCE; import static com.haskforce.psi.HaskellTypes.LBRACE; import static com.haskforce.psi.HaskellTypes.RBRACE; import static com.haskforce.psi.HaskellTypes.EXLAMATION; // FIXME: Rename. import static com.haskforce.psi.HaskellTypes.PIPE; import static com.haskforce.psi.HaskellTypes.CHARTOKEN; import static com.haskforce.psi.HaskellTypes.LET; import static com.haskforce.psi.HaskellTypes.INTEGERTOKEN; import static com.haskforce.psi.HaskellTypes.VARIDREGEXP; import static com.haskforce.psi.HaskellTypes.ASTERISK; import static com.haskforce.psi.HaskellTypes.SINGLEQUOTE; import static com.haskforce.psi.HaskellTypes.DEFAULT; import static com.haskforce.psi.HaskellTypes.AMPERSAT; import static com.haskforce.psi.HaskellTypes.PLUS; import static com.haskforce.psi.HaskellTypes.TILDE; import static com.haskforce.psi.HaskellTypes.THEN; import static com.haskforce.psi.HaskellTypes.CASE; import static com.haskforce.psi.HaskellTypes.OF; import static com.haskforce.psi.HaskellTypes.SEMICOLON; import static com.haskforce.psi.HaskellTypes.DERIVING; import static com.haskforce.psi.HaskellTypes.FLOATTOKEN; import static com.haskforce.psi.HaskellTypes.IF; import static com.haskforce.psi.HaskellTypes.ELSE; /** * New Parser using parser-helper. */ public class HaskellParser2 implements PsiParser { private static final Logger LOG = Logger.getInstance(HaskellParser2.class); private final Project myProject; private final JsonParser myJsonParser; public HaskellParser2(@NotNull Project project) { myProject = project; myJsonParser = new JsonParser(project); } @NotNull @Override public ASTNode parse(IElementType root, PsiBuilder builder) { PsiBuilder.Marker rootMarker = builder.mark(); TopPair tp = myJsonParser.parse(builder.getOriginalText()); if (tp.error != null && !tp.error.isEmpty()) { // TODO: Parse failed. Possibly warn. Could be annoying. } IElementType e = builder.getTokenType(); while (!builder.eof() && (isInterruption(e) && e != OPENPRAGMA)) { if (e == COMMENT || e == OPENCOM) { parseComment(e, builder, tp.comments); e = builder.getTokenType(); } else if (e == CPPIF || e == CPPELSE || e == CPPENDIF) { // Ignore CPP-tokens, they are not fed to parser-helper anyways. builder.advanceLexer(); e = builder.getTokenType(); } else { throw new RuntimeException("Unexpected failure on:" + e.toString()); } } parseModule(builder, (Module) tp.moduleType, tp.comments); return chewEverything(rootMarker, root, builder); } private static ASTNode chewEverything(PsiBuilder.Marker marker, IElementType e, PsiBuilder builder) { while (!builder.eof()) { builder.advanceLexer(); } marker.done(e); ASTNode result = builder.getTreeBuilt(); // System.out.println("Psifile:" + builder.getTreeBuilt().getPsi().getContainingFile().getName()); return result; } /** * Parses a complete module. */ private static void parseModule(PsiBuilder builder, Module module, Comment[] comments) { parseModulePragmas(builder, module == null ? null : module.modulePragmas, comments); parseModuleHead(builder, module == null ? null : module.moduleHeadMaybe, comments); parseImportDecls(builder, module == null ? null : module.importDecls, comments); parseBody(builder, module == null ? null : module.decls, comments); } /** * Parses "module NAME [modulepragmas] [exportSpecList] where". */ private static void parseModuleHead(PsiBuilder builder, ModuleHead head, Comment[] comments) { IElementType e = builder.getTokenType(); if (e != MODULE) return; PsiBuilder.Marker moduleMark = builder.mark(); consumeToken(builder, MODULE); parseModuleName(builder, head == null ? null : head.moduleName, comments); // TODO: parseExportSpecList(builder, head.exportSpecList, comments); IElementType e2 = builder.getTokenType(); while (e2 != WHERE) { if (e2 == OPENPRAGMA) { parseGenericPragma(builder, null, comments); } else { builder.advanceLexer(); } e2 = builder.getTokenType(); } consumeToken(builder, WHERE); moduleMark.done(e); } private static void parseModuleName(PsiBuilder builder, ModuleName name, Comment[] comments) { builder.getTokenType(); // Need to getTokenType to advance lexer over whitespace. int startPos = builder.getCurrentOffset(); IElementType e = builder.getTokenType(); while ((name != null && (builder.getCurrentOffset() - startPos) < name.name.length()) || name == null && e != WHERE) { builder.remapCurrentToken(NAME); consumeToken(builder, NAME); e = builder.getTokenType(); if (e == PERIOD) builder.advanceLexer(); } } /** * Parses a list of import statements. */ private static void parseImportDecls(PsiBuilder builder, ImportDecl[] importDecls, Comment[] comments) { IElementType e = builder.getTokenType(); int i = 0; while (isInterruption(e) || importDecls != null && i < importDecls.length) { if (e == CPPIF || e == CPPELSE || e == CPPENDIF) { builder.advanceLexer(); e = builder.getTokenType(); continue; } else if (e == OPENCOM) { parseComment(e, builder, comments); e = builder.getTokenType(); continue; } else if (e == OPENPRAGMA) { parseGenericPragma(builder, null, comments); e = builder.getTokenType(); continue; } if (e != IMPORT) return; parseImportDecl(builder, importDecls[i], comments); i++; e = builder.getTokenType(); } } /** * Returns true for elements that can occur anywhere in the tree, * for example comments or pragmas. */ private static boolean isInterruption(IElementType e) { return (e == CPPIF || e == CPPELSE || e == CPPENDIF || e == OPENCOM || e == OPENPRAGMA); } /** * Parses an import statement. */ private static void parseImportDecl(PsiBuilder builder, ImportDecl importDecl, Comment[] comments) { IElementType e = builder.getTokenType(); PsiBuilder.Marker importMark = builder.mark(); consumeToken(builder, IMPORT); IElementType e2 = builder.getTokenType(); if (e2 == QUALIFIED || (importDecl != null && importDecl.importQualified)) { consumeToken(builder, QUALIFIED); } parseModuleName(builder, importDecl == null ? null : importDecl.importModule, comments); e2 = builder.getTokenType(); if (e2 == AS || false) { // TODO: Update. consumeToken(builder, AS); e2 = builder.getTokenType(); parseModuleName(builder, importDecl == null ? null : importDecl.importAs, comments); e2 = builder.getTokenType(); } if (e2 == HIDING || false) { // (importDecl != null && importDecl.importSpecs)) { TODO: FIXME consumeToken(builder, HIDING); e2 = builder.getTokenType(); } int nest = e2 == LPAREN ? 1 : 0; while (nest > 0) { builder.advanceLexer(); e2 = builder.getTokenType(); if (e2 == LPAREN) { nest++; } else if (e2 == RPAREN) { nest } } if (e2 == RPAREN) consumeToken(builder, RPAREN); importMark.done(e); } /** * Parses a foreign import statement. */ private static void parseForeignImportDecl(PsiBuilder builder, ForImp importDecl, Comment[] comments) { IElementType e = builder.getTokenType(); consumeToken(builder, FOREIGN); consumeToken(builder, IMPORT); IElementType e2 = builder.getTokenType(); builder.advanceLexer(); // TODO: Parse 'ccall' etc. e2 = builder.getTokenType(); if (e2 != DOUBLEQUOTE) { // TODO: Parse safety. builder.advanceLexer(); e2 = builder.getTokenType(); } if (e2 == DOUBLEQUOTE || false) { parseStringLiteral(builder); } e2 = builder.getTokenType(); parseName(builder, importDecl.name, comments); e2 = builder.getTokenType(); consumeToken(builder, DOUBLECOLON); parseTypeTopType(builder, importDecl.type, comments); } /** * Parses a foreign export statement. */ private static void parseForeignExportDecl(PsiBuilder builder, ForExp forExp, Comment[] comments) { IElementType e = builder.getTokenType(); consumeToken(builder, FOREIGN); e = builder.getTokenType(); consumeToken(builder, EXPORTTOKEN); IElementType e2 = builder.getTokenType(); builder.advanceLexer(); // TODO: Parse 'ccall' etc. e2 = builder.getTokenType(); if (e2 == DOUBLEQUOTE || false) { parseStringLiteral(builder); } e2 = builder.getTokenType(); parseName(builder, forExp.name, comments); e2 = builder.getTokenType(); consumeToken(builder, DOUBLECOLON); parseTypeTopType(builder, forExp.type, comments); } private static void parseBody(PsiBuilder builder, DeclTopType[] decls, Comment[] comments) { IElementType e = builder.getTokenType(); int i = 0; while (isInterruption(e) || decls != null && i < decls.length) { if (e == CPPIF || e == CPPELSE || e == CPPENDIF) { builder.advanceLexer(); e = builder.getTokenType(); continue; } else if (e == OPENCOM) { parseComment(e, builder, comments); e = builder.getTokenType(); continue; } else if (e == OPENPRAGMA) { parseGenericPragma(builder, null, comments); e = builder.getTokenType(); continue; } parseDecl(builder, decls[i], comments); e = builder.getTokenType(); i++; } } /** * Parse a list of declarations. */ private static void parseDecls(PsiBuilder builder, DeclTopType[] decl, Comment[] comments) { IElementType e = builder.getTokenType(); int i = 0; while (decl != null && i < decl.length) { parseDecl(builder, decl[i], comments); i++; e = builder.getTokenType(); } } /** * Parse a single declaration. */ private static void parseDecl(PsiBuilder builder, DeclTopType decl, Comment[] comments) { IElementType e = builder.getTokenType(); // Pragmas are handled by the outer loop in parseBody, so they are no-ops. if (decl instanceof PatBind) { PsiBuilder.Marker declMark = builder.mark(); parsePatBind(builder, (PatBind) decl, comments); declMark.done(e); } else if (decl instanceof FunBind) { PsiBuilder.Marker declMark = builder.mark(); parseFunBind(builder, (FunBind) decl, comments); declMark.done(e); } else if (decl instanceof DataDecl) { PsiBuilder.Marker declMark = builder.mark(); parseDataDecl(builder, (DataDecl) decl, comments); declMark.done(e); } else if (decl instanceof TypeDecl) { PsiBuilder.Marker declMark = builder.mark(); parseTypeDecl(builder, (TypeDecl) decl, comments); declMark.done(e); } else if (decl instanceof DataInsDecl) { PsiBuilder.Marker declMark = builder.mark(); parseDataInstanceDecl(builder, (DataInsDecl) decl, comments); declMark.done(e); } else if (decl instanceof GDataInsDecl) { PsiBuilder.Marker declMark = builder.mark(); parseGDataInstanceDecl(builder, (GDataInsDecl) decl, comments); declMark.done(e); } else if (decl instanceof InstDecl) { PsiBuilder.Marker declMark = builder.mark(); parseInstDecl(builder, (InstDecl) decl, comments); declMark.done(e); } else if (decl instanceof DerivDecl) { PsiBuilder.Marker declMark = builder.mark(); parseDerivDecl(builder, (DerivDecl) decl, comments); declMark.done(e); } else if (decl instanceof InfixDecl) { PsiBuilder.Marker declMark = builder.mark(); parseInfixDecl(builder, (InfixDecl) decl, comments); declMark.done(e); } else if (decl instanceof DefaultDecl) { PsiBuilder.Marker declMark = builder.mark(); parseDefaultDecl(builder, (DefaultDecl) decl, comments); declMark.done(e); } else if (decl instanceof SpliceDecl) { PsiBuilder.Marker declMark = builder.mark(); parseExpTopType(builder, ((SpliceDecl) decl).exp, comments); declMark.done(e); } else if (decl instanceof TypeSig) { PsiBuilder.Marker declMark = builder.mark(); parseTypeSig(builder, (TypeSig) decl, comments); declMark.done(e); } else if (decl instanceof ForImp) { PsiBuilder.Marker declMark = builder.mark(); parseForeignImportDecl(builder, (ForImp) decl, comments); declMark.done(e); } else if (decl instanceof ForExp) { PsiBuilder.Marker declMark = builder.mark(); parseForeignExportDecl(builder, (ForExp) decl, comments); declMark.done(e); } else if (decl instanceof InlineSig) { // parseGenericPragma(builder, (InlineSig) decl, comments); } else if (decl instanceof InlineConlikeSig) { // parseGenericPragma(builder, (InlineConlikeSig) decl, comments); } else if (decl instanceof SpecSig) { // parseGenericPragma(builder, (SpecSig) decl, comments); } else if (decl instanceof SpecInlineSig) { // parseGenericPragma(builder, (SpecSig) decl, comments); } else if (decl instanceof RulePragmaDecl) { // parseGenericPragma(builder, (SpecSig) decl, comments); } else if (decl instanceof DeprPragmaDecl) { // parseGenericPragma(builder, (DeprPragmaDecl) decl, comments); } else if (decl instanceof WarnPragmaDecl) { // parseGenericPragma(builder, (WarnPragmaDecl) decl, comments); } else if (decl instanceof InstSig) { PsiBuilder.Marker declMark = builder.mark(); parseInstSig(builder, (InstSig) decl, comments); declMark.done(e); } else if (decl instanceof AnnPragma) { // parseGenericPragma(builder, (AnnPragma) decl, comments); } else { throw new RuntimeException("Unexpected decl type: " + decl.toString()); } } /** * Parse a pattern binding. */ private static void parsePatBind(PsiBuilder builder, PatBind patBind, Comment[] comments) { IElementType e = builder.getTokenType(); parsePatTopType(builder, patBind.pat, comments); if (patBind.type != null) throw new RuntimeException("Unexpected type in patbind"); // TODO: parseType(builder, patBind.type, comments); parseRhsTopType(builder, patBind.rhs, comments); if (patBind.binds != null) throw new RuntimeException("Unexpected binds in patbind"); } /** * Parse a function binding. */ private static void parseFunBind(PsiBuilder builder, FunBind funBind, Comment[] comments) { IElementType e = builder.getTokenType(); int i = 0; while (funBind.match != null && i < funBind.match.length) { parseMatchTop(builder, funBind.match[i], comments); i++; } } /** * Parse a derive declaration. */ private static void parseDerivDecl(PsiBuilder builder, DerivDecl derivDecl, Comment[] comments) { IElementType e = builder.getTokenType(); consumeToken(builder, DERIVING); e = builder.getTokenType(); consumeToken(builder, INSTANCE); parseContextTopType(builder, derivDecl.contextMaybe, comments); e = builder.getTokenType(); parseInstHead(builder, derivDecl.instHead, comments); e = builder.getTokenType(); } /** * Parses an instance specialization. */ private static void parseInstSig(PsiBuilder builder, InstSig instSig, Comment[] comments) { IElementType e = builder.getTokenType(); parseGenericPragma(builder, null, null); e = builder.getTokenType(); // TODO: Improve precision of specialize instance pragma parsing. // parseContextTopType(builder, instSig.contextMaybe, comments); // e = builder.getTokenType(); // parseInstHead(builder, instSig.instHead, comments); // e = builder.getTokenType(); } /** * Parse a instance declaration. */ private static void parseInstDecl(PsiBuilder builder, InstDecl instDecl, Comment[] comments) { IElementType e = builder.getTokenType(); consumeToken(builder, INSTANCE); e = builder.getTokenType(); parseContextTopType(builder, instDecl.contextMaybe, comments); e = builder.getTokenType(); if (instDecl.contextMaybe != null) consumeToken(builder, DOUBLEARROW); parseInstHead(builder, instDecl.instHead, comments); e = builder.getTokenType(); consumeToken(builder, WHERE); parseInstDeclTopTypes(builder, instDecl.instDecls, comments); e = builder.getTokenType(); } /** * Parse a list of instance declarations. */ private static void parseInstDeclTopTypes(PsiBuilder builder, InstDeclTopType[] instDecls, Comment[] comments) { IElementType e = builder.getTokenType(); int i = 0; while (instDecls != null && i < instDecls.length) { parseInstDeclTopType(builder, instDecls[i], comments); i++; } } /** * Parses a single instance declaration. */ private static void parseInstDeclTopType(PsiBuilder builder, InstDeclTopType decl, Comment[] comments) { IElementType e = builder.getTokenType(); if (decl instanceof InsDecl) { parseDecl(builder, ((InsDecl) decl).decl, comments); e = builder.getTokenType(); } else if (decl instanceof InsType) { throw new RuntimeException("InsType not implemented: " + decl.toString()); /* Preliminary implementation: parseTypeTopType(builder, ((InsType) decl).t1, comments); e = builder.getTokenType(); parseTypeTopType(builder, ((InsType) decl).t2, comments); e = builder.getTokenType(); */ } else if (decl instanceof InsData) { throw new RuntimeException("InsData not implemented:" + decl.toString()); } else if (decl instanceof InsGData) { throw new RuntimeException("InsGData not implemented:" + decl.toString()); } } /** * Parses a data declaration. */ private static void parseDataDecl(PsiBuilder builder, DataDecl dataDecl, Comment[] comments) { IElementType e = builder.getTokenType(); consumeToken(builder, DATA); parseDeclHead(builder, dataDecl.declHead, comments); e = builder.getTokenType(); if (e == EQUALS) consumeToken(builder, EQUALS); int i = 0; e = builder.getTokenType(); while (dataDecl.qualConDecls != null && i < dataDecl.qualConDecls.length) { parseQualConDecl(builder, dataDecl.qualConDecls[i], comments); i++; if (i < dataDecl.qualConDecls.length) { builder.advanceLexer(); e = builder.getTokenType(); } } } /** * Parses a data instance declaration. */ private static void parseDataInstanceDecl(PsiBuilder builder, DataInsDecl dataDecl, Comment[] comments) { IElementType e = builder.getTokenType(); consumeToken(builder, DATA); e = builder.getTokenType(); consumeToken(builder, INSTANCE); e = builder.getTokenType(); parseTypeTopType(builder, dataDecl.type, comments); e = builder.getTokenType(); if (e == EQUALS) consumeToken(builder, EQUALS); int i = 0; e = builder.getTokenType(); while (dataDecl.qualConDecls != null && i < dataDecl.qualConDecls.length) { parseQualConDecl(builder, dataDecl.qualConDecls[i], comments); i++; if (i < dataDecl.qualConDecls.length) { builder.advanceLexer(); e = builder.getTokenType(); } } e = builder.getTokenType(); if (dataDecl.derivingMaybe != null) throw new RuntimeException("TODO: deriving unimplemeted"); } /** * Parses a gadt-style data instance declaration. */ private static void parseGDataInstanceDecl(PsiBuilder builder, GDataInsDecl gDataInsDecl, Comment[] comments) { IElementType e = builder.getTokenType(); consumeToken(builder, DATA); e = builder.getTokenType(); consumeToken(builder, INSTANCE); e = builder.getTokenType(); parseTypeTopType(builder, gDataInsDecl.type, comments); e = builder.getTokenType(); parseKindTopType(builder, gDataInsDecl.kindMaybe, comments); e = builder.getTokenType(); if (e == WHERE) consumeToken(builder, WHERE); int i = 0; e = builder.getTokenType(); while (gDataInsDecl.gadtDecls != null && i < gDataInsDecl.gadtDecls.length) { parseGadtDecl(builder, gDataInsDecl.gadtDecls[i], comments); i++; if (i < gDataInsDecl.gadtDecls.length) { builder.advanceLexer(); e = builder.getTokenType(); } } e = builder.getTokenType(); if (gDataInsDecl.derivingMaybe != null) throw new RuntimeException("TODO: deriving unimplemeted"); } /** * Parse a single gadt-style declaration. */ private static void parseGadtDecl(PsiBuilder builder, GadtDecl gadtDecl, Comment[] comments) { IElementType e = builder.getTokenType(); parseName(builder, gadtDecl.name, comments); e = builder.getTokenType(); consumeToken(builder, DOUBLECOLON); e = builder.getTokenType(); parseTypeTopType(builder, gadtDecl.type, comments); e = builder.getTokenType(); } /** * Parses the left side of '=' in a data/type declaration. */ private static void parseDeclHead(PsiBuilder builder, DeclHeadTopType declHead, Comment[] comments) { IElementType e = builder.getTokenType(); if (declHead instanceof DHead) { parseName(builder, ((DHead) declHead).name, comments); e = builder.getTokenType(); parseTyVarBinds(builder, ((DHead) declHead).tyVars, comments); } else if (declHead instanceof DHInfix) { parseTyVarBind(builder, ((DHInfix) declHead).tb1, comments); e = builder.getTokenType(); parseName(builder, ((DHInfix) declHead).name, comments); e = builder.getTokenType(); parseTyVarBind(builder, ((DHInfix) declHead).tb2, comments); e = builder.getTokenType(); } else if (declHead instanceof DHParen) { consumeToken(builder, LPAREN); e = builder.getTokenType(); parseDeclHead(builder, ((DHParen) declHead).declHead, comments); e = builder.getTokenType(); consumeToken(builder, RPAREN); e = builder.getTokenType(); } } /** * Parses the left side of '=>' in an instance declaration. */ private static void parseInstHead(PsiBuilder builder, InstHeadTopType instHead, Comment[] comments) { IElementType e = builder.getTokenType(); if (instHead instanceof IHead) { parseQName(builder, ((IHead) instHead).qName, comments); e = builder.getTokenType(); parseTypeTopTypes(builder, ((IHead) instHead).types, comments); e = builder.getTokenType(); } else if (instHead instanceof IHInfix) { parseTypeTopType(builder, ((IHInfix) instHead).t1, comments); e = builder.getTokenType(); parseQName(builder, ((IHInfix) instHead).qName, comments); e = builder.getTokenType(); parseTypeTopType(builder, ((IHInfix) instHead).t2, comments); e = builder.getTokenType(); } else if (instHead instanceof IHParen) { consumeToken(builder, LPAREN); e = builder.getTokenType(); parseInstHead(builder, ((IHParen) instHead).instHead, comments); consumeToken(builder, RPAREN); e = builder.getTokenType(); } } /** * Parses the type variables in a data declaration. */ private static void parseTyVarBinds(PsiBuilder builder, TyVarBindTopType[] tyVarBindTopType, Comment[] comments) { IElementType e = builder.getTokenType(); int i = 0; while (tyVarBindTopType != null && i < tyVarBindTopType.length) { parseTyVarBind(builder, tyVarBindTopType[i], comments); i++; } e = builder.getTokenType(); } /** * Parses the type variables in a data declaration. */ private static void parseTyVarBind(PsiBuilder builder, TyVarBindTopType tyVarBindTopType, Comment[] comments) { IElementType e = builder.getTokenType(); if (tyVarBindTopType instanceof KindedVar) { consumeToken(builder, LPAREN); e = builder.getTokenType(); parseName(builder, ((KindedVar) tyVarBindTopType).name, comments); e = builder.getTokenType(); consumeToken(builder, DOUBLECOLON); e = builder.getTokenType(); parseKindTopType(builder, ((KindedVar) tyVarBindTopType).kind, comments); consumeToken(builder, RPAREN); } else if (tyVarBindTopType instanceof UnkindedVar) { parseName(builder, ((UnkindedVar) tyVarBindTopType).name, comments); } e = builder.getTokenType(); } /** * Parses a type declaration. */ private static void parseTypeDecl(PsiBuilder builder, TypeDecl typeDecl, Comment[] comments) { IElementType e = builder.getTokenType(); consumeToken(builder, TYPE); parseDeclHead(builder, typeDecl.declHead, comments); e = builder.getTokenType(); if (e == EQUALS) consumeToken(builder, EQUALS); parseTypeTopType(builder, typeDecl.type, comments); e = builder.getTokenType(); } /** * Parses a type signature. */ private static void parseTypeSig(PsiBuilder builder, TypeSig dataDecl, Comment[] comments) { IElementType e = builder.getTokenType(); parseNames(builder, dataDecl.names, comments); e = builder.getTokenType(); consumeToken(builder, DOUBLECOLON); e = builder.getTokenType(); parseTypeTopType(builder, dataDecl.type, comments); } /** * Parses a qualified constructor declaration. */ private static void parseQualConDecl(PsiBuilder builder, QualConDecl qualConDecl, Comment[] comments) { IElementType e = builder.getTokenType(); parseConDecl(builder, qualConDecl == null ? null : qualConDecl.conDecl, comments); } /** * Parses a constructor declaration. */ private static void parseConDecl(PsiBuilder builder, ConDeclTopType conDecl, Comment[] comments) { if (conDecl instanceof ConDecl) { parseName(builder, ((ConDecl) conDecl).name, comments); IElementType e = builder.getTokenType(); parseBangTypes(builder, conDecl == null ? null : ((ConDecl) conDecl).bangTypes, comments); } else if (conDecl instanceof InfixConDecl) { IElementType e = builder.getTokenType(); parseBangType(builder, ((InfixConDecl) conDecl).b1, comments); e = builder.getTokenType(); parseName(builder, ((InfixConDecl) conDecl).name, comments); parseBangType(builder, ((InfixConDecl) conDecl).b2, comments); } else if (conDecl instanceof RecDecl) { parseName(builder, ((RecDecl) conDecl).name, comments); boolean layouted = false; IElementType e = builder.getTokenType(); if (e == LBRACE) { consumeToken(builder, LBRACE); e = builder.getTokenType(); layouted = true; } parseFieldDecls(builder, ((RecDecl) conDecl).fields, comments); e = builder.getTokenType(); if (layouted) { consumeToken(builder, RBRACE); e = builder.getTokenType(); } } } /** * Parses the field declarations in a GADT-style declaration. */ private static void parseFieldDecls(PsiBuilder builder, FieldDecl[] fieldDecls, Comment[] comments) { IElementType e = builder.getTokenType(); int i = 0; while (fieldDecls != null && i < fieldDecls.length) { parseFieldDecl(builder, fieldDecls[i], comments); i++; } e = builder.getTokenType(); } /** * Parses a field declaration. */ private static void parseFieldDecl(PsiBuilder builder, FieldDecl fieldDecl, Comment[] comments) { IElementType e = builder.getTokenType(); parseNames(builder, fieldDecl.names, comments); e = builder.getTokenType(); consumeToken(builder, DOUBLECOLON); e = builder.getTokenType(); parseBangType(builder, fieldDecl.bang, comments); e = builder.getTokenType(); } /** * Parses a list of bang types. */ private static void parseBangTypes(PsiBuilder builder, BangTypeTopType[] bangTypes, Comment[] comments) { int i = 0; while (bangTypes != null && i < bangTypes.length) { parseBangType(builder, bangTypes[i], comments); i++; } } /** * Parses one bang type. */ private static void parseBangType(PsiBuilder builder, BangTypeTopType bangType, Comment[] comments) { IElementType e = builder.getTokenType(); // TODO: Refine bangType. if (bangType instanceof UnBangedTy) { parseTypeTopType(builder, ((UnBangedTy) bangType).type, comments); } else if (bangType instanceof BangedTy) { consumeToken(builder, EXLAMATION); parseTypeTopType(builder, ((BangedTy) bangType).type, comments); e = builder.getTokenType(); } else if (bangType instanceof UnpackedTy) { parseGenericPragma(builder, null, comments); consumeToken(builder, EXLAMATION); e = builder.getTokenType(); parseTypeTopType(builder, ((UnpackedTy) bangType).type, comments); e = builder.getTokenType(); } } private static void parseMatchTop(PsiBuilder builder, MatchTopType matchTopType, Comment[] comments) { IElementType e = builder.getTokenType(); if (matchTopType instanceof Match) { parseMatch(builder, (Match) matchTopType, comments); } else if (matchTopType instanceof InfixMatch) { parseInfixMatch(builder, (InfixMatch) matchTopType, comments); } } /** * Parses a single match. */ private static void parseMatch(PsiBuilder builder, Match match, Comment[] comments) { IElementType e = builder.getTokenType(); parseName(builder, match.name, comments); int i = 0; while (match.pats != null && i < match.pats.length) { parsePatTopType(builder, match.pats[i], comments); i++; } parseRhsTopType(builder, match.rhs, comments); e = builder.getTokenType(); if (e == WHERE) { consumeToken(builder, WHERE); parseBindsTopType(builder, match.bindsMaybe, comments); e = builder.getTokenType(); } } /** * Parses a single infix declaration. */ private static void parseInfixDecl(PsiBuilder builder, InfixDecl decl, Comment[] comments) { IElementType e = builder.getTokenType(); builder.advanceLexer(); // TOOD: Parse infix/infixl/infixr e = builder.getTokenType(); if (e == INTEGERTOKEN) consumeToken(builder, INTEGERTOKEN); e = builder.getTokenType(); int i = 0; while (decl.ops != null && i < decl.ops.length) { parseOp(builder, decl.ops[i], comments); i++; e = builder.getTokenType(); if (e == COMMA) { consumeToken(builder, COMMA); e = builder.getTokenType(); } } } /** * Parses a single default declaration. */ private static void parseDefaultDecl(PsiBuilder builder, DefaultDecl decl, Comment[] comments) { IElementType e = builder.getTokenType(); consumeToken(builder, DEFAULT); e = builder.getTokenType(); consumeToken(builder, LPAREN); e = builder.getTokenType(); parseTypeTopTypes(builder, decl.types, comments); e = builder.getTokenType(); consumeToken(builder, RPAREN); } /** * Parses a single infix match. */ private static void parseInfixMatch(PsiBuilder builder, InfixMatch match, Comment[] comments) { IElementType e = builder.getTokenType(); boolean startParen = e == LPAREN && !(match.pat instanceof PParen); if (startParen) consumeToken(builder, LPAREN); e = builder.getTokenType(); parsePatTopType(builder, match.pat, comments); e = builder.getTokenType(); parseName(builder, match.name, comments); int i = 0; while (match.pats != null && i < match.pats.length) { parsePatTopType(builder, match.pats[i], comments); if (startParen && i == 0) { consumeToken(builder, RPAREN); e = builder.getTokenType(); } i++; } parseRhsTopType(builder, match.rhs, comments); e = builder.getTokenType(); if (e == WHERE) { consumeToken(builder, WHERE); parseBindsTopType(builder, match.bindsMaybe, comments); e = builder.getTokenType(); } } /** * Parses one binding. */ private static void parseBindsTopType(PsiBuilder builder, BindsTopType bindsTopType, Comment[] comments) { IElementType e = builder.getTokenType(); if (bindsTopType instanceof BDecls) { parseDecls(builder, ((BDecls) bindsTopType).decls, comments); } else if (bindsTopType instanceof IPBinds) { throw new RuntimeException("TODO: Implement IPBinds:" + bindsTopType.toString()); } } /** * Parses several patterns. */ private static void parsePatTopTypes(PsiBuilder builder, PatTopType[] pats, Comment[] comments) { IElementType e = builder.getTokenType(); int i = 0; while(pats != null && i < pats.length) { parsePatTopType(builder, pats[i], comments); i++; e = builder.getTokenType(); if (e == COMMA) { consumeToken(builder, COMMA); e = builder.getTokenType(); } } } /** * Parses one pattern. */ private static void parsePatTopType(PsiBuilder builder, PatTopType patTopType, Comment[] comments) { IElementType e = builder.getTokenType(); if (patTopType instanceof PVar) { parsePVar(builder, (PVar) patTopType, comments); } else if (patTopType instanceof PLit) { parseLiteralTop(builder, ((PLit) patTopType).lit, comments); e = builder.getTokenType(); } else if (patTopType instanceof PNeg) { e = builder.getTokenType(); consumeToken(builder, MINUS); e = builder.getTokenType(); parsePatTopType(builder, ((PNeg) patTopType).pat, comments); e = builder.getTokenType(); } else if (patTopType instanceof PNPlusK) { e = builder.getTokenType(); parseName(builder, ((PNPlusK) patTopType).name, comments); e = builder.getTokenType(); consumeToken(builder, PLUS); e = builder.getTokenType(); consumeToken(builder, INTEGERTOKEN); e = builder.getTokenType(); } else if (patTopType instanceof PApp) { e = builder.getTokenType(); parseQName(builder, ((PApp) patTopType).qName, comments); e = builder.getTokenType(); parsePatTopTypes(builder, ((PApp) patTopType).pats, comments); e = builder.getTokenType(); } else if (patTopType instanceof PInfixApp) { e = builder.getTokenType(); parsePatTopType(builder, ((PInfixApp) patTopType).p1, comments); e = builder.getTokenType(); parseQName(builder, ((PInfixApp) patTopType).qName, comments); e = builder.getTokenType(); parsePatTopType(builder, ((PInfixApp) patTopType).p1, comments); e = builder.getTokenType(); } else if (patTopType instanceof PTuple) { consumeToken(builder, LPAREN); e = builder.getTokenType(); boolean unboxed = parseBoxed(builder, ((PTuple) patTopType).boxed, comments); parsePatTopTypes(builder, ((PTuple) patTopType).pats, comments); e = builder.getTokenType(); if (unboxed) { consumeToken(builder, HASH); e = builder.getTokenType(); } consumeToken(builder, RPAREN); e = builder.getTokenType(); } else if (patTopType instanceof PList) { consumeToken(builder, LBRACKET); parsePatTopTypes(builder, ((PList) patTopType).pats, comments); e = builder.getTokenType(); consumeToken(builder, RBRACKET); e = builder.getTokenType(); } else if (patTopType instanceof PParen) { consumeToken(builder, LPAREN); e = builder.getTokenType(); parsePatTopType(builder, ((PParen) patTopType).pat, comments); consumeToken(builder, RPAREN); e = builder.getTokenType(); } else if (patTopType instanceof PRec) { parseQName(builder, ((PRec) patTopType).qName, comments); e = builder.getTokenType(); consumeToken(builder, LBRACE); parsePatFieldTopTypes(builder, ((PRec) patTopType).patFields, comments); e = builder.getTokenType(); consumeToken(builder, RBRACE); e = builder.getTokenType(); } else if (patTopType instanceof PAsPat) { parseName(builder, ((PAsPat) patTopType).name, comments); e = builder.getTokenType(); consumeToken(builder, AMPERSAT); parsePatTopType(builder, ((PAsPat) patTopType).pat, comments); e = builder.getTokenType(); } else if (patTopType instanceof PWildCard) { builder.advanceLexer(); // TODO: Token.UNDERSCORE? e = builder.getTokenType(); } else if (patTopType instanceof PIrrPat) { consumeToken(builder, TILDE); e = builder.getTokenType(); parsePatTopType(builder, ((PIrrPat) patTopType).pat, comments); e = builder.getTokenType(); } else if (patTopType instanceof PatTypeSig) { parsePatTopType(builder, ((PatTypeSig) patTopType).pat, comments); e = builder.getTokenType(); consumeToken(builder, DOUBLECOLON); parseTypeTopType(builder, ((PatTypeSig) patTopType).type, comments); e = builder.getTokenType(); } else if (patTopType instanceof PViewPat) { parseExpTopType(builder, ((PViewPat) patTopType).exp, comments); e = builder.getTokenType(); consumeToken(builder, RIGHTARROW); parsePatTopType(builder, ((PViewPat) patTopType).pat, comments); e = builder.getTokenType(); } else if (patTopType instanceof PBangPat) { consumeToken(builder, EXLAMATION); e = builder.getTokenType(); parsePatTopType(builder, ((PBangPat) patTopType).pat, comments); e = builder.getTokenType(); } else { throw new RuntimeException("parsePatTopType" + patTopType.toString()); } } private static void parseComment(IElementType start, PsiBuilder builder, Comment[] comments) { PsiBuilder.Marker startCom = builder.mark(); IElementType e = builder.getTokenType(); while (e == COMMENT || e == COMMENTTEXT || e == OPENCOM || e == CLOSECOM) { builder.advanceLexer(); e = builder.getTokenType(); } startCom.done(start); } /** * Parses a group of module pragmas. */ private static void parseModulePragmas(PsiBuilder builder, ModulePragmaTopType[] modulePragmas, Comment[] comments) { int i = 0; while(modulePragmas != null && i < modulePragmas.length) { parseModulePragma(builder, modulePragmas[i], comments); i++; } } /** * Parses a module pragma. */ private static void parseModulePragma(PsiBuilder builder, ModulePragmaTopType modulePragmaTopType, Comment[] comments) { int i = 0; if (modulePragmaTopType instanceof LanguagePragma) { LanguagePragma langPragma = (LanguagePragma) modulePragmaTopType; IElementType e = builder.getTokenType(); PsiBuilder.Marker pragmaMark = builder.mark(); consumeToken(builder, OPENPRAGMA); consumeToken(builder, PRAGMA); while (langPragma.names != null && i < langPragma.names.length) { // TODO: Improve precision of pragma lexing. // parseName(builder, langPragma.names[i], comments); i++; } consumeToken(builder, CLOSEPRAGMA); pragmaMark.done(e); } else if (modulePragmaTopType instanceof OptionsPragma) { // FIXME: Use optionsPragma information. OptionsPragma optionsPragma = (OptionsPragma) modulePragmaTopType; IElementType e = builder.getTokenType(); PsiBuilder.Marker pragmaMark = builder.mark(); chewPragma(builder); consumeToken(builder, CLOSEPRAGMA); pragmaMark.done(e); } else if (modulePragmaTopType instanceof AnnModulePragma) { // FIXME: Use annModulePragma information. AnnModulePragma annModulePragma = (AnnModulePragma) modulePragmaTopType; IElementType e = builder.getTokenType(); PsiBuilder.Marker pragmaMark = builder.mark(); chewPragma(builder); consumeToken(builder, CLOSEPRAGMA); pragmaMark.done(e); } } /** * Parses a pattern variable. */ private static void parsePVar(PsiBuilder builder, PVar pVar, Comment[] comments) { parseName(builder, pVar.name, comments); } /** * Parses a group of GuardedRhss. */ private static void parseGuardedRhss(PsiBuilder builder, GuardedRhs[] rhss, Comment[] comments) { IElementType e = builder.getTokenType(); int i = 0; while(rhss != null && i < rhss.length) { parseGuardedRhs(builder, rhss[i], comments); i++; e = builder.getTokenType(); } } /** * Parses one GuardedRhs. */ private static void parseGuardedRhs(PsiBuilder builder, GuardedRhs rhs, Comment[] comments) { IElementType e = builder.getTokenType(); consumeToken(builder, PIPE); e = builder.getTokenType(); parseStmtTopTypes(builder, rhs.stmts, comments); e = builder.getTokenType(); consumeToken(builder, EQUALS); parseExpTopType(builder, rhs.exp, comments); e = builder.getTokenType(); } /** * Parses one Rhs. */ private static void parseRhsTopType(PsiBuilder builder, RhsTopType rhsTopType, Comment[] comments) { IElementType e = builder.getTokenType(); if (rhsTopType instanceof UnGuardedRhs) { consumeToken(builder, EQUALS); parseExpTopType(builder, ((UnGuardedRhs) rhsTopType).exp, comments); } else if (rhsTopType instanceof GuardedRhss) { e = builder.getTokenType(); parseGuardedRhss(builder, ((GuardedRhss) rhsTopType).rhsses, comments); } } /** * Parses an unqualified op. */ private static void parseOp(PsiBuilder builder, OpTopType opTopType, Comment[] comments) { IElementType e = builder.getTokenType(); boolean backticked = e == BACKTICK; if (backticked) { consumeToken(builder, BACKTICK); e = builder.getTokenType(); } if (opTopType instanceof VarOp) { parseName(builder, ((VarOp) opTopType).name, comments); } else if (opTopType instanceof ConOp) { parseName(builder, ((ConOp) opTopType).name, comments); } if (backticked) consumeToken(builder, BACKTICK); e = builder.getTokenType(); } /** * Parses a qualified op. */ private static void parseQOp(PsiBuilder builder, QOpTopType qOpTopType, Comment[] comments) { IElementType e = builder.getTokenType(); boolean backticked = e == BACKTICK; if (backticked) { consumeToken(builder, BACKTICK); e = builder.getTokenType(); } if (qOpTopType instanceof QVarOp) { parseQName(builder, ((QVarOp) qOpTopType).qName, comments); } else if (qOpTopType instanceof QConOp) { parseQName(builder, ((QConOp) qOpTopType).qName, comments); } if (backticked) consumeToken(builder, BACKTICK); e = builder.getTokenType(); } /** * Parses a qualified name. */ private static void parseQName(PsiBuilder builder, QNameTopType qNameTopType, Comment[] comments) { if (qNameTopType instanceof Qual) { Qual name = (Qual) qNameTopType; parseModuleName(builder, name.moduleName, comments); parseName(builder, name.name, comments); } else if (qNameTopType instanceof UnQual) { parseName(builder, ((UnQual) qNameTopType).name, comments); } else if (qNameTopType instanceof Special) { parseSpecialConTopType(builder, ((Special) qNameTopType).specialCon, comments); } } /** * Parses a special constructor. */ private static void parseSpecialConTopType(PsiBuilder builder, SpecialConTopType specialConTopType, Comment[] comments) { IElementType e = builder.getTokenType(); if (specialConTopType instanceof UnitCon) { consumeToken(builder, LPAREN); e = builder.getTokenType(); consumeToken(builder, RPAREN); e = builder.getTokenType(); } else if (specialConTopType instanceof ListCon) { consumeToken(builder, LBRACKET); e = builder.getTokenType(); consumeToken(builder, RBRACKET); e = builder.getTokenType(); } else if (specialConTopType instanceof FunCon) { consumeToken(builder, LPAREN); e = builder.getTokenType(); consumeToken(builder, RIGHTARROW); e = builder.getTokenType(); consumeToken(builder, RPAREN); e = builder.getTokenType(); } else if (specialConTopType instanceof TupleCon) { consumeToken(builder, LPAREN); e = builder.getTokenType(); boolean unboxed = parseBoxed(builder, ((TupleCon) specialConTopType).boxed, comments); e = builder.getTokenType(); int i = 1; while (i < ((TupleCon) specialConTopType).i) { consumeToken(builder, COMMA); e = builder.getTokenType(); i++; } e = builder.getTokenType(); if (unboxed) { consumeToken(builder, HASH); e = builder.getTokenType(); } consumeToken(builder, RPAREN); e = builder.getTokenType(); } else if (specialConTopType instanceof Cons) { consumeToken(builder, COLON); e = builder.getTokenType(); } else if (specialConTopType instanceof UnboxedSingleCon) { consumeToken(builder, LPAREN); e = builder.getTokenType(); consumeToken(builder, HASH); e = builder.getTokenType(); consumeToken(builder, HASH); e = builder.getTokenType(); consumeToken(builder, RPAREN); } } /** * Parses a list of names. */ private static void parseNames(PsiBuilder builder, NameTopType[] names, Comment[] comments) { IElementType e = builder.getTokenType(); int i = 0; while (names != null && i < names.length) { parseName(builder, names[i], comments); i++; e = builder.getTokenType(); if (e == COMMA) consumeToken(builder, COMMA); } } /** * Parses a name. */ private static void parseName(PsiBuilder builder, NameTopType nameTopType, Comment[] comments) { IElementType e = builder.getTokenType(); if (nameTopType instanceof Ident) { int startPos = builder.getCurrentOffset(); while ((builder.getCurrentOffset() - startPos) < ((Ident) nameTopType).name.length()) { builder.remapCurrentToken(NAME); consumeToken(builder, NAME); e = builder.getTokenType(); } } else if (nameTopType instanceof Symbol) { boolean startParen = e == LPAREN; if (startParen) consumeToken(builder, LPAREN); e = builder.getTokenType(); int startPos = builder.getCurrentOffset(); while ((builder.getCurrentOffset() - startPos) < ((Symbol) nameTopType).symbol.length()) { builder.remapCurrentToken(SYMBOL); consumeToken(builder, SYMBOL); e = builder.getTokenType(); } e = builder.getTokenType(); if (startParen) { consumeToken(builder, RPAREN); e = builder.getTokenType(); } } } /** * Parses a literal */ private static void parseLiteralTop(PsiBuilder builder, LiteralTopType literalTopType, Comment[] comments) { IElementType e = builder.getTokenType(); if (literalTopType instanceof CharLit) { consumeToken(builder, CHARTOKEN); e = builder.getTokenType(); } else if (literalTopType instanceof StringLit) { parseStringLiteral(builder); } else if (literalTopType instanceof IntLit) { consumeToken(builder, INTEGERTOKEN); e = builder.getTokenType(); } else if (literalTopType instanceof FracLit) { consumeToken(builder, FLOATTOKEN); e = builder.getTokenType(); } else if (literalTopType instanceof PrimInt) { consumeToken(builder, INTEGERTOKEN); e = builder.getTokenType(); consumeToken(builder, HASH); e = builder.getTokenType(); } else if (literalTopType instanceof PrimWord) { consumeToken(builder, INTEGERTOKEN); e = builder.getTokenType(); consumeToken(builder, HASH); e = builder.getTokenType(); consumeToken(builder, HASH); e = builder.getTokenType(); } else if (literalTopType instanceof PrimFloat) { consumeToken(builder, FLOATTOKEN); e = builder.getTokenType(); consumeToken(builder, HASH); e = builder.getTokenType(); } else if (literalTopType instanceof PrimDouble) { consumeToken(builder, FLOATTOKEN); e = builder.getTokenType(); consumeToken(builder, HASH); e = builder.getTokenType(); consumeToken(builder, HASH); e = builder.getTokenType(); } else if (literalTopType instanceof PrimChar) { consumeToken(builder, CHARTOKEN); e = builder.getTokenType(); consumeToken(builder, HASH); e = builder.getTokenType(); } else if (literalTopType instanceof PrimString) { parseStringLiteral(builder); e = builder.getTokenType(); consumeToken(builder, HASH); e = builder.getTokenType(); } else { throw new RuntimeException("LiteralTop: " + literalTopType.toString()); } } /** * Parse a string literal. */ private static void parseStringLiteral(PsiBuilder builder) { IElementType e = builder.getTokenType(); PsiBuilder.Marker marker = builder.mark(); consumeToken(builder, DOUBLEQUOTE); IElementType e2 = builder.getTokenType(); while (e2 != DOUBLEQUOTE) { if (e2 == BADSTRINGTOKEN) { builder.error("Bad stringtoken"); builder.advanceLexer(); } else { consumeToken(builder, STRINGTOKEN); } e2 = builder.getTokenType(); } consumeToken(builder, DOUBLEQUOTE); marker.done(e); } /** * Parses a list of statements. */ private static void parseStmtTopTypes(PsiBuilder builder, StmtTopType[] stmtTopTypes, Comment[] comments) { IElementType e = builder.getTokenType(); int i = 0; while (stmtTopTypes != null && i < stmtTopTypes.length) { parseStmtTopType(builder, stmtTopTypes[i], comments); i++; } } /** * Parses a statement. */ private static void parseStmtTopType(PsiBuilder builder, StmtTopType stmtTopType, Comment[] comments) { IElementType e = builder.getTokenType(); PsiBuilder.Marker stmtMark = builder.mark(); if (stmtTopType instanceof Generator) { parsePatTopType(builder, ((Generator) stmtTopType).pat, comments); consumeToken(builder, LEFTARROW); parseExpTopType(builder, ((Generator) stmtTopType).exp, comments); } else if (stmtTopType instanceof Qualifier) { parseExpTopType(builder, ((Qualifier) stmtTopType).exp, comments); } else if (stmtTopType instanceof LetStmt) { consumeToken(builder, LET); parseBindsTopType(builder, ((LetStmt) stmtTopType).binds, comments); } else if (stmtTopType instanceof RecStmt) { builder.advanceLexer(); IElementType e1 = builder.getTokenType(); parseStmtTopTypes(builder, ((RecStmt) stmtTopType).stmts, comments); e1 = builder.getTokenType(); } stmtMark.done(e); } /** * Parses a list of expressions. */ private static void parseExpTopTypes(PsiBuilder builder, ExpTopType[] expTopType, Comment[] comments) { IElementType e = builder.getTokenType(); int i = 0; while (expTopType != null && i < expTopType.length) { parseExpTopType(builder, expTopType[i], comments); i++; e = builder.getTokenType(); if (e == COMMA) consumeToken(builder, COMMA); } } /** * Parses an expression. */ private static void parseExpTopType(PsiBuilder builder, ExpTopType expTopType, Comment[] comments) { IElementType e1 = builder.getTokenType(); if (expTopType instanceof App) { parseExpTopType(builder, ((App) expTopType).e1, comments); parseExpTopType(builder, ((App) expTopType).e2, comments); } else if (expTopType instanceof Var) { parseQName(builder, ((Var) expTopType).qName, comments); } else if (expTopType instanceof Con) { parseQName(builder, ((Con) expTopType).qName, comments); } else if (expTopType instanceof Lit) { parseLiteralTop(builder, ((Lit) expTopType).literal, comments); } else if (expTopType instanceof InfixApp) { parseExpTopType(builder, ((InfixApp) expTopType).e1, comments); IElementType e = builder.getTokenType(); parseQOp(builder, ((InfixApp) expTopType).qop, comments); e = builder.getTokenType(); parseExpTopType(builder, ((InfixApp) expTopType).e2, comments); e = builder.getTokenType(); } else if (expTopType instanceof List) { builder.advanceLexer(); parseExpTopTypes(builder, ((List) expTopType).exps, comments); IElementType e = builder.getTokenType(); builder.advanceLexer(); } else if (expTopType instanceof NegApp) { consumeToken(builder, MINUS); parseExpTopType(builder, ((NegApp) expTopType).e1, comments); } else if (expTopType instanceof Case) { IElementType e = builder.getTokenType(); consumeToken(builder, CASE); e = builder.getTokenType(); parseExpTopType(builder, ((Case) expTopType).scrutinee, comments); e = builder.getTokenType(); consumeToken(builder, OF); e = builder.getTokenType(); parseAlts(builder, ((Case) expTopType).alts, comments); e = builder.getTokenType(); } else if (expTopType instanceof Do) { IElementType e = builder.getTokenType(); PsiBuilder.Marker doMark = builder.mark(); consumeToken(builder, DO); parseStmtTopTypes(builder, ((Do) expTopType).stmts, comments); doMark.done(e); } else if (expTopType instanceof MDo) { IElementType e = builder.getTokenType(); PsiBuilder.Marker doMark = builder.mark(); builder.advanceLexer(); // TODO: Token.MDO parseStmtTopTypes(builder, ((MDo) expTopType).stmts, comments); doMark.done(e); } else if (expTopType instanceof Lambda) { consumeToken(builder, BACKSLASH); IElementType e = builder.getTokenType(); parsePatTopTypes(builder, ((Lambda) expTopType).pats, comments); e = builder.getTokenType(); consumeToken(builder, RIGHTARROW); parseExpTopType(builder, ((Lambda) expTopType).exp, comments); e = builder.getTokenType(); } else if (expTopType instanceof Tuple) { consumeToken(builder, LPAREN); IElementType e = builder.getTokenType(); boolean unboxed = parseBoxed(builder, ((Tuple) expTopType).boxed, comments); e = builder.getTokenType(); parseExpTopTypes(builder, ((Tuple) expTopType).exps, comments); e = builder.getTokenType(); if (unboxed) { consumeToken(builder, HASH); e = builder.getTokenType(); } consumeToken(builder, RPAREN); e1 = builder.getTokenType(); } else if (expTopType instanceof TupleSection) { TupleSection ts = (TupleSection) expTopType; consumeToken(builder, LPAREN); IElementType e = builder.getTokenType(); boolean unboxed = parseBoxed(builder, ((TupleSection) expTopType).boxed, comments); e = builder.getTokenType(); int i = 0; while (ts.expMaybes != null && i < ts.expMaybes.length) { if (ts.expMaybes[i] != null) parseExpTopType(builder, ts.expMaybes[i], comments); i++; e = builder.getTokenType(); if (e == COMMA) consumeToken(builder, COMMA); } e = builder.getTokenType(); if (unboxed) { consumeToken(builder, HASH); e = builder.getTokenType(); } consumeToken(builder, RPAREN); e1 = builder.getTokenType(); } else if (expTopType instanceof Paren) { consumeToken(builder, LPAREN); e1 = builder.getTokenType(); parseExpTopType(builder, ((Paren) expTopType).exp, comments); e1 = builder.getTokenType(); consumeToken(builder, RPAREN); e1 = builder.getTokenType(); } else if (expTopType instanceof LeftSection) { e1 = builder.getTokenType(); consumeToken(builder, LPAREN); e1 = builder.getTokenType(); parseExpTopType(builder, ((LeftSection) expTopType).exp, comments); e1 = builder.getTokenType(); parseQOp(builder, ((LeftSection) expTopType).qop, comments); e1 = builder.getTokenType(); consumeToken(builder, RPAREN); e1 = builder.getTokenType(); } else if (expTopType instanceof RightSection) { e1 = builder.getTokenType(); consumeToken(builder, LPAREN); parseQOp(builder, ((RightSection) expTopType).qop, comments); parseExpTopType(builder, ((RightSection) expTopType).exp, comments); e1 = builder.getTokenType(); consumeToken(builder, RPAREN); e1 = builder.getTokenType(); } else if (expTopType instanceof RecConstr) { e1 = builder.getTokenType(); parseQName(builder, ((RecConstr) expTopType).qName, comments); e1 = builder.getTokenType(); consumeToken(builder, LBRACE); parseFieldUpdateTopTypes(builder, ((RecConstr) expTopType).fieldUpdates, comments); e1 = builder.getTokenType(); consumeToken(builder, RBRACE); e1 = builder.getTokenType(); } else if (expTopType instanceof RecUpdate) { e1 = builder.getTokenType(); parseExpTopType(builder, ((RecUpdate) expTopType).exp, comments); e1 = builder.getTokenType(); consumeToken(builder, LBRACE); parseFieldUpdateTopTypes(builder, ((RecUpdate) expTopType).fieldUpdates, comments); e1 = builder.getTokenType(); consumeToken(builder, RBRACE); e1 = builder.getTokenType(); } else if (expTopType instanceof EnumFrom) { consumeToken(builder, LBRACKET); e1 = builder.getTokenType(); parseExpTopType(builder, ((EnumFrom) expTopType).exp, comments); e1 = builder.getTokenType(); consumeToken(builder, DOUBLEPERIOD); e1 = builder.getTokenType(); consumeToken(builder, RBRACKET); e1 = builder.getTokenType(); } else if (expTopType instanceof EnumFromTo) { consumeToken(builder, LBRACKET); e1 = builder.getTokenType(); parseExpTopType(builder, ((EnumFromTo) expTopType).from, comments); e1 = builder.getTokenType(); consumeToken(builder, DOUBLEPERIOD); e1 = builder.getTokenType(); parseExpTopType(builder, ((EnumFromTo) expTopType).to, comments); consumeToken(builder, RBRACKET); e1 = builder.getTokenType(); } else if (expTopType instanceof EnumFromThen) { consumeToken(builder, LBRACKET); e1 = builder.getTokenType(); parseExpTopType(builder, ((EnumFromThen) expTopType).from, comments); e1 = builder.getTokenType(); consumeToken(builder, COMMA); e1 = builder.getTokenType(); parseExpTopType(builder, ((EnumFromThen) expTopType).step, comments); consumeToken(builder, DOUBLEPERIOD); e1 = builder.getTokenType(); consumeToken(builder, RBRACKET); e1 = builder.getTokenType(); } else if (expTopType instanceof EnumFromThenTo) { consumeToken(builder, LBRACKET); e1 = builder.getTokenType(); parseExpTopType(builder, ((EnumFromThenTo) expTopType).from, comments); e1 = builder.getTokenType(); consumeToken(builder, COMMA); e1 = builder.getTokenType(); parseExpTopType(builder, ((EnumFromThenTo) expTopType).step, comments); consumeToken(builder, DOUBLEPERIOD); e1 = builder.getTokenType(); parseExpTopType(builder, ((EnumFromThenTo) expTopType).to, comments); e1 = builder.getTokenType(); consumeToken(builder, RBRACKET); e1 = builder.getTokenType(); } else if (expTopType instanceof ListComp) { consumeToken(builder, LBRACKET); e1 = builder.getTokenType(); parseExpTopType(builder, ((ListComp) expTopType).exp, comments); e1 = builder.getTokenType(); consumeToken(builder, PIPE); e1 = builder.getTokenType(); parseQualStmtTopTypes(builder, ((ListComp) expTopType).qualStmts, comments); e1 = builder.getTokenType(); consumeToken(builder, RBRACKET); e1 = builder.getTokenType(); } else if (expTopType instanceof ParComp) { ParComp p = (ParComp) expTopType; consumeToken(builder, LBRACKET); e1 = builder.getTokenType(); parseExpTopType(builder, ((ParComp) expTopType).exp, comments); e1 = builder.getTokenType(); consumeToken(builder, PIPE); e1 = builder.getTokenType(); int i = 0; while (p.qualStmts != null && i < p.qualStmts.length) { parseQualStmtTopTypes(builder, p.qualStmts[i], comments); i++; e1 = builder.getTokenType(); if (e1 == PIPE) consumeToken(builder, PIPE); e1 = builder.getTokenType(); } consumeToken(builder, RBRACKET); e1 = builder.getTokenType(); } else if (expTopType instanceof ExpTypeSig) { IElementType e = builder.getTokenType(); parseExpTopType(builder, ((ExpTypeSig) expTopType).exp, comments); e = builder.getTokenType(); consumeToken(builder, DOUBLECOLON); e = builder.getTokenType(); parseTypeTopType(builder, ((ExpTypeSig) expTopType).type, comments); e = builder.getTokenType(); } else if (expTopType instanceof Let) { builder.advanceLexer(); IElementType e = builder.getTokenType(); parseBindsTopType(builder, ((Let) expTopType).binds, comments); e = builder.getTokenType(); consumeToken(builder, IN); e = builder.getTokenType(); parseExpTopType(builder, ((Let) expTopType).exp, comments); e = builder.getTokenType(); } else if (expTopType instanceof If) { consumeToken(builder, IF); IElementType e = builder.getTokenType(); parseExpTopType(builder, ((If) expTopType).cond, comments); e = builder.getTokenType(); consumeToken(builder, THEN); e = builder.getTokenType(); parseExpTopType(builder, ((If) expTopType).t, comments); e = builder.getTokenType(); consumeToken(builder, ELSE); e = builder.getTokenType(); parseExpTopType(builder, ((If) expTopType).f, comments); e = builder.getTokenType(); } else if (expTopType instanceof MultiIf) { consumeToken(builder, IF); IElementType e = builder.getTokenType(); parseIfAlts(builder, ((MultiIf) expTopType).alts, comments); e = builder.getTokenType(); } else if (expTopType instanceof QuasiQuote) { IElementType e = builder.getTokenType(); consumeToken(builder, LBRACKET); builder.advanceLexer(); e = builder.getTokenType(); consumeToken(builder, PIPE); e = builder.getTokenType(); while (e != PIPE) { builder.advanceLexer(); e = builder.getTokenType(); } consumeToken(builder, PIPE); consumeToken(builder, RBRACKET); e = builder.getTokenType(); } else if (expTopType instanceof CorePragma) { parseGenericPragma(builder, null, comments); parseExpTopType(builder, ((CorePragma) expTopType).exp, comments); } else if (expTopType instanceof SCCPragma) { parseGenericPragma(builder, null, comments); parseExpTopType(builder, ((SCCPragma) expTopType).exp, comments); } else if (expTopType instanceof Proc) { e1 = builder.getTokenType(); builder.advanceLexer(); // TODO: consumeToken(builder, PROCTOKEN); e1 = builder.getTokenType(); parsePatTopType(builder, ((Proc) expTopType).pat, comments); consumeToken(builder, RIGHTARROW); parseExpTopType(builder, ((Proc) expTopType).exp, comments); } else if (expTopType instanceof LeftArrApp) { e1 = builder.getTokenType(); parseExpTopType(builder, ((LeftArrApp) expTopType).e1, comments); builder.advanceLexer(); // TODO: consumeToken(builder, LeftArrApp); e1 = builder.getTokenType(); builder.advanceLexer(); e1 = builder.getTokenType(); parseExpTopType(builder, ((LeftArrApp) expTopType).e2, comments); e1 = builder.getTokenType(); } else if (expTopType instanceof RightArrApp) { e1 = builder.getTokenType(); parseExpTopType(builder, ((RightArrApp) expTopType).e1, comments); builder.advanceLexer(); // TODO: consumeToken(builder, RightArrApp); e1 = builder.getTokenType(); builder.advanceLexer(); e1 = builder.getTokenType(); parseExpTopType(builder, ((RightArrApp) expTopType).e2, comments); e1 = builder.getTokenType(); } else if (expTopType instanceof LeftArrHighApp) { e1 = builder.getTokenType(); parseExpTopType(builder, ((LeftArrHighApp) expTopType).e1, comments); builder.advanceLexer(); // TODO: consumeToken(builder, LeftArrHighApp); e1 = builder.getTokenType(); builder.advanceLexer(); e1 = builder.getTokenType(); builder.advanceLexer(); e1 = builder.getTokenType(); parseExpTopType(builder, ((LeftArrHighApp) expTopType).e2, comments); e1 = builder.getTokenType(); } else if (expTopType instanceof RightArrHighApp) { e1 = builder.getTokenType(); parseExpTopType(builder, ((RightArrHighApp) expTopType).e1, comments); builder.advanceLexer(); // TODO: consumeToken(builder, RightArrHighApp); e1 = builder.getTokenType(); builder.advanceLexer(); e1 = builder.getTokenType(); builder.advanceLexer(); e1 = builder.getTokenType(); parseExpTopType(builder, ((RightArrHighApp) expTopType).e2, comments); e1 = builder.getTokenType(); } else if (expTopType instanceof LCase) { IElementType e = builder.getTokenType(); consumeToken(builder, BACKSLASH); e = builder.getTokenType(); consumeToken(builder, CASE); e = builder.getTokenType(); parseAlts(builder, ((LCase) expTopType).alts, comments); e = builder.getTokenType(); } else { throw new RuntimeException("parseExpTopType: " + expTopType.toString()); } } /** * Parses a list of field patterns. */ private static void parsePatFieldTopTypes(PsiBuilder builder, PatFieldTopType[] fields, Comment[] comments) { IElementType e = builder.getTokenType(); int i = 0; while (fields != null && i < fields.length) { parsePatFieldTopType(builder, fields[i], comments); i++; e = builder.getTokenType(); if (e == COMMA) consumeToken(builder, COMMA); } } /** * Parses a field pattern. */ private static void parsePatFieldTopType(PsiBuilder builder, PatFieldTopType field, Comment[] comments) { IElementType e = builder.getTokenType(); if (field instanceof PFieldPat) { parseQName(builder, ((PFieldPat) field).qName, comments); e = builder.getTokenType(); consumeToken(builder, EQUALS); e = builder.getTokenType(); parsePatTopType(builder, ((PFieldPat) field).pat, comments); e = builder.getTokenType(); } else if (field instanceof PFieldPun) { consumeToken(builder, VARIDREGEXP); e = builder.getTokenType(); } else if (field instanceof PFieldWildcard) { builder.advanceLexer(); // TODO: Token.UNDERSCORE? e = builder.getTokenType(); } } /** * Parses a list of field updates. */ private static void parseFieldUpdateTopTypes(PsiBuilder builder, FieldUpdateTopType[] fieldUpdateTopTypes, Comment[] comments) { IElementType e = builder.getTokenType(); int i = 0; while (fieldUpdateTopTypes != null && i < fieldUpdateTopTypes.length) { parseFieldUpdateTopType(builder, fieldUpdateTopTypes[i], comments); i++; e = builder.getTokenType(); if (e == COMMA) consumeToken(builder, COMMA); } } /** * Parses a field update. */ private static void parseFieldUpdateTopType(PsiBuilder builder, FieldUpdateTopType fieldUpdate, Comment[] comments) { IElementType e = builder.getTokenType(); if (fieldUpdate instanceof FieldUpdate) { parseQName(builder, ((FieldUpdate) fieldUpdate).qName, comments); e = builder.getTokenType(); consumeToken(builder, EQUALS); e = builder.getTokenType(); parseExpTopType(builder, ((FieldUpdate) fieldUpdate).exp, comments); e = builder.getTokenType(); } else if (fieldUpdate instanceof FieldPun) { throw new RuntimeException("TODO: FieldPun not implemented"); } else if (fieldUpdate instanceof FieldWildcard) { throw new RuntimeException("TODO: FieldWildcard not implemented"); } } /** * Parses a list of alts. */ private static void parseAlts(PsiBuilder builder, Alt[] alts, Comment[] comments) { IElementType e = builder.getTokenType(); int i = 0; while (alts != null && i < alts.length) { parseAlt(builder, alts[i], comments); i++; e = builder.getTokenType(); if (e == SEMICOLON) consumeToken(builder, SEMICOLON); } } /** * Parses a single alt. */ private static void parseAlt(PsiBuilder builder, Alt alt, Comment[] comments) { IElementType e = builder.getTokenType(); parsePatTopType(builder, alt.pat, comments); e = builder.getTokenType(); parseGuardedAltsTopType(builder, alt.guardedAlts, comments); e = builder.getTokenType(); parseBindsTopType(builder, alt.bindsMaybe, comments); e = builder.getTokenType(); } /** * Parses a list of IfAlts. */ private static void parseIfAlts(PsiBuilder builder, IfAlt[] alts, Comment[] comments) { IElementType e = builder.getTokenType(); int i = 0; while (alts != null && i < alts.length) { parseIfAlt(builder, alts[i], comments); i++; e = builder.getTokenType(); if (e == PIPE) consumeToken(builder, PIPE); } } /** * Parses a single IfAlt */ private static void parseIfAlt(PsiBuilder builder, IfAlt alt, Comment[] comments) { IElementType e = builder.getTokenType(); parseExpTopType(builder, alt.e1, comments); e = builder.getTokenType(); consumeToken(builder, RIGHTARROW); e = builder.getTokenType(); parseExpTopType(builder, alt.e2, comments); e = builder.getTokenType(); } /** * Parses a single guarded alt. */ private static void parseGuardedAltsTopType(PsiBuilder builder, GuardedAltsTopType alt, Comment[] comments) { IElementType e = builder.getTokenType(); if (alt instanceof UnGuardedAlt) { consumeToken(builder, RIGHTARROW); e = builder.getTokenType(); parseExpTopType(builder, ((UnGuardedAlt) alt).exp, comments); e = builder.getTokenType(); } else if (alt instanceof GuardedAlts) { parseGuardedAlts(builder, ((GuardedAlts) alt).alts, comments); e = builder.getTokenType(); } } /** * Parses a list of guarded alts. */ private static void parseGuardedAlts(PsiBuilder builder, GuardedAlt[] alts, Comment[] comments) { IElementType e = builder.getTokenType(); int i = 0; while (alts != null && i < alts.length) { parseGuardedAlt(builder, alts[i], comments); i++; e = builder.getTokenType(); if (e == SEMICOLON) consumeToken(builder, SEMICOLON); } } /** * Parses a single guarded alt. */ private static void parseGuardedAlt(PsiBuilder builder, GuardedAlt alt, Comment[] comments) { IElementType e = builder.getTokenType(); consumeToken(builder, PIPE); e = builder.getTokenType(); parseStmtTopTypes(builder, alt.stmts, comments); e = builder.getTokenType(); consumeToken(builder, RIGHTARROW); e = builder.getTokenType(); parseExpTopType(builder, alt.exp, comments); e = builder.getTokenType(); } /** * Parses a list of types. */ private static void parseTypeTopTypes(PsiBuilder builder, TypeTopType[] typeTopTypes, Comment[] comments) { IElementType e = builder.getTokenType(); int i = 0; while (typeTopTypes != null && i < typeTopTypes.length) { parseTypeTopType(builder, typeTopTypes[i], comments); i++; e = builder.getTokenType(); if (e == COMMA) consumeToken(builder, COMMA); } } /** * Parses a type. */ private static void parseTypeTopType(PsiBuilder builder, TypeTopType typeTopType, Comment[] comments) { IElementType e = builder.getTokenType(); if (typeTopType instanceof TyForall) { // FIXME: No forall lexeme. TyForall t = (TyForall) typeTopType; e = builder.getTokenType(); if (t.tyVarBinds != null) { // Implicit foralls for typeclasses. builder.advanceLexer(); e = builder.getTokenType(); parseTyVarBinds(builder, t.tyVarBinds, comments); e = builder.getTokenType(); consumeToken(builder, PERIOD); } parseContextTopType(builder, t.context, comments); e = builder.getTokenType(); if (e == DOUBLEARROW) consumeToken(builder, DOUBLEARROW); parseTypeTopType(builder, t.type, comments); e = builder.getTokenType(); } else if (typeTopType instanceof TyFun) { parseTypeTopType(builder, ((TyFun) typeTopType).t1, comments); consumeToken(builder, RIGHTARROW); parseTypeTopType(builder, ((TyFun) typeTopType).t2, comments); } else if (typeTopType instanceof TyTuple) { consumeToken(builder, LPAREN); e = builder.getTokenType(); boolean unboxed = parseBoxed(builder, ((TyTuple) typeTopType).boxed, comments); e = builder.getTokenType(); parseTypeTopTypes(builder, ((TyTuple) typeTopType).types, comments); e = builder.getTokenType(); if (unboxed) { consumeToken(builder, HASH); e = builder.getTokenType(); } consumeToken(builder, RPAREN); e = builder.getTokenType(); } else if (typeTopType instanceof TyList) { consumeToken(builder, LBRACKET); e = builder.getTokenType(); parseTypeTopType(builder, ((TyList) typeTopType).t, comments); e = builder.getTokenType(); consumeToken(builder, RBRACKET); e = builder.getTokenType(); } else if (typeTopType instanceof TyApp) { parseTypeTopType(builder, ((TyApp) typeTopType).t1, comments); e = builder.getTokenType(); parseTypeTopType(builder, ((TyApp) typeTopType).t2, comments); e = builder.getTokenType(); } else if (typeTopType instanceof TyVar) { parseName(builder, ((TyVar) typeTopType).name, comments); e = builder.getTokenType(); } else if (typeTopType instanceof TyCon) { parseQName(builder, ((TyCon) typeTopType).qName, comments); } else if (typeTopType instanceof TyParen) { consumeToken(builder, LPAREN); e = builder.getTokenType(); parseTypeTopType(builder, ((TyParen) typeTopType).type, comments); e = builder.getTokenType(); consumeToken(builder, RPAREN); e = builder.getTokenType(); } else if (typeTopType instanceof TyInfix) { e = builder.getTokenType(); parseTypeTopType(builder, ((TyInfix) typeTopType).t1, comments); e = builder.getTokenType(); parseQName(builder, ((TyInfix) typeTopType).qName, comments); e = builder.getTokenType(); parseTypeTopType(builder, ((TyInfix) typeTopType).t2, comments); e = builder.getTokenType(); } else if (typeTopType instanceof TyKind) { e = builder.getTokenType(); consumeToken(builder, LPAREN); e = builder.getTokenType(); parseTypeTopType(builder, ((TyKind) typeTopType).type, comments); e = builder.getTokenType(); consumeToken(builder, DOUBLECOLON); e = builder.getTokenType(); parseKindTopType(builder, ((TyKind) typeTopType).kind, comments); e = builder.getTokenType(); consumeToken(builder, RPAREN); e = builder.getTokenType(); } else { throw new RuntimeException("parseTypeTopType: " + typeTopType.toString()); } } /** * Parses a list of kinds. */ private static void parseKindTopTypes(PsiBuilder builder, KindTopType[] kinds, Comment[] comments) { IElementType e = builder.getTokenType(); int i = 0; while (kinds != null && i < kinds.length) { parseKindTopType(builder, kinds[i], comments); i++; e = builder.getTokenType(); if (e == COMMA) consumeToken(builder, COMMA); } } /** * Parses a kind. */ private static void parseKindTopType(PsiBuilder builder, KindTopType kind, Comment[] comments) { IElementType e = builder.getTokenType(); if (kind instanceof KindStar) { consumeToken(builder, ASTERISK); e = builder.getTokenType(); } else if (kind instanceof KindBang) { consumeToken(builder, EXLAMATION); e = builder.getTokenType(); } else if (kind instanceof KindFn) { parseKindTopType(builder, ((KindFn) kind).k1, comments); consumeToken(builder, RIGHTARROW); parseKindTopType(builder, ((KindFn) kind).k2, comments); } else if (kind instanceof KindParen) { consumeToken(builder, LPAREN); e = builder.getTokenType(); parseKindTopType(builder, ((KindParen) kind).kind, comments); e = builder.getTokenType(); consumeToken(builder, RPAREN); e = builder.getTokenType(); } else if (kind instanceof KindVar) { parseQName(builder, ((KindVar) kind).qName, comments); e = builder.getTokenType(); } else if (kind instanceof KindApp) { parseKindTopType(builder, ((KindApp) kind).k1, comments); e = builder.getTokenType(); parseKindTopType(builder, ((KindApp) kind).k2, comments); e = builder.getTokenType(); } else if (kind instanceof KindTuple) { consumeToken(builder, SINGLEQUOTE); e = builder.getTokenType(); consumeToken(builder, LPAREN); e = builder.getTokenType(); parseKindTopTypes(builder, ((KindTuple) kind).kinds, comments); consumeToken(builder, RPAREN); e = builder.getTokenType(); } else if (kind instanceof KindList) { consumeToken(builder, SINGLEQUOTE); e = builder.getTokenType(); consumeToken(builder, LBRACKET); e = builder.getTokenType(); parseKindTopTypes(builder, ((KindList) kind).kinds, comments); consumeToken(builder, RBRACKET); e = builder.getTokenType(); } } /** * Parses a list of qualified statements. */ private static void parseQualStmtTopTypes(PsiBuilder builder, QualStmtTopType[] qualStmtTopTypes, Comment[] comments) { IElementType e = builder.getTokenType(); int i = 0; while (qualStmtTopTypes != null && i < qualStmtTopTypes.length) { parseQualStmtTopType(builder, qualStmtTopTypes[i], comments); i++; e = builder.getTokenType(); if (e == COMMA) consumeToken(builder, COMMA); } } /** * Parses one qualified statement. */ private static void parseQualStmtTopType(PsiBuilder builder, QualStmtTopType qualStmtTopType, Comment[] comments) { IElementType e = builder.getTokenType(); if (qualStmtTopType instanceof QualStmt) { parseStmtTopType(builder, ((QualStmt) qualStmtTopType).stmt, comments); } else if (qualStmtTopType instanceof ThenTrans) { consumeToken(builder, THEN); e = builder.getTokenType(); parseExpTopType(builder, ((ThenTrans) qualStmtTopType).exp, comments); e = builder.getTokenType(); } else if (qualStmtTopType instanceof ThenBy) { consumeToken(builder, THEN); e = builder.getTokenType(); parseExpTopType(builder, ((ThenBy) qualStmtTopType).e1, comments); e = builder.getTokenType(); builder.advanceLexer(); // TODO: Add Token.BY e = builder.getTokenType(); parseExpTopType(builder, ((ThenBy) qualStmtTopType).e2, comments); e = builder.getTokenType(); } else if (qualStmtTopType instanceof GroupBy) { consumeToken(builder, THEN); e = builder.getTokenType(); builder.advanceLexer(); // TODO: Add Token.GROUP e = builder.getTokenType(); builder.advanceLexer(); // TODO: Add Token.USING e = builder.getTokenType(); parseExpTopType(builder, ((GroupBy) qualStmtTopType).exp, comments); e = builder.getTokenType(); } else if (qualStmtTopType instanceof GroupUsing) { consumeToken(builder, THEN); e = builder.getTokenType(); builder.advanceLexer(); // TODO: Add Token.GROUP e = builder.getTokenType(); builder.advanceLexer(); // TODO: Add Token.USING e = builder.getTokenType(); parseExpTopType(builder, ((GroupUsing) qualStmtTopType).exp, comments); e = builder.getTokenType(); } else if (qualStmtTopType instanceof GroupByUsing) { consumeToken(builder, THEN); e = builder.getTokenType(); builder.advanceLexer(); // TODO: Add Token.GROUP e = builder.getTokenType(); builder.advanceLexer(); // TODO: Add Token.BY e = builder.getTokenType(); parseExpTopType(builder, ((GroupByUsing) qualStmtTopType).e1, comments); e = builder.getTokenType(); builder.advanceLexer(); // TODO: Add Token.USING. parseExpTopType(builder, ((GroupByUsing) qualStmtTopType).e2, comments); e = builder.getTokenType(); } } /** * Parses contexts. */ private static void parseContextTopType(PsiBuilder builder, ContextTopType context, Comment[] comments) { IElementType e = builder.getTokenType(); if (context instanceof CxSingle) { parseAsstTopType(builder, ((CxSingle) context).asst, comments); } else if (context instanceof CxTuple) { consumeToken(builder, LPAREN); e = builder.getTokenType(); parseAsstTopTypes(builder, ((CxTuple) context).assts, comments); e = builder.getTokenType(); consumeToken(builder, RPAREN); e = builder.getTokenType(); } else if (context instanceof CxParen) { consumeToken(builder, LPAREN); parseContextTopType(builder, ((CxParen) context).context, comments); e = builder.getTokenType(); consumeToken(builder, RPAREN); e = builder.getTokenType(); } else if (context instanceof CxEmpty) { throw new RuntimeException("TODO: Implement CxEmpty"); } } /** * Parses a list of Assts. */ private static void parseAsstTopTypes(PsiBuilder builder, AsstTopType[] assts, Comment[] comments) { int i = 0; IElementType e = builder.getTokenType(); while (assts != null && i < assts.length) { parseAsstTopType(builder, assts[i], comments); i++; e = builder.getTokenType(); if (e == COMMA) { consumeToken(builder, COMMA); e = builder.getTokenType(); } } } /** * Parses Assts. */ private static void parseAsstTopType(PsiBuilder builder, AsstTopType asst, Comment[] comments) { IElementType e = builder.getTokenType(); if (asst instanceof ClassA) { parseQName(builder, ((ClassA) asst).qName, comments); e = builder.getTokenType(); parseTypeTopTypes(builder, ((ClassA) asst).types, comments); e = builder.getTokenType(); } else if (asst instanceof InfixA) { parseTypeTopType(builder, ((InfixA) asst).t1, comments); e = builder.getTokenType(); parseQName(builder, ((InfixA) asst).qName, comments); e = builder.getTokenType(); parseTypeTopType(builder, ((InfixA) asst).t2, comments); e = builder.getTokenType(); } else if (asst instanceof IParam) { throw new RuntimeException("TODO: Parse IParam"); /* Preliminary untested implementation: parseContextTopType(builder, ((IParam) asst).ipName, comments); e = builder.getTokenType(); parseTypeTopType(builder, ((IParam) asst).type, comments); e = builder.getTokenType(); */ } else if (asst instanceof EqualP) { throw new RuntimeException("TODO: Parse EqualP"); /* Preliminary untested implementation: parseTypeTopType(builder, ((EqualP) asst).t1, comments); consumeToken(builder, TILDETOKENHERE); e = builder.getTokenType(); parseTypeTopType(builder,((EqualP) asst).t2, comments); e = builder.getTokenType(); */ } } /** * Parses box annotations. */ public static boolean parseBoxed(PsiBuilder builder, BoxedTopType boxedTopType, Comment[] comments) { // TODO: Improve granularity. IElementType e = builder.getTokenType(); if (boxedTopType instanceof Boxed) { return false; } else if (boxedTopType instanceof Unboxed) { consumeToken(builder, HASH); return true; } throw new RuntimeException("Unexpected boxing: " + boxedTopType.toString()); } /** * Parses a generic pragma. */ public static void parseGenericPragma(PsiBuilder builder, DeclTopType annPragma, Comment[] comments) { // TODO: Improve granularity. PsiBuilder.Marker pragmaMark = builder.mark(); IElementType e = builder.getTokenType(); chewPragma(builder); consumeToken(builder, CLOSEPRAGMA); pragmaMark.done(e); } /** * Eats a complete pragma and leaves the builder at CLOSEPRAGMA token. */ public static void chewPragma(PsiBuilder builder) { IElementType e = builder.getTokenType(); while (e != CLOSEPRAGMA) { builder.advanceLexer(); e = builder.getTokenType(); } } public static boolean consumeToken(PsiBuilder builder_, IElementType token) { if (nextTokenIsInner(builder_, token)) { builder_.advanceLexer(); return true; } return false; } public static boolean nextTokenIsInner(PsiBuilder builder_, IElementType expectedToken) { IElementType tokenType = builder_.getTokenType(); if (expectedToken != tokenType) { System.out.println("Found token: " + tokenType + " vs expected: " + expectedToken); } return expectedToken == tokenType; } }
package com.jmex.model.XMLparser; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.helpers.DefaultHandler; public class XMLtoBinary { private DataOutputStream myOut; /** * Converts an XML file to jME binary. The syntax is: "XMLtoBinary file.xml out.jme" * @param args 2 strings. The first is the XML file to read, the second is the place to place its output. */ public static void main(String[] args) { if (args.length!=2){ System.err.println("Correct way to use is: <FormatFile> <jmeoutputfile>"); System.err.println("For example: runner.xml runner.jme"); return; } File inFile=new File(args[0]); File outFile=new File(args[1]); if (!inFile.canRead()){ System.err.println("Cannot read input file " + inFile); return; } try { System.out.println("Converting file " + inFile + " to " + outFile); new XMLtoBinary().sendXMLtoBinary(new FileInputStream(inFile),new FileOutputStream(outFile)); } catch (IOException e) { System.err.println("Unable to convert:" + e); return; } System.out.println("Conversion complete!"); } /** * Creates a new XMl -> Binary object. */ public XMLtoBinary(){ } /** * The only function a user needs to call. It converts an XML file to jME's binary format * @param XmlStream A stream representing the XML file to convert * @param binFile The stream to save the XML's jME binary equivalent */ public void sendXMLtoBinary(InputStream XmlStream,OutputStream binFile){ myOut=new DataOutputStream(binFile); SAXParserFactory factory=SAXParserFactory.newInstance(); factory.setValidating(true); try { SAXParser parser=factory.newSAXParser(); parser.parse(XmlStream,new SAXConverter()); } catch (IOException e) { throw new RuntimeException("Unable to do IO correctly:" + e.getMessage()); } catch (ParserConfigurationException e) { throw new RuntimeException("Serious parser configuration error:" + e.getMessage()); } catch (SAXParseException e) { throw new RuntimeException(e.toString() +'\n' + "Line: " +e.getLineNumber() + '\n' + "Column: " + e.getColumnNumber()); }catch (SAXException e) { throw new RuntimeException("Unknown sax error: " + e.getMessage()); } } /** * This class reads XML files in a SAX manner. */ private class SAXConverter extends DefaultHandler{ private static final boolean DEBUG = false; public void startDocument() throws SAXException { try { myOut.writeLong(BinaryFormatConstants.BEGIN_FILE); } catch (IOException e) { throw new SAXException("Unable to write header:" + e); } } public void endDocument() throws SAXException { try { myOut.writeByte(BinaryFormatConstants.END_FILE); myOut.close(); } catch (IOException e) { throw new SAXException("Unable to close binFile outStream:"+e); } } public void startElement(String uri,String localName,String qName, Attributes atts) throws SAXException{ if (DEBUG) System.out.println("startElement:" + qName); try { myOut.writeByte(BinaryFormatConstants.BEGIN_TAG); myOut.writeUTF(qName); myOut.writeByte(atts.getLength()); for (int i=0;i<atts.getLength();i++){ String currentAtt=atts.getQName(i); myOut.writeUTF(currentAtt); processWrite(qName,currentAtt,atts.getValue(i)); } } catch (IOException e) { throw new SAXException("Unable to write start element: " + qName + " " + e); } } /** * Takes a tag's name, an attribute's name, and the value of the attribute and writes it in the * appropriate manner. For example, (&lt vertex data="blarg">) * @param qName Name of tag (example "vertex" ) * @param att Name of attribute (example "data" ) * @param value Name of the value of the attribute (example "blarg" ) * @throws IOException */ private void processWrite(String qName,String att, String value) throws IOException { if (DEBUG) System.out.println("processWrite qName=" + qName + "**att=" + att + "**value="+ value+"**"); if ("data".equals(att)){ if ("vertex".equals(qName) || "normal".equals(qName) || "origvertex".equals(qName)|| "orignormal".equals(qName)){ writeVector3fArray(value); } else if ("color".equals(qName)){ writeColorArray(value); } else if ("texturecoords".equals(qName)){ writeVector2fArray(value); } else if ("index".equals(qName) || "jointindex".equals(qName)){ writeIntArray(value); } else{ writeString(value); } } else if ("index".equals(att)){ if("sptscale".equals(qName) || "sptrot".equals(qName) || "spttrans".equals(qName)) writeIntArray(value); } else if ("loc".equals(att) || "dir".equals(att) || "scale".equals(att) || "translation".equals(att) || "trans".equals(att) || "localvec".equals(att) || "origcent".equals(att) || "origext".equals(att) || "nowcent".equals(att) || "nowext".equals(att)) { writeVec3f(value); } else if ("rotation".equals(att) || "rot".equals(att)){ writeQuat(value); } else if ("localrot".equals(att)){ writeMatrix(value); }else if ("alpha".equals(att) || "shiny".equals(att) || "time".equals(att) || "width".equals(att)){ writeFloat(value); } else if ("fconstant".equals(att) || "flinear".equals(att) || "fquadratic".equals(att) || "fangle".equals(att) || "fexponent".equals(att)){ writeFloat(value); } else if ("ambient".equals(att) || "diffuse".equals(att) || "emissive".equals(att) || "specular".equals(att)){ writeColor(value); } else if ("URL".equals(att)){ writeURL(value); } else if ("isattenuate".equals(att)){ writeBoolean(value); } else if ("numJoints".equals(att) || "index".equals(att) || "parentindex".equals(att)){ writeInt(value); } else if ("v3farray".equals(att) || "scalevalues".equals(att) || "transvalues".equals(att)){ writeVector3fArray(value); } else if ("quatarray".equals(att) || "rotvalues".equals(att)){ writeQuatArray(value); } else if ("q3norm".equals(att)){ writeShortArray(value); } else if ("q3vert".equals(att)){ writeByteArray(value); } else if ("texnum".equals(att) || "wrap".equals(att) || "parnum".equals(att) || "obnum".equals(att) || "facetype".equals(att) || "numobjects".equals(att)){ writeInt(value); } else writeString(value); } private void writeShortArray(String data) throws IOException { myOut.writeByte(BinaryFormatConstants.DATA_SHORTARRAY); if (data==null || data.length()==0) { myOut.writeInt(0); return; } String [] information=removeDoubleWhiteSpaces(data).trim().split(" "); if (information.length==1 && "".equals(information[0])){ myOut.writeInt(0); return; } myOut.writeInt(information.length); for (int i=0;i<information.length;i++){ myOut.writeShort(Short.parseShort(information[i])); } } private void writeByteArray(String data) throws IOException { myOut.writeByte(BinaryFormatConstants.DATA_BYTEARRAY); if (data==null || data.length()==0) { myOut.writeInt(0); return; } String [] information=removeDoubleWhiteSpaces(data).trim().split(" "); if (information.length==1 && "".equals(information[0])){ myOut.writeInt(0); return; } myOut.writeInt(information.length); for (int i=0;i<information.length;i++){ myOut.writeShort(Byte.parseByte(information[i])); } } private void writeQuatArray(String data) throws IOException { myOut.writeByte(BinaryFormatConstants.DATA_QUATARRAY); if (data==null || data.length()==0){ myOut.writeInt(0); return; } String [] information=removeDoubleWhiteSpaces(data).trim().split(" "); if (information.length==1 && "".equals(information[0])){ myOut.writeInt(0); return; } if (information.length%4!=0){ throw new IOException("Quat length not modulus of 4: " + information.length); } myOut.writeInt(information.length/4); for (int i=0;i<information.length/4;i++){ myOut.writeFloat(Float.parseFloat(information[i*4+0])); myOut.writeFloat(Float.parseFloat(information[i*4+1])); myOut.writeFloat(Float.parseFloat(information[i*4+2])); myOut.writeFloat(Float.parseFloat(information[i*4+3])); } } private void writeBoolean(String value) throws IOException { boolean toWrite; if ("true".equals(value)) toWrite=true; else if ("false".equals(value)) toWrite=false; else throw new IOException("Parameter must be true or false, not " + value); myOut.writeByte(BinaryFormatConstants.DATA_BOOLEAN); myOut.writeBoolean(toWrite); } private void writeInt(String value) throws IOException { myOut.write(BinaryFormatConstants.DATA_INT); myOut.writeInt(Integer.parseInt(value)); } private void writeURL(String value) throws IOException { myOut.writeByte(BinaryFormatConstants.DATA_URL); myOut.writeUTF(value); } private void writeColor(String value) throws IOException{ myOut.writeByte(BinaryFormatConstants.DATA_COLOR); String [] split=value.trim().split(" "); if (split.length!=4) throw new IOException("ilformated Color:" + value); myOut.writeFloat(Float.parseFloat(split[0])); myOut.writeFloat(Float.parseFloat(split[1])); myOut.writeFloat(Float.parseFloat(split[2])); myOut.writeFloat(Float.parseFloat(split[3])); } private void writeFloat(String value) throws IOException { myOut.writeByte(BinaryFormatConstants.DATA_FLOAT); myOut.writeFloat(Float.parseFloat(value)); } private void writeMatrix(String value) throws IOException { myOut.writeByte(BinaryFormatConstants.DATA_MATRIX3); String [] split=value.trim().split(" "); if (split.length!=9) throw new IOException("ilformated Matrix3:" + value); for (int i=0;i<9;i++) myOut.writeFloat(Float.parseFloat(split[i])); } private void writeQuat(String value) throws IOException { myOut.writeByte(BinaryFormatConstants.DATA_QUAT); String [] split=value.trim().split(" "); if (split.length!=4) throw new IOException("ilformated Quat:" + value); myOut.writeFloat(Float.parseFloat(split[0])); myOut.writeFloat(Float.parseFloat(split[1])); myOut.writeFloat(Float.parseFloat(split[2])); myOut.writeFloat(Float.parseFloat(split[3])); } private void writeVec3f(String value) throws IOException { myOut.writeByte(BinaryFormatConstants.DATA_V3F); String [] split=value.trim().split(" "); if (split.length!=3) throw new IOException("ilformated Vector3f:" + value); myOut.writeFloat(Float.parseFloat(split[0])); myOut.writeFloat(Float.parseFloat(split[1])); myOut.writeFloat(Float.parseFloat(split[2])); } private void writeString(String value) throws IOException { myOut.writeByte(BinaryFormatConstants.DATA_STRING); myOut.writeUTF(value); } private void writeIntArray(String data) throws IOException { myOut.writeByte(BinaryFormatConstants.DATA_INTARRAY); if (data==null || data.length()==0) { myOut.writeInt(0); return; } String [] information=removeDoubleWhiteSpaces(data).trim().split(" "); if (information.length==1 && "".equals(information[0])){ myOut.writeInt(0); return; } myOut.writeInt(information.length); for (int i=0;i<information.length;i++){ myOut.writeInt(Integer.parseInt(information[i])); } } private void writeVector2fArray(String data) throws IOException { myOut.writeByte(BinaryFormatConstants.DATA_V2FARRAY); if (data==null || data.length()==0){ myOut.writeInt(0); return; } String [] information=removeDoubleWhiteSpaces(data).trim().split(" "); if (information.length==1 && "".equals(information[0])){ myOut.writeInt(0); return; } if (information.length%2!=0){ throw new IOException("Vector2f length not modulus of 2: " + information.length); } myOut.writeInt(information.length/2); for (int i=0;i<information.length/2;i++){ myOut.writeFloat(Float.parseFloat(information[i*2+0])); myOut.writeFloat(Float.parseFloat(information[i*2+1])); } } public void writeColorArray(String data) throws IOException { myOut.writeByte(BinaryFormatConstants.DATA_COLORARRAY); if (data == null || data.length()==0){ myOut.writeInt(0); return; } String [] information=removeDoubleWhiteSpaces(data).trim().split(" "); if (information.length==1 && "".equals(information[0])){ myOut.writeInt(0); return; } if (information.length%4!=0){ throw new IOException("Color length not modulus of 4: " + information.length); } myOut.writeInt(information.length/4); for (int i=0;i<information.length/4;i++){ myOut.writeFloat(Float.parseFloat(information[i*4+0])); myOut.writeFloat(Float.parseFloat(information[i*4+1])); myOut.writeFloat(Float.parseFloat(information[i*4+2])); myOut.writeFloat(Float.parseFloat(information[i*4+3])); } } private void writeVector3fArray(String data) throws IOException{ myOut.writeByte(BinaryFormatConstants.DATA_V3FARRAY); if (data==null || data.length()==0){ myOut.writeInt(0); return; } String [] information=removeDoubleWhiteSpaces(data).trim().split(" "); if (information.length==1 && "".equals(information[0])){ myOut.writeInt(0); return; } if (information.length%3!=0){ throw new IOException("Vector3f length not modulus of 3: " + information.length); } myOut.writeInt(information.length/3); for (int i=0;i<information.length/3;i++){ myOut.writeFloat(Float.parseFloat(information[i*3+0])); myOut.writeFloat(Float.parseFloat(information[i*3+1])); myOut.writeFloat(Float.parseFloat(information[i*3+2])); } } /** * Whenever two or more whitespaces are next to each other, they are removed and replaced by ' '. * @param data The string to remove from * @return A new, removed string */ private String removeDoubleWhiteSpaces(String data) { StringBuffer toReturn=new StringBuffer(); boolean whiteSpaceFlag=false; for (int i=0;i<data.length();i++){ if (Character.isWhitespace(data.charAt(i))){ if (!whiteSpaceFlag && toReturn.length()!=0) toReturn.append(' '); whiteSpaceFlag = true; } else{ toReturn.append(data.charAt(i)); whiteSpaceFlag=false; } } return toReturn.toString(); } public void endElement(String uri,String localName, String qName) throws SAXException{ try { if (DEBUG) System.out.println("endElement:" + qName); myOut.writeByte(BinaryFormatConstants.END_TAG); myOut.writeUTF(qName); } catch (IOException e) { throw new SAXException("Unable to write end element: " + qName + " " + e); } } } }
package com.magneticbear.scala1; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.webkit.WebView; import android.webkit.WebViewClient; import android.webkit.SslErrorHandler; import android.widget.TextView; import android.widget.Toast; import android.net.http.SslError; public class SpeakersInfo extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_speakers_info); // Setup debug data String speaker_title_to_display = "Speaker Info"; int speaker_id_to_load = 1; // Navigate to speaker url WebView speakers_info_webview = (WebView)findViewById(R.id.webview_speaker_info); // This is a bugfix for HTTPS pages, that will just not display because the user is not prompted // to accept the cert. This is an android bug, and this is the accepted workaround speakers_info_webview.setWebViewClient(new WebViewClient() { public void onReceivedSslError (WebView view, SslErrorHandler handler, SslError error) { handler.proceed(); } }); speakers_info_webview.getSettings().setJavaScriptEnabled(true); speakers_info_webview.loadUrl(getString(R.string.url_speakers_info_base) + speaker_id_to_load); // Set title to speaker name title TextView title = (TextView)findViewById(R.id.speaker_info_title); title.setText(speaker_title_to_display); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_speakers_info, menu); return true; } @Override public void onBackPressed() { // Go to speakers Intent intent = new Intent(getBaseContext(), Speakers.class); startActivityForResult(intent, 0); } }
package com.precisionguessworks.frc; import com.sun.squawk.microedition.io.FileConnection; import com.sun.squawk.util.Arrays; import java.io.IOException; import java.io.PrintStream; import java.util.Calendar; import javax.microedition.io.Connector; public class DataFile { public final boolean EnableFileWritting = false; private final PrintStream file; public DataFile(String suffix) throws IOException { if (EnableFileWritting) { Calendar cal = Calendar.getInstance(); String year = new Integer(cal.get(Calendar.YEAR)).toString(); String month = new Integer(cal.get(Calendar.MONTH) + 1).toString(); String date = new Integer(cal.get(Calendar.DATE)).toString(); String hour = new Integer(cal.get(Calendar.HOUR_OF_DAY)).toString(); String minute = new Integer(cal.get(Calendar.MINUTE)).toString(); String second = new Integer(cal.get(Calendar.SECOND)).toString(); String name = year + DataFile.paddingString(month, 2, '0', true) + DataFile.paddingString(date, 2, '0', true) + "-" + DataFile.paddingString(hour, 2, '0', true) + DataFile.paddingString(minute, 2, '0', true) + DataFile.paddingString(second, 2, '0', true) + "_" + suffix + ".csv"; FileConnection connection = (FileConnection) Connector.open("file:///" + name, Connector.WRITE); connection.create(); this.file = new PrintStream(connection.openDataOutputStream()); System.out.println("Writing sensor data to: " + name); } else { this.file = null; System.out.println("Skipping writting data to file " + suffix + ", renable with DataFile.EnableFileWritting"); } } public void writeln(String line) { if (EnableFileWritting) { this.file.println(line); } } private static String paddingString(String s, int n, char c, boolean paddingLeft) { if (s == null) { return s; } int add = n - s.length(); // may overflow int size... should not be a problem in real life if(add <= 0) { return s; } StringBuffer str = new StringBuffer(s); char[] ch = new char[add]; Arrays.fill(ch, c); if(paddingLeft){ str.insert(0, ch); } else { str.append(ch); } return str.toString(); } }
package org.ode4j.drawstuff.internal; import org.lwjgl.LWJGLException; import org.lwjgl.Sys; import org.lwjgl.input.Keyboard; import org.lwjgl.input.Mouse; import org.lwjgl.opengl.Display; import org.lwjgl.opengl.DisplayMode; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GLContext; import org.ode4j.drawstuff.DrawStuff; import org.ode4j.drawstuff.DrawStuff.dsFunctions; import org.ode4j.ode.OdeHelper; import org.ode4j.ode.internal.Common; import static org.cpp4j.Cstdio.*; /** * Main window and event handling for LWJGL. */ abstract class LwJGL extends Internal implements DrawStuffApi { //Ensure that Display.destroy() is called (TZ) //Not sure this works, but it's an attempt at least. //-> This should avoid the Problem that a process keeps running with 99%CPU, // even if the window is closed (clicking on the 'x'). The supposed // problem is that when clicking 'x', Display.destroy() never gets called // by dsPlatformSimLoop(). static { Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { // Display.destroy(); } }); } /** * Handles the keyboard * @param fn */ private void handleKeyboard(dsFunctions fn) { Keyboard.poll(); while(Keyboard.next()) { char key = (char) Keyboard.getEventKey(); if (key == Keyboard.KEY_ESCAPE) { run = false; } if (!(Keyboard.isKeyDown(Keyboard.KEY_LCONTROL) || Keyboard.isKeyDown(Keyboard.KEY_RCONTROL))) { // if ((event.xkey.state & ControlMask) == 0) { //if (key >= ' ' && key <= 126 && fn.command) fn.command (key); char keyChar = Keyboard.getEventCharacter(); if (keyChar >= ' ' && keyChar <= 126) fn.command (keyChar); // System.out.println("cmd-c " +Keyboard.getEventCharacter()); // System.out.println("cmd- " + (char)(key+65)); } else { //if (event.xkey.state & ControlMask) { if (key == last_key_pressed) { continue; } switch (key) { case Keyboard.KEY_T: dsSetTextures (!dsGetTextures()); break; case Keyboard.KEY_S: dsSetShadows (!dsGetShadows()); break; case Keyboard.KEY_X: run = false; break; case Keyboard.KEY_P: pause = !pause; singlestep = false; break; case Keyboard.KEY_O: if (pause) singlestep = true; break; case Keyboard.KEY_V: { float[] xyz=new float [3], hpr = new float [3]; dsGetViewpoint (xyz,hpr); printf ("Viewpoint = (%.4f,%.4f,%.4f,%.4f,%.4f,%.4f)\n", xyz[0],xyz[1],xyz[2],hpr[0],hpr[1],hpr[2]); break; } case Keyboard.KEY_W: writeframes = !writeframes; if (writeframes) printf ("Now writing frames to PPM files\n"); break; } } last_key_pressed = key; // a kludgy place to put this... } } /** * handles the mouse */ private void handleMouse() { readBufferedMouse(); } /** * reads a mouse in buffered mode */ private void readBufferedMouse() { // iterate all events, use the last button down while(Mouse.next()) { if (Mouse.getEventButton() != -1) { if (Mouse.getEventButtonState()) { } //lastButton = Mouse.getEventButton(); } } updateState(); } /** * Updates our "model" * */ private void updateState() { int dx = Mouse.getDX(); int dy = Mouse.getDY(); int dw = Mouse.getDWheel(); // get out if no movement if (dx == dy && dx == 0 && dw == 0) { return; } //LWJGL: 0=left 1=right 2=middle //GL: 0=left 1=middle 2=right int mode = 0; if (Mouse.isButtonDown(0)) mode |= 1; if (Mouse.isButtonDown(2)) mode |= 2; if (Mouse.isButtonDown(1)) mode |= 4; if (mode != 0) { //LWJGL has inverted dy wrt C++/GL dsMotion (mode, dx, -dy); } } //void dsPlatformSimLoop (int window_width, int window_height, dsFunctions *fn, // int initial_pause) private static boolean firsttime=true; void dsPlatformSimLoop (int window_width, int window_height, dsFunctions fn, boolean initial_pause) { pause = initial_pause; createMainWindow (window_width, window_height); //glXMakeCurrent (display,win,glx_context); //TODO ? //GLContext.useContext(context); try { //Sets the context / by TZ Display.makeCurrent(); } catch (LWJGLException e) { throw new RuntimeException(e); } dsStartGraphics (window_width,window_height,fn); //TZ static bool firsttime=true; if (firsttime) { System.err.println(); System.err.print("Using ode4j version: " + OdeHelper.getVersion()); System.err.println(" [" + OdeHelper.getConfiguration() + "]"); System.err.println(); fprintf ( stderr, "\n" + "Simulation test environment v%d.%02d\n" + " Ctrl-P : pause / unpause (or say `-pause' on command line).\n" + " Ctrl-O : single step when paused.\n" + " Ctrl-T : toggle textures (or say `-notex' on command line).\n" + " Ctrl-S : toggle shadows (or say `-noshadow' on command line).\n" + " Ctrl-V : print current viewpoint coordinates (x,y,z,h,p,r).\n" + " Ctrl-W : write frames to ppm files: frame/frameNNN.ppm\n" + " Ctrl-X : exit.\n" + "\n" + "Change the camera position by clicking + dragging in the window.\n" + " Left button - pan and tilt.\n" + " Right button - forward and sideways.\n" + " Left + Right button (or middle button) - sideways and up.\n" + "\n",DrawStuff.DS_VERSION >> 8,DrawStuff.DS_VERSION & 0xff ); firsttime = false; } //if (fn.start) fn.start(); int frame = 1; run = true; long startTime = System.currentTimeMillis() + 5000; long fps = 0; while (run && !Display.isCloseRequested()) { // while (run) { // read in and process all pending events for the main window // XEvent event; // while (run && XPending (display)) { // XNextEvent (display,event); // handleEvent (event,fn); handleKeyboard(fn); handleMouse(); GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT); dsDrawFrame (width,height,fn,pause && !singlestep); singlestep = false; Display.update(); if (startTime > System.currentTimeMillis()) { fps++; } else { long timeUsed = 5000 + (startTime - System.currentTimeMillis()); startTime = System.currentTimeMillis() + 5000; System.out.println(fps + " frames in " + (float) (timeUsed / 1000f) + " seconds = " + (fps / (timeUsed / 1000f))); fps = 0; } // glFlush(); // glXSwapBuffers (display,win); // XSync (display,0); // capture frames if necessary if (pause==false && writeframes) { captureFrame (frame); frame++; } } //if (fn.stop) fn.stop(); dsStopGraphics(); destroyMainWindow(); } //extern "C" void dsStop() public void dsStop() { run = false; } private static double prev=(double)System.nanoTime()/1000000000.0; //extern "C" double dsElapsedTime() public double dsElapsedTime() { if (true) {//(HAVE_GETTIMEOFDAY) { //#if HAVE_GETTIMEOFDAY //TZ static double prev=0.0; // timeval tv ; // gettimeofday(tv, 0); // double curr = tv.tv_sec + (double) tv.tv_usec / 1000000.0 ; double curr = (double)System.nanoTime()/1000000000.0; // if (prev==-1) // prev=curr; double retval = curr-prev; prev=curr; if (retval>1.0) retval=1.0; if (retval<Common.dEpsilon) retval=Common.dEpsilon; return retval; } else { //#else return 0.01666; // Assume 60 fps //#endif } } }
package mondrian.rolap.aggmatcher; import mondrian.olap.MondrianProperties; import mondrian.olap.MondrianDef; import mondrian.olap.Util; import mondrian.rolap.RolapAggregator; import mondrian.rolap.RolapStar; import mondrian.resource.MondrianResource; import mondrian.spi.Dialect; import javax.sql.DataSource; import org.apache.log4j.Logger; import java.lang.ref.SoftReference; import java.io.PrintWriter; import java.io.StringWriter; import java.sql.ResultSet; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.Types; import java.sql.SQLException; import java.util.*; /** * Metadata gleaned from JDBC about the tables and columns in the star schema. * This class is used to scrape a database and store information about its * tables and columnIter. * * <p>The structure of this information is as follows: A database has tables. A * table has columnIter. A column has one or more usages. A usage might be a * column being used as a foreign key or as part of a measure. * * <p> Tables are created when calling code requests the set of available * tables. This call <code>getTables()</code> causes all tables to be loaded. * But a table's columnIter are not loaded until, on a table-by-table basis, * a request is made to get the set of columnIter associated with the table. * Since, the AggTableManager first attempts table name matches (recognition) * most tables do not match, so why load their columnIter. * Of course, as a result, there are a host of methods that can throw an * {@link SQLException}, rats. * * @author Richard M. Emberson * @version $Id$ */ public class JdbcSchema { private static final Logger LOGGER = Logger.getLogger(JdbcSchema.class); private static final MondrianResource mres = MondrianResource.instance(); /** * Returns the Logger. */ public Logger getLogger() { return LOGGER; } public interface Factory { JdbcSchema makeDB(DataSource dataSource); void clearDB(JdbcSchema db); void removeDB(JdbcSchema db); } private static final Map<DataSource, SoftReference<JdbcSchema>> dbMap = new HashMap<DataSource, SoftReference<JdbcSchema>>(); /** * How often between sweeping through the dbMap looking for nulls. */ private static final int SWEEP_COUNT = 10; private static int sweepDBCount = 0; public static class StdFactory implements Factory { StdFactory() { } public JdbcSchema makeDB(DataSource dataSource) { return new JdbcSchema(dataSource); } public void clearDB(JdbcSchema db) { // NoOp } public void removeDB(JdbcSchema db) { // NoOp } } private static Factory factory; private static void makeFactory() { if (factory == null) { String classname = MondrianProperties.instance().JdbcFactoryClass.get(); if (classname == null) { factory = new StdFactory(); } else { try { Class<?> clz = Class.forName(classname); factory = (Factory) clz.newInstance(); } catch (ClassNotFoundException ex) { throw mres.BadJdbcFactoryClassName.ex(classname); } catch (InstantiationException ex) { throw mres.BadJdbcFactoryInstantiation.ex(classname); } catch (IllegalAccessException ex) { throw mres.BadJdbcFactoryAccess.ex(classname); } } } } /** * Creates or retrieves an instance of the JdbcSchema for the given * DataSource. * * @param dataSource DataSource * @return instance of the JdbcSchema for the given DataSource */ public static synchronized JdbcSchema makeDB(DataSource dataSource) { makeFactory(); JdbcSchema db = null; SoftReference<JdbcSchema> ref = dbMap.get(dataSource); if (ref != null) { db = ref.get(); } if (db == null) { db = factory.makeDB(dataSource); dbMap.put(dataSource, new SoftReference<JdbcSchema>(db)); } sweepDB(); return db; } /** * Clears information in a JdbcSchema associated with a DataSource. * * @param dataSource DataSource */ public static synchronized void clearDB(DataSource dataSource) { makeFactory(); SoftReference<JdbcSchema> ref = dbMap.get(dataSource); if (ref != null) { JdbcSchema db = ref.get(); if (db != null) { factory.clearDB(db); db.clear(); } else { dbMap.remove(dataSource); } } sweepDB(); } /** * Removes a JdbcSchema associated with a DataSource. * * @param dataSource DataSource */ public static synchronized void removeDB(DataSource dataSource) { makeFactory(); SoftReference<JdbcSchema> ref = dbMap.remove(dataSource); if (ref != null) { JdbcSchema db = ref.get(); if (db != null) { factory.removeDB(db); db.remove(); } } sweepDB(); } /** * Every SWEEP_COUNT calls to this method, go through all elements of * the dbMap removing all that either have null values (null SoftReference) * or those with SoftReference with null content. */ private static void sweepDB() { if (sweepDBCount++ > SWEEP_COUNT) { Iterator<SoftReference<JdbcSchema>> it = dbMap.values().iterator(); while (it.hasNext()) { SoftReference<JdbcSchema> ref = it.next(); if ((ref == null) || (ref.get() == null)) { try { it.remove(); } catch (Exception ex) { // Should not happen, but might still like to // know that something's funky. LOGGER.warn(ex); } } } // reset sweepDBCount = 0; } } // Types of column usages. public static final int UNKNOWN_COLUMN_USAGE = 0x0001; public static final int FOREIGN_KEY_COLUMN_USAGE = 0x0002; public static final int MEASURE_COLUMN_USAGE = 0x0004; public static final int LEVEL_COLUMN_USAGE = 0x0008; public static final int FACT_COUNT_COLUMN_USAGE = 0x0010; public static final int IGNORE_COLUMN_USAGE = 0x0020; public static final String UNKNOWN_COLUMN_NAME = "UNKNOWN"; public static final String FOREIGN_KEY_COLUMN_NAME = "FOREIGN_KEY"; public static final String MEASURE_COLUMN_NAME = "MEASURE"; public static final String LEVEL_COLUMN_NAME = "LEVEL"; public static final String FACT_COUNT_COLUMN_NAME = "FACT_COUNT"; public static final String IGNORE_COLUMN_NAME = "IGNORE"; /** * Enumeration of ways that an aggregate table can use a column. */ enum UsageType { UNKNOWN, FOREIGN_KEY, MEASURE, LEVEL, FACT_COUNT, IGNORE } /** * Determine if the parameter represents a single column type, i.e., the * column only has one usage. * * @param columnType Column types * @return true if column has only one usage. */ public static boolean isUniqueColumnType(Set<UsageType> columnType) { return columnType.size() == 1; } /** * Maps from column type enum to column type name or list of names if the * parameter represents more than on usage. */ public static String convertColumnTypeToName(Set<UsageType> columnType) { if (columnType.size() == 1) { return columnType.iterator().next().name(); } // it's a multi-purpose column StringBuilder buf = new StringBuilder(); int k = 0; for (UsageType usage : columnType) { if (k++ > 0) { buf.append('|'); } buf.append(usage.name()); } return buf.toString(); } /** * Converts a {@link java.sql.Types} value to a * {@link mondrian.spi.Dialect.Datatype}. * * @param javaType JDBC type code, as per {@link java.sql.Types} * @return Datatype */ public static Dialect.Datatype getDatatype(int javaType) { switch (javaType) { case Types.TINYINT: case Types.SMALLINT: case Types.INTEGER: case Types.BIGINT: return Dialect.Datatype.Integer; case Types.FLOAT: case Types.REAL: case Types.DOUBLE: case Types.NUMERIC: case Types.DECIMAL: return Dialect.Datatype.Numeric; case Types.BOOLEAN: return Dialect.Datatype.Boolean; case Types.DATE: return Dialect.Datatype.Date; case Types.TIME: return Dialect.Datatype.Time; case Types.TIMESTAMP: return Dialect.Datatype.Timestamp; case Types.CHAR: case Types.VARCHAR: default: return Dialect.Datatype.String; } } /** * Returns true if the parameter is a java.sql.Type text type. */ public static boolean isText(int javaType) { switch (javaType) { case Types.CHAR: case Types.VARCHAR: case Types.LONGVARCHAR: return true; default: return false; } } enum TableUsageType { UNKNOWN, FACT, AGG } /** * A table in a database. */ public class Table { /** * A column in a table. */ public class Column { /** * A usage of a column. */ public class Usage { private final UsageType usageType; private String symbolicName; private RolapAggregator aggregator; // These instance variables are used to hold // stuff which is determines at one place and // then used somewhere else. Generally, a usage // is created before all of its "stuff" can be // determined, hence, usage is not a set of classes, // rather its one class with a bunch of instance // variables which may or may not be used. // measure stuff public RolapStar.Measure rMeasure; // hierarchy stuff public MondrianDef.Relation relation; public MondrianDef.Expression joinExp; public String levelColumnName; // level public RolapStar.Column rColumn; // for subtables public RolapStar.Table rTable; public String rightJoinConditionColumnName; /** * The prefix (possibly null) to use during aggregate table * generation (See AggGen). */ public String usagePrefix; /** * Creates a Usage. * * @param usageType Usage type */ Usage(UsageType usageType) { this.usageType = usageType; } /** * Returns the column with which this usage is associated. * * @return the usage's column. */ public Column getColumn() { return JdbcSchema.Table.Column.this; } /** * Returns the column usage type. */ public UsageType getUsageType() { return usageType; } /** * Sets the symbolic (logical) name associated with this usage. * For example, this might be the measure's name. * * @param symbolicName Symbolic name */ public void setSymbolicName(final String symbolicName) { this.symbolicName = symbolicName; } /** * Returns the usage's symbolic name. */ public String getSymbolicName() { return symbolicName; } /** * Sets the aggregator associated with this usage (if it is a * measure usage). * * @param aggregator Aggregator */ public void setAggregator(final RolapAggregator aggregator) { this.aggregator = aggregator; } /** * Returns the aggregator associated with this usage (if its a * measure usage, otherwise null). */ public RolapAggregator getAggregator() { return aggregator; } public String toString() { StringWriter sw = new StringWriter(64); PrintWriter pw = new PrintWriter(sw); print(pw, ""); pw.flush(); return sw.toString(); } public void print(final PrintWriter pw, final String prefix) { if (getSymbolicName() != null) { pw.print("symbolicName="); pw.print(getSymbolicName()); } if (getAggregator() != null) { pw.print(", aggregator="); pw.print(getAggregator().getName()); } pw.print(", columnType="); pw.print(getUsageType().name()); } } /** This is the name of the column. */ private final String name; /** This is the java.sql.Type enum of the column in the database. */ private int type; /** * This is the java.sql.Type name of the column in the database. */ private String typeName; /** This is the size of the column in the database. */ private int columnSize; /** The number of fractional digits. */ private int decimalDigits; /** Radix (typically either 10 or 2). */ private int numPrecRadix; /** For char types the maximum number of bytes in the column. */ private int charOctetLength; /** * False means the column definitely does not allow NULL values. */ private boolean isNullable; public final MondrianDef.Column column; private final List<JdbcSchema.Table.Column.Usage> usages; /** * This contains the enums of all of the column's usages. */ private final Set<UsageType> usageTypes = Util.enumSetNoneOf(UsageType.class); private Column(final String name) { this.name = name; this.column = new MondrianDef.Column( JdbcSchema.Table.this.getName(), name); this.usages = new ArrayList<JdbcSchema.Table.Column.Usage>(); } /** * Returns the column's name in the database, not a symbolic name. */ public String getName() { return name; } /** * Sets the columnIter java.sql.Type enun of the column. * * @param type */ private void setType(final int type) { this.type = type; } /** * Returns the columnIter java.sql.Type enun of the column. */ public int getType() { return type; } /** * Sets the columnIter java.sql.Type name. * * @param typeName */ private void setTypeName(final String typeName) { this.typeName = typeName; } /** * Returns the columnIter java.sql.Type name. */ public String getTypeName() { return typeName; } /** * Returns this column's table. */ public Table getTable() { return JdbcSchema.Table.this; } /** * Return true if this column is numeric. */ public Dialect.Datatype getDatatype() { return JdbcSchema.getDatatype(getType()); } /** * Sets the size in bytes of the column in the database. * * @param columnSize */ private void setColumnSize(final int columnSize) { this.columnSize = columnSize; } /** * Returns the size in bytes of the column in the database. * */ public int getColumnSize() { return columnSize; } /** * Sets number of fractional digits. * * @param decimalDigits */ private void setDecimalDigits(final int decimalDigits) { this.decimalDigits = decimalDigits; } /** * Returns number of fractional digits. */ public int getDecimalDigits() { return decimalDigits; } /** * Sets Radix (typically either 10 or 2). * * @param numPrecRadix */ private void setNumPrecRadix(final int numPrecRadix) { this.numPrecRadix = numPrecRadix; } /** * Returns Radix (typically either 10 or 2). */ public int getNumPrecRadix() { return numPrecRadix; } /** * For char types the maximum number of bytes in the column. * * @param charOctetLength */ private void setCharOctetLength(final int charOctetLength) { this.charOctetLength = charOctetLength; } /** * For char types the maximum number of bytes in the column. */ public int getCharOctetLength() { return charOctetLength; } /** * False means the column definitely does not allow NULL values. * * @param isNullable */ private void setIsNullable(final boolean isNullable) { this.isNullable = isNullable; } /** * False means the column definitely does not allow NULL values. */ public boolean isNullable() { return isNullable; } /** * How many usages does this column have. A column has * between 0 and N usages. It has no usages if usages is some * administrative column. It has one usage if, for example, its * the fact_count column or a level column (for a collapsed * dimension aggregate). It might have 2 usages if its a foreign key * that is also used as a measure. If its a column used in N * measures, then usages will have N usages. */ public int numberOfUsages() { return usages.size(); } /** * Return true if the column has at least one usage. */ public boolean hasUsage() { return (usages.size() != 0); } /** * Return true if the column has at least one usage of the given * column type. */ public boolean hasUsage(UsageType columnType) { return usageTypes.contains(columnType); } /** * Returns an iterator over all usages. */ public List<Usage> getUsages() { return usages; } /** * Returns an iterator over all usages of the given column type. */ public Iterator<Usage> getUsages(UsageType usageType) { class ColumnTypeIterator implements Iterator<Usage> { private final Iterator<Usage> usageIter; private final UsageType usageType; private Usage nextUsage; ColumnTypeIterator( final List<Usage> usages, final UsageType columnType) { this.usageIter = usages.iterator(); this.usageType = columnType; } public boolean hasNext() { while (usageIter.hasNext()) { Usage usage = usageIter.next(); if (usage.getUsageType() == this.usageType) { nextUsage = usage; return true; } } nextUsage = null; return false; } public Usage next() { return nextUsage; } public void remove() { usageIter.remove(); } } return new ColumnTypeIterator(getUsages(), usageType); } /** * Create a new usage of a given column type. */ public Usage newUsage(UsageType usageType) { this.usageTypes.add(usageType); Usage usage = new Usage(usageType); usages.add(usage); return usage; } public String toString() { StringWriter sw = new StringWriter(256); PrintWriter pw = new PrintWriter(sw); print(pw, ""); pw.flush(); return sw.toString(); } public void print(final PrintWriter pw, final String prefix) { pw.print(prefix); pw.print("name="); pw.print(getName()); pw.print(", typename="); pw.print(getTypeName()); pw.print(", size="); pw.print(getColumnSize()); switch (getType()) { case Types.TINYINT: case Types.SMALLINT: case Types.INTEGER: case Types.BIGINT: case Types.FLOAT: case Types.REAL: case Types.DOUBLE: break; case Types.NUMERIC: case Types.DECIMAL: pw.print(", decimalDigits="); pw.print(getDecimalDigits()); pw.print(", numPrecRadix="); pw.print(getNumPrecRadix()); break; case Types.CHAR: case Types.VARCHAR: pw.print(", charOctetLength="); pw.print(getCharOctetLength()); break; case Types.LONGVARCHAR: case Types.DATE: case Types.TIME: case Types.TIMESTAMP: case Types.BINARY: case Types.VARBINARY: case Types.LONGVARBINARY: default: break; } pw.print(", isNullable="); pw.print(isNullable()); if (hasUsage()) { pw.print(" Usages ["); for (Usage usage : getUsages()) { pw.print('('); usage.print(pw, prefix); pw.print(')'); } pw.println("]"); } } } /** Name of table. */ private final String name; /** Map from column name to column. */ private Map<String, Column> columnMap; /** Sum of all of the table's column's column sizes. */ private int totalColumnSize; /** * Whether the table is a fact, aggregate or other table type. * Note: this assumes that a table has only ONE usage. */ private TableUsageType tableUsageType; /** * Typical table types are: "TABLE", "VIEW", "SYSTEM TABLE", * "GLOBAL TEMPORARY", "LOCAL TEMPORARY", "ALIAS", "SYNONYM". * (Depends what comes out of JDBC.) */ private final String tableType; // mondriandef stuff public MondrianDef.Table table; private boolean allColumnsLoaded; private Table(final String name, String tableType) { this.name = name; this.tableUsageType = TableUsageType.UNKNOWN; this.tableType = tableType; } public void load() throws SQLException { loadColumns(); } /** * Returns the name of the table. */ public String getName() { return name; } /** * Returns the total size of a row (sum of the column sizes). */ public int getTotalColumnSize() { return totalColumnSize; } /** * Returns the number of rows in the table. */ public int getNumberOfRows() { return -1; } /** * Returns the collection of columns in this Table. */ public Collection<Column> getColumns() { return getColumnMap().values(); } /** * Returns an iterator over all column usages of a given type. */ public Iterator<JdbcSchema.Table.Column.Usage> getColumnUsages( final UsageType usageType) { class CTIterator implements Iterator<JdbcSchema.Table.Column.Usage> { private final Iterator<Column> columnIter; private final UsageType columnType; private Iterator<JdbcSchema.Table.Column.Usage> usageIter; private JdbcSchema.Table.Column.Usage nextObject; CTIterator(Collection<Column> columns, UsageType columnType) { this.columnIter = columns.iterator(); this.columnType = columnType; } public boolean hasNext() { while (true) { while ((usageIter == null) || ! usageIter.hasNext()) { if (! columnIter.hasNext()) { nextObject = null; return false; } Column c = columnIter.next(); usageIter = c.getUsages().iterator(); } JdbcSchema.Table.Column.Usage usage = usageIter.next(); if (usage.getUsageType() == columnType) { nextObject = usage; return true; } } } public JdbcSchema.Table.Column.Usage next() { return nextObject; } public void remove() { usageIter.remove(); } } return new CTIterator(getColumns(), usageType); } /** * Returns a column by its name. */ public Column getColumn(final String columnName) { return getColumnMap().get(columnName); } /** * Return true if this table contains a column with the given name. */ public boolean constainsColumn(final String columnName) { return getColumnMap().containsKey(columnName); } /** * Sets the table usage (fact, aggregate or other). * * @param tableUsageType */ public void setTableUsageType(final TableUsageType tableUsageType) { // if usageIter has already been set, then usageIter can NOT be // reset if ((this.tableUsageType != TableUsageType.UNKNOWN) && (this.tableUsageType != tableUsageType)) { throw mres.AttemptToChangeTableUsage.ex( getName(), this.tableUsageType.name(), tableUsageType.name()); } this.tableUsageType = tableUsageType; } /** * Returns the table's usage type. */ public TableUsageType getTableUsageType() { return tableUsageType; } /** * Returns the table's type. */ public String getTableType() { return tableType; } public String toString() { StringWriter sw = new StringWriter(256); PrintWriter pw = new PrintWriter(sw); print(pw, ""); pw.flush(); return sw.toString(); } public void print(final PrintWriter pw, final String prefix) { pw.print(prefix); pw.println("Table:"); String subprefix = prefix + " "; String subsubprefix = subprefix + " "; pw.print(subprefix); pw.print("name="); pw.print(getName()); pw.print(", type="); pw.print(getTableType()); pw.print(", usage="); pw.println(getTableUsageType().name()); pw.print(subprefix); pw.print("totalColumnSize="); pw.println(getTotalColumnSize()); pw.print(subprefix); pw.println("Columns: ["); for (Column column : getColumnMap().values()) { column.print(pw, subsubprefix); pw.println(); } pw.print(subprefix); pw.println("]"); } /** * Returns all of the columnIter associated with a table and creates * Column objects with the column's name, type, type name and column * size. * * @throws SQLException */ private void loadColumns() throws SQLException { if (! allColumnsLoaded) { Connection conn = getDataSource().getConnection(); try { DatabaseMetaData dmd = conn.getMetaData(); String schema = JdbcSchema.this.getSchemaName(); String catalog = JdbcSchema.this.getCatalogName(); String tableName = getName(); String columnNamePattern = "%"; ResultSet rs = null; try { Map<String, Column> map = getColumnMap(); rs = dmd.getColumns( catalog, schema, tableName, columnNamePattern); while (rs.next()) { String name = rs.getString(4); int type = rs.getInt(5); String typeName = rs.getString(6); int columnSize = rs.getInt(7); int decimalDigits = rs.getInt(9); int numPrecRadix = rs.getInt(10); int charOctetLength = rs.getInt(16); String isNullable = rs.getString(18); Column column = new Column(name); column.setType(type); column.setTypeName(typeName); column.setColumnSize(columnSize); column.setDecimalDigits(decimalDigits); column.setNumPrecRadix(numPrecRadix); column.setCharOctetLength(charOctetLength); column.setIsNullable(!"NO".equals(isNullable)); map.put(name, column); totalColumnSize += column.getColumnSize(); } } finally { if (rs != null) { rs.close(); } } } finally { try { conn.close(); } catch (SQLException e) { //ignore } } allColumnsLoaded = true; } } private Map<String, Column> getColumnMap() { if (columnMap == null) { columnMap = new HashMap<String, Column>(); } return columnMap; } } private DataSource dataSource; private String schema; private String catalog; private boolean allTablesLoaded; /** * Tables by name. We use a sorted map so {@link #getTables()}'s output * is in deterministic order. */ private final SortedMap<String, Table> tables = new TreeMap<String, Table>(); JdbcSchema(final DataSource dataSource) { this.dataSource = dataSource; } /** * This forces the tables to be loaded. * * @throws SQLException */ public void load() throws SQLException { loadTables(); } protected void clear() { // keep the DataSource, clear/reset everything else allTablesLoaded = false; schema = null; catalog = null; tables.clear(); } protected void remove() { // set ALL instance variables to null clear(); dataSource = null; } /** * Used for testing allowing one to load tables and their columnIter * from more than one datasource */ void resetAllTablesLoaded() { allTablesLoaded = false; } public DataSource getDataSource() { return dataSource; } protected void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } /** * Sets the database's schema name. * * @param schema Schema name */ public void setSchemaName(final String schema) { this.schema = schema; } /** * Returns the database's schema name. */ public String getSchemaName() { return schema; } /** * Sets the database's catalog name. */ public void setCatalogName(final String catalog) { this.catalog = catalog; } /** * Returns the database's catalog name. */ public String getCatalogName() { return catalog; } /** * Returns the database's tables. The collection is sorted by table name. */ public synchronized Collection<Table> getTables() { return getTablesMap().values(); } /** * Gets a table by name. */ public synchronized Table getTable(final String tableName) { return getTablesMap().get(tableName); } public String toString() { StringWriter sw = new StringWriter(256); PrintWriter pw = new PrintWriter(sw); print(pw, ""); pw.flush(); return sw.toString(); } public void print(final PrintWriter pw, final String prefix) { pw.print(prefix); pw.println("JdbcSchema:"); String subprefix = prefix + " "; String subsubprefix = subprefix + " "; pw.print(subprefix); pw.println("Tables: ["); for (Table table : getTablesMap().values()) { table.print(pw, subsubprefix); } pw.print(subprefix); pw.println("]"); } /** * Gets all of the tables (and views) in the database. * If called a second time, this method is a no-op. * * @throws SQLException */ private void loadTables() throws SQLException { if (allTablesLoaded) { return; } Connection conn = null; try { conn = getDataSource().getConnection(); final DatabaseMetaData databaseMetaData = conn.getMetaData(); String[] tableTypes = { "TABLE", "VIEW" }; if (databaseMetaData.getDatabaseProductName().toUpperCase() .contains("VERTICA")) { for (String tableType : tableTypes) { loadTablesOfType(databaseMetaData, new String[]{tableType}); } } else { loadTablesOfType(databaseMetaData, tableTypes); } allTablesLoaded = true; } finally { if (conn != null) { conn.close(); } } } /** * Loads definition of tables of a given set of table types ("TABLE", "VIEW" * etc.) */ private void loadTablesOfType( DatabaseMetaData databaseMetaData, String[] tableTypes) throws SQLException { final String schema = getSchemaName(); final String catalog = getCatalogName(); final String tableName = "%"; ResultSet rs = null; try { rs = databaseMetaData.getTables( catalog, schema, tableName, tableTypes); if (rs == null) { getLogger().debug("ERROR: rs == null"); return; } while (rs.next()) { addTable(rs); } } finally { if (rs != null) { rs.close(); } } } /** * Makes a Table from an ResultSet: the table's name is the ResultSet third * entry. * * @param rs Result set * @throws SQLException */ protected void addTable(final ResultSet rs) throws SQLException { String name = rs.getString(3); String tableType = rs.getString(4); Table table = new Table(name, tableType); tables.put(table.getName(), table); } private SortedMap<String, Table> getTablesMap() { return tables; } public static synchronized void clearAllDBs() { factory = null; makeFactory(); } } // End JdbcSchema.java
package ch.unizh.ini.caviar.graphics; import ch.unizh.ini.caviar.*; import ch.unizh.ini.caviar.aemonitor.*; import ch.unizh.ini.caviar.aesequencer.*; import ch.unizh.ini.caviar.biasgen.*; import ch.unizh.ini.caviar.chip.*; //import ch.unizh.ini.caviar.chip.convolution.Conv64NoNegativeEvents; import ch.unizh.ini.caviar.chip.retina.*; import ch.unizh.ini.caviar.event.*; import ch.unizh.ini.caviar.eventio.*; import ch.unizh.ini.caviar.eventprocessing.EventFilter; import ch.unizh.ini.caviar.eventprocessing.EventFilter2D; import ch.unizh.ini.caviar.eventprocessing.FilterChain; import ch.unizh.ini.caviar.eventprocessing.FilterFrame; import ch.unizh.ini.caviar.hardwareinterface.*; import ch.unizh.ini.caviar.hardwareinterface.usb.*; import ch.unizh.ini.caviar.util.*; import ch.unizh.ini.caviar.util.browser.*; import java.awt.*; import java.awt.datatransfer.*; import java.awt.dnd.*; import java.awt.event.*; import java.awt.image.*; import java.beans.*; import java.beans.PropertyChangeListener; import java.io.*; import java.lang.reflect.*; import java.util.*; import java.util.logging.*; import java.util.prefs.*; import javax.imageio.*; import javax.swing.*; import javax.swing.filechooser.FileFilter; import spread.*; /** * This is the main jAER interface to the user. The main event loop "ViewLoop" is here; see ViewLoop.run(). AEViewer shows AE chip live view and allows for controlling view and recording and playing back events from files and network connections. <p> AEViewer supports PropertyChangeListener's and fires PropertyChangeEvents on the following events: <ul> <li> "playmode" - when the player mode changes, e.g. from PlayMode.LIVE to PlayMode.PLAYBACK. The old and new values are the old and new PlayMode values <li> "fileopen" - when a new file is opened; old=null, new=file. <li> "stopme" - when stopme is called; old=new=null. </ul> In addition, when A5EViewer is in PLAYBACK PlayMode, users can register as PropertyChangeListeners on the AEFileInputStream for rewind events, etc. * * @author tobi */ public class AEViewer extends javax.swing.JFrame implements PropertyChangeListener, DropTargetListener { public static String HELP_URL_USER_GUIDE = "http://jaer.wiki.sourceforge.net"; public static String HELP_URL_RETINA = "http://siliconretina.ini.uzh.ch"; public static String HELP_URL_JAVADOC_WEB = "http://jaer.sourceforge.net/javadoc"; public static String HELP_URL_JAVADOC; static { String curDir = System.getProperty("user.dir"); HELP_URL_JAVADOC = "file://" + curDir + "/dist/javadoc/index.html"; // System.out.println("HELP_URL_JAVADOC="+HELP_URL_JAVADOC); } public static String HELP_URL_USER_GUIDE_USB2_MINI; static { String curDir = System.getProperty("user.dir"); File f = new File(curDir); File pf = f.getParentFile().getParentFile(); HELP_URL_USER_GUIDE_USB2_MINI = "file://" + pf.getPath() + "/doc/USBAERmini2userguide.pdf"; } public static String HELP_URL_USER_GUIDE_AER_CABLING; static { String curDir = System.getProperty("user.dir"); File f = new File(curDir); File pf = f.getParentFile().getParentFile(); HELP_URL_USER_GUIDE_AER_CABLING = "file://" + pf.getPath() + "/doc/AER Hardware and cabling.pdf"; } /** Modes of viewing: WAITING means waiting for device or for playback or remote, LIVE means showing a hardware interface, PLAYBACK means playing * back a recorded file, SEQUENCING means sequencing a file out on a sequencer device, REMOTE means playing a remote stream of AEs */ public enum PlayMode { WAITING, LIVE, PLAYBACK, SEQUENCING, REMOTE } volatile private PlayMode playMode = PlayMode.WAITING; static Preferences prefs = Preferences.userNodeForPackage(AEViewer.class); Logger log = Logger.getLogger("AEViewer"); private PropertyChangeSupport support = new PropertyChangeSupport(this); EventExtractor2D extractor = null; BiasgenFrame biasgenFrame = null; Biasgen biasgen = null; EventFilter2D filter1 = null, filter2 = null; AEChipRenderer renderer = null; AEMonitorInterface aemon = null; private ViewLoop viewLoop = null; FilterChain filterChain = null; FilterFrame filterFrame = null; RecentFiles recentFiles = null; File lastFile = null; public File lastLoggingFolder = null;//changed pol File lastImageFile = null; File currentFile = null; FrameRater frameRater = new FrameRater(); ChipCanvas chipCanvas; volatile boolean loggingEnabled = false; /** The date formatter used by AEViewer for logged data files */ File loggingFile; AEFileOutputStream loggingOutputStream; private boolean activeRenderingEnabled = prefs.getBoolean("AEViewer.activeRenderingEnabled", true); private boolean openGLRenderingEnabled = prefs.getBoolean("AEViewer.openGLRenderingEnabled", true); private boolean renderBlankFramesEnabled = prefs.getBoolean("AEViewer.renderBlankFramesEnabled", false); // number of packets to skip over rendering, used to speed up real time processing private int skipPacketsRenderingNumber = prefs.getInt("AEViewer.skipPacketsRenderingNumber", 0); int skipPacketsRenderingCount = 0; // render first packet always DropTarget dropTarget; File draggedFile; private boolean loggingPlaybackImmediatelyEnabled = prefs.getBoolean("AEViewer.loggingPlaybackImmediatelyEnabled", false); private boolean enableFiltersOnStartup = prefs.getBoolean("AEViewer.enableFiltersOnStartup", true); private long loggingTimeLimit = 0, loggingStartTime = System.currentTimeMillis(); private boolean stereoModeEnabled = false; private boolean logFilteredEventsEnabled = prefs.getBoolean("AEViewer.logFilteredEventsEnabled", false); private DynamicFontSizeJLabel statisticsLabel; private boolean filterFrameBuilt = false; // flag to signal that the frame should be rebuilt when initially shown or when chip is changed private AEChip chip; public static String DEFAULT_CHIP_CLASS = Tmpdiff128.class.getName(); private String aeChipClassName = prefs.get("AEViewer.aeChipClassName", DEFAULT_CHIP_CLASS); Class aeChipClass; // WindowSaver windowSaver; private JAERViewer jaerViewer; // multicast connections private AEMulticastInput aeMulticastInput = null; private AEMulticastOutput aeMulticastOutput = null; private boolean multicastInputEnabled = false, multicastOutputEnabled = false; // unicast dataqgram data xfer private volatile AEUnicastOutput unicastOutput = null; private volatile AEUnicastInput unicastInput = null; private boolean unicastInputEnabled = false, unicastOutputEnabled = false; // socket connections private volatile AEServerSocket aeServerSocket = null; // this server socket accepts connections from clients who want events from us private volatile AESocket aeSocket = null; // this socket is used to get events from a server to us private boolean socketInputEnabled = false; // flags that we are using socket input stream // Spread connections private volatile AESpreadInterface spreadInterface = null; private boolean spreadOutputEnabled = false, spreadInputEnabled = false; /** * construct new instance and then set classname of device to show in it * * @param jaerViewer the manager of all viewers */ public AEViewer(JAERViewer jaerViewer) { setLocale(Locale.US); // to avoid problems with other language support in JOGL // try { // UIManager.setLookAndFeel(new WindowsLookAndFeel()); // } catch (Exception e) { // log.warning(e.getMessage()); setName("AEViewer"); initComponents(); this.jaerViewer = jaerViewer; if (jaerViewer != null) { jaerViewer.addViewer(this); } statisticsLabel = new DynamicFontSizeJLabel(); statisticsLabel.setToolTipText("Time slice/Absolute time, NumEvents/NumFiltered, events/sec, Frame rate acheived/desired, Time expansion X contraction /, delay after frame, color scale"); statisticsPanel.add(statisticsLabel); int n = menuBar.getMenuCount(); for (int i = 0; i < n; i++) { JMenu m = menuBar.getMenu(i); m.getPopupMenu().setLightWeightPopupEnabled(false); } filtersSubMenu.getPopupMenu().setLightWeightPopupEnabled(false); // otherwise can't see on canvas graphicsSubMenu.getPopupMenu().setLightWeightPopupEnabled(false); remoteMenu.getPopupMenu().setLightWeightPopupEnabled(false); // make remote submenu heavy to show over glcanvas String lastFilePath = prefs.get("AEViewer.lastFile", ""); lastFile = new File(lastFilePath); String defaultLoggingFolderName = System.getProperty("user.dir"); // lastLoggingFolder starts off at user.dir which is startup folder "host/java" where .exe launcher lives lastLoggingFolder = new File(prefs.get("AEViewer.lastLoggingFolder", defaultLoggingFolderName)); // check lastLoggingFolder to see if it really exists, if not, default to user.dir if (!lastLoggingFolder.exists() || !lastLoggingFolder.isDirectory()) { log.warning("lastLoggingFolder " + lastLoggingFolder + " no good, defaulting to " + defaultLoggingFolderName); lastLoggingFolder = new File(defaultLoggingFolderName); } // recent files tracks recently used files *and* folders. recentFiles adds the anonymous listener // built here to open the selected file recentFiles = new RecentFiles(prefs, fileMenu, new ActionListener() { public void actionPerformed(ActionEvent evt) { File f = new File(evt.getActionCommand()); // log.info("opening "+evt.getActionCommand()); try { if (f != null && f.isFile()) { getAePlayer().startPlayback(f); recentFiles.addFile(f); } else if (f != null && f.isDirectory()) { prefs.put("AEViewer.lastFile", f.getCanonicalPath()); aePlayer.openAEInputFileDialog(); recentFiles.addFile(f); } } catch (Exception fnf) { fnf.printStackTrace(); // exceptionOccurred(fnf,this); recentFiles.removeFile(f); } } }); buildDeviceMenu(); // we need to do this after building device menu so that proper menu item radio button can be selected setAeChipClass(getAeChipClass()); // set default device - last chosen playerControlPanel.setVisible(false); pack(); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { if (aemon != null && aemon.isOpen()) { aemon.close(); } } }); setFocusable(true); requestFocus(); viewLoop = new ViewLoop(); viewLoop.start(); dropTarget = new DropTarget(imagePanel, this); fixLoggingControls(); buildInterfaceMenu(); // init menu items that are checkboxes to correct initial state viewActiveRenderingEnabledMenuItem.setSelected(isActiveRenderingEnabled()); viewOpenGLEnabledMenuItem.setSelected(isOpenGLRenderingEnabled()); loggingPlaybackImmediatelyCheckBoxMenuItem.setSelected(isLoggingPlaybackImmediatelyEnabled()); subsampleEnabledCheckBoxMenuItem.setSelected(chip.isSubSamplingEnabled()); acccumulateImageEnabledCheckBoxMenuItem.setSelected(renderer.isAccumulateEnabled()); autoscaleContrastEnabledCheckBoxMenuItem.setSelected(renderer.isAutoscaleEnabled()); pauseRenderingCheckBoxMenuItem.setSelected(isPaused()); viewRenderBlankFramesCheckBoxMenuItem.setSelected(isRenderBlankFramesEnabled()); logFilteredEventsCheckBoxMenuItem.setSelected(logFilteredEventsEnabled); enableFiltersOnStartupCheckBoxMenuItem.setSelected(enableFiltersOnStartup); fixSkipPacketsRenderingMenuItems(); if (jaerViewer != null) { electricalSyncEnabledCheckBoxMenuItem.setSelected(jaerViewer.isElectricalSyncEnabled()); } openHardwareIfNonambiguous(); // start the server thread for incoming socket connections for remote consumers of events if (aeServerSocket == null) { try { aeServerSocket = new AEServerSocket(); aeServerSocket.start(); } catch (IOException ex) { log.warning(ex.toString() + ": While constructing AEServerSocket. Another viewer or process has already bound this port or some other error. This viewer will not have a server socket for AE data."); aeServerSocket = null; } } } private boolean isWindows() { String osName = System.getProperty("os.name"); if (osName.startsWith("Windows")) { return true; } else { return false; } } void openHardwareIfNonambiguous() { // if we are are the only viewer, automatically set // interface to the hardware interface if there is only 1 of them and there is not already // a hardware inteface (e.g. StereoHardwareInterface which consists of // two interfaces). otherwise force user choice if (jaerViewer != null && jaerViewer.getViewers().size() == 1 && chip.getHardwareInterface() == null && HardwareInterfaceFactory.instance().getNumInterfacesAvailable() == 1) { // log.info("opening unambiguous device"); chip.setHardwareInterface(HardwareInterfaceFactory.instance().getFirstAvailableInterface()); } } private ArrayList<String> chipClassNames; private ArrayList<Class> chipClasses; @SuppressWarnings("unchecked") void getChipClassPrefs() { // Deserialize from a byte array try { byte[] bytes = prefs.getByteArray("chipClassNames", null); if (bytes != null) { ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes)); chipClassNames = (ArrayList<String>) in.readObject(); in.close(); } else { makeDefaultChipClassNames(); } } catch (Exception e) { makeDefaultChipClassNames(); } } private void makeDefaultChipClassNames() { chipClassNames = SubclassFinder.findSubclassesOf(AEChip.class.getName()); // chipClassNames=new ArrayList<String>(AEChip.CHIP_CLASSSES.length); // for(int i=0;i<AEChip.CHIP_CLASSSES.length;i++){ // chipClassNames.add(AEChip.CHIP_CLASSSES[i].getCanonicalName()); } private void putChipClassPrefs() { try { // Serialize to a byte array ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(bos); out.writeObject(chipClassNames); out.close(); // Get the bytes of the serialized object byte[] buf = bos.toByteArray(); prefs.putByteArray("chipClassNames", buf); } catch (IOException e) { e.printStackTrace(); } catch (IllegalArgumentException e2) { log.warning("too many classes in Preferences, " + chipClassNames.size() + " class names"); } } private static class FastClassFinder { static HashMap<String, Class> map = new HashMap<String, Class>(); private static Class forName(String name) throws ClassNotFoundException { Class c = null; if ((c = map.get(name)) == null) { c = Class.forName(name); map.put(name, c); return c; } else { return c; } } } private void buildDeviceMenu() { ButtonGroup deviceGroup = new ButtonGroup(); deviceMenu.removeAll(); chipClasses = new ArrayList<Class>(); deviceMenu.addSeparator(); deviceMenu.add(customizeDevicesMenuItem); getChipClassPrefs(); for (String deviceClassName : chipClassNames) { try { Class c = FastClassFinder.forName(deviceClassName); chipClasses.add(c); JRadioButtonMenuItem b = new JRadioButtonMenuItem(deviceClassName); deviceMenu.insert(b, deviceMenu.getItemCount() - 2); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { try { String name = evt.getActionCommand(); Class cl = FastClassFinder.forName(name); setAeChipClass(cl); } catch (Exception e) { e.printStackTrace(); } } }); deviceGroup.add(b); } catch (ClassNotFoundException e) { log.warning(e.getMessage()); } } } public void zeroTimestamps() { if (aemon != null && aemon.isOpen()) { aemon.resetTimestamps(); } } public Class getAeChipClass() { if (aeChipClass == null) { // log.warning("AEViewer.getAeChipClass(): null aeChipClass, initializing to default "+aeChipClassName); try { // log.info("getting class for "+aeChipClassName); aeChipClass = FastClassFinder.forName(aeChipClassName); // throws exception if class not found if (java.lang.reflect.Modifier.isAbstract(aeChipClass.getModifiers())) { log.warning(aeChipClass + " is abstract, setting chip class to default " + DEFAULT_CHIP_CLASS); aeChipClassName = DEFAULT_CHIP_CLASS; aeChipClass = aeChipClass = FastClassFinder.forName(aeChipClassName); } } catch (Exception e) { log.warning(aeChipClassName + " class not found, setting preferred chip class to default " + DEFAULT_CHIP_CLASS); prefs.put("AEViewer.aeChipClassName", DEFAULT_CHIP_CLASS); System.exit(1); } } return aeChipClass; } /** this sets window title according to actual state */ public void setTitleAccordingToState() { String ts = null; switch (getPlayMode()) { case LIVE: ts = getAeChipClass().getSimpleName() + " " + aemon + " LIVE"; break; case PLAYBACK: ts = currentFile.getName() + " PLAYING"; break; case WAITING: ts = "AEViewer - WAITING"; break; case SEQUENCING: ts = getAeChipClass().getSimpleName() + " " + aemon + " LIVE SEQUENCE-MONITOR"; break; case REMOTE: ts = "REMOTE"; break; default: ts = "Unknown state"; } setTitle(ts); } /** sets the device class, e.g. Tmpdiff128, from the fully qual classname provided by the menu item itself * @param deviceClass the Class of the AEChip to add to the AEChip menu */ public void setAeChipClass(Class deviceClass) { // log.infox("AEViewer.setAeChipClass("+deviceClass+")"); try { if (filterFrame != null) { filterFrame.dispose(); filterFrame = null; } filterFrameBuilt = false; filtersToggleButton.setVisible(false); viewFiltersMenuItem.setEnabled(false); showBiasgen(false); Constructor<AEChip> constructor = deviceClass.getConstructor(); if (constructor == null) { log.warning("null chip constructer, need to select valid chip class"); return; } if (getChip() == null) { // handle initial case constructChip(constructor); } else { synchronized (chip) { // handle live case -- this is not ideal thread programming - better to sync on a lock object in the run loop synchronized (extractor) { synchronized (renderer) { constructChip(constructor); } } } } if (chip == null) { log.warning("null chip, not continuing"); return; } aeChipClass = deviceClass; prefs.put("AEViewer.aeChipClassName", aeChipClass.getName()); // begin added by Philipp // if (aeChipClass.renderer instanceof AdaptiveIntensityRenderer){ // that does not work since the renderer is obviously not defined before a chip gets instanciated if (aeChipClass.getName().equals("ch.unizh.ini.caviar.chip.foveated.UioFoveatedImager") || aeChipClass.getName().equals("ch.unizh.ini.caviar.chip.staticbiovis.UioStaticBioVis")) { calibrationStartStop.setVisible(true); calibrationStartStop.setEnabled(true); } else { calibrationStartStop.setVisible(false); calibrationStartStop.setEnabled(false); } // end added by Philipp if (aemon != null) { // force reopen aemon.close(); } makeCanvas(); setTitleAccordingToState(); Component[] devMenuComps = deviceMenu.getMenuComponents(); for (int i = 0; i < devMenuComps.length; i++) { if (devMenuComps[i] instanceof JRadioButtonMenuItem) { JMenuItem item = (JRadioButtonMenuItem) devMenuComps[i]; if (item.getActionCommand().equals(aeChipClass.getName())) { item.setSelected(true); break; } } } fixLoggingControls(); filterChain = chip.getFilterChain(); if (filterChain == null) { filtersToggleButton.setVisible(false); viewFiltersMenuItem.setEnabled(false); } else { filterChain.reset(); filtersToggleButton.setVisible(true); viewFiltersMenuItem.setEnabled(true); } HardwareInterface hw = chip.getHardwareInterface(); if (hw != null) { log.warning("setting hardware interface of " + chip + " to " + hw); aemon = (AEMonitorInterface) hw; } showFilters(enableFiltersOnStartup); // fix selected radio button for chip class if (deviceMenu.getItemCount() == 0) { log.warning("tried to select device in menu but no device menu has been built yet"); } for (int i = 0; i < deviceMenu.getItemCount(); i++) { JMenuItem m = deviceMenu.getItem(i); if (m != null && m instanceof JRadioButtonMenuItem && m.getText() == aeChipClass.getName()) { m.setSelected(true); break; } } } catch (Exception e) { e.printStackTrace(); } } private void constructChip(Constructor<AEChip> constructor) { try { // System.out.println("AEViewer.constructChip(): constructing chip with constructor "+constructor); setChip(constructor.newInstance((java.lang.Object[]) null)); extractor = chip.getEventExtractor(); renderer = chip.getRenderer(); extractor.setSubsamplingEnabled(subsampleEnabledCheckBoxMenuItem.isSelected()); extractor.setSubsampleThresholdEventCount(renderer.getSubsampleThresholdEventCount()); // awkward connection between components here - ideally chip should contrain info about subsample limit if (chip.getBiasgen() != null && !chip.getBiasgen().isInitialized()) { chip.getBiasgen().showUnitializedBiasesWarningDialog(this); } getChip().setAeViewer(this); } catch (Exception e) { log.warning("AEViewer.constructChip exception " + e.getMessage()); e.printStackTrace(); } } synchronized void makeCanvas() { if (chipCanvas != null) { imagePanel.remove(chipCanvas.getCanvas()); } if (chip == null) { log.warning("null chip, not making canvas"); return; } chipCanvas = chip.getCanvas(); chipCanvas.setOpenGLEnabled(isOpenGLRenderingEnabled()); imagePanel.add(chipCanvas.getCanvas()); chipCanvas.getCanvas().invalidate(); // find display menu reference and fill it with display menu for this canvas viewMenu.remove(displayMethodMenu); viewMenu.add(chipCanvas.getDisplayMethodMenu()); displayMethodMenu = chipCanvas.getDisplayMethodMenu(); viewMenu.invalidate(); validate(); pack(); // causes a lot of flashing ... Toolkit.getDefaultToolkit().setDynamicLayout(true); // dynamic resizing -- see if this bombs! } /** This method sets the "current file" which sets the field, the preferences of the last file, and the window title. It does not actually start playing the file. @see AEViewer.AEPlayer */ protected void setCurrentFile(File f) { currentFile = new File(f.getPath()); lastFile = currentFile; prefs.put("AEViewer.lastFile", lastFile.toString()); // System.out.println("put AEViewer.lastFile="+lastFile); setTitleAccordingToState(); } /** If the AEViewer is playing (or has played) a file, then this method returns it. @return the File @see PlayMode */ public File getCurrentFile() { return currentFile; } FileInputStream fileInputStream; /** writes frames and frame sequences for video making using, e.g. adobe premiere */ class CanvasFileWriter { boolean writingMovieEnabled = false; Canvas canvas; int frameNumber = 0; java.io.File sequenceDir; String sequenceName = "sequence"; int snapshotNumber = 0; // this is appended automatically to single snapshot filenames String snapshotName = "snapshot"; String getFilename() { return sequenceName + String.format("%04d.png", frameNumber); } synchronized void startWritingMovie() { // if(isOpenGLRenderingEnabled()){ // JOptionPane.showMessageDialog(AEViewer.this,"Disable OpenGL graphics from the View menu first"); // return; if (!isActiveRenderingEnabled()) { JOptionPane.showMessageDialog(AEViewer.this, "Active rendering will be enabled for movie writing"); setActiveRenderingEnabled(true); viewActiveRenderingEnabledMenuItem.setSelected(true); } String homeDir = System.getProperty("user.dir"); // the program startup folder // System.getenv("USERPROFILE"); // returns documents and setttings\tobi, not my documents sequenceName = JOptionPane.showInputDialog("<html>Sequence name?<br>This folder will be created in the directory<br> " + homeDir + "</html>"); if (sequenceName == null || sequenceName.equals("")) { log.info("canceled image sequence"); return; } log.info("creating directory " + homeDir + File.separator + sequenceName); sequenceDir = new File(homeDir + File.separator + sequenceName); if (sequenceDir.exists()) { JOptionPane.showMessageDialog(AEViewer.this, sequenceName + " already exists"); return; } boolean madeit = sequenceDir.mkdir(); if (!madeit) { JOptionPane.showMessageDialog(AEViewer.this, "couldn't create directory " + sequenceName); return; } frameNumber = 0; writingMovieEnabled = true; } synchronized void stopWritingMovie() { writingMovieEnabled = false; openLoggingFolderWindow(); } synchronized void writeMovieFrame() { try { Container container = getContentPane(); canvas = chip.getCanvas().getCanvas(); Rectangle r = canvas.getBounds(); Image image = canvas.createImage(r.width, r.height); Graphics g = image.getGraphics(); synchronized (container) { container.paintComponents(g); if (!isOpenGLRenderingEnabled()) { chip.getCanvas().paint(g); ImageIO.write((RenderedImage) image, "png", new File(sequenceDir, getFilename())); } else if (chip.getCanvas().getImageOpenGL() != null) { ImageIO.write(chip.getCanvas().getImageOpenGL(), "png", new File(sequenceDir, getFilename())); } } frameNumber++; } catch (IOException ioe) { ioe.printStackTrace(); } } // /** Take an Image associated with a file, and wait until it is // * done loading. Just a simple application of MediaTracker. // * If you are loading multiple images, don't use this // * consecutive times; instead use the version that takes // * an array of images. // */ // boolean waitForImage(Image image, Component c) { // tracker.addImage(image, 0); // try { // tracker.waitForAll(); // } catch(InterruptedException ie) {} // return(!tracker.isErrorAny()); synchronized void writeSnapshotImage() { boolean wasPaused = isPaused(); setPaused(true); JFileChooser fileChooser = new JFileChooser(); String lastFilePath = prefs.get("AEViewer.lastFile", ""); // get the last folder lastFile = new File(lastFilePath); // fileChooser.setFileFilter(datFileFilter); PNGFileFilter indexFileFilter = new PNGFileFilter(); fileChooser.addChoosableFileFilter(indexFileFilter); fileChooser.setCurrentDirectory(lastFile); // sets the working directory of the chooser if (lastImageFile == null) { lastImageFile = new File("snapshot.png"); } fileChooser.setSelectedFile(lastImageFile); int retValue = fileChooser.showOpenDialog(AEViewer.this); if (retValue == JFileChooser.APPROVE_OPTION) { lastImageFile = fileChooser.getSelectedFile(); String suffix = ""; if (!lastImageFile.getName().endsWith(".png")) { suffix = ".png"; } try { // if(!isOpenGLRenderingEnabled()){ Container container = getContentPane(); Rectangle r = container.getBounds(); Image image = container.createImage(r.width, r.height); Graphics g = image.getGraphics(); synchronized (container) { container.paintComponents(g); g.translate(0, statisticsPanel.getHeight()); chip.getCanvas().paint(g); // ImageIO.write((RenderedImage)imageOpenGL, "png", new File(snapshotName+snapshotNumber+".png")); // log.info("writing image to file"); ImageIO.write((RenderedImage) image, "png", new File(lastImageFile.getPath() + suffix)); } // }else{ // open gl canvas snapshotNumber++; } catch (Exception e) { e.printStackTrace(); } } setPaused(wasPaused); } } // builds list of attached hardware interfaces by asking the hardware interface factory for the list synchronized void buildInterfaceMenu() { if (!isWindows()) { // TODO not really anymore with linux interface to retinas return; } // System.out.println("AEViewer.buildInterfaceMenu"); ButtonGroup bg = new ButtonGroup(); interfaceMenu.removeAll(); // make a 'none' item JRadioButtonMenuItem b = new JRadioButtonMenuItem("None"); b.putClientProperty("HardwareInterface", null); interfaceMenu.add(b); bg.add(b); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { // log.info("selected null interface"); if (chip.getHardwareInterface() != null) { chip.getHardwareInterface().close(); } chip.setHardwareInterface(null); } }); interfaceMenu.add(new JSeparator()); int n = HardwareInterfaceFactory.instance().getNumInterfacesAvailable(); for (int i = 0; i < n; i++) { HardwareInterface hw = HardwareInterfaceFactory.instance().getInterface(i); if (hw == null) { continue; } // in case it disappeared b = new JRadioButtonMenuItem(hw.toString()); b.putClientProperty("HardwareInterfaceNumber", new Integer(i)); interfaceMenu.add(b); bg.add(b); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { JComponent comp = (JComponent) evt.getSource(); int interfaceNumber = (Integer) comp.getClientProperty("HardwareInterfaceNumber"); HardwareInterface hw = HardwareInterfaceFactory.instance().getInterface(interfaceNumber); // HardwareInterface hw=(HardwareInterface)comp.getClientProperty("HardwareInterface"); log.info("selected interface " + evt.getActionCommand() + " with HardwareInterface number" + interfaceNumber + " which is " + hw); chip.setHardwareInterface(hw); } }); HardwareInterface chipInterface = chip.getHardwareInterface(); if (chipInterface != null) { // log.info("chip.getHardwareInterface="+chip.getHardwareInterface()); } if (hw != null) { // log.info("hw="+hw); } //check if device in menu is already one assigned to this chip, by String comparison. Checking by object doesn't work because if (chipInterface != null && hw != null && chipInterface.toString().equals(hw.toString())) { b.setSelected(true); } // if(chip!=null && chip.getHardwareInterface()==hw) b.setSelected(true); } } void fixBiasgenControls() { // // debug // biasesToggleButton.setEnabled(true); // biasesToggleButton.setVisible(true); // viewBiasesMenuItem.setEnabled(true); if (chip == null) { return; } if (chip.getBiasgen() == null) { biasesToggleButton.setEnabled(false); biasesToggleButton.setVisible(false); viewBiasesMenuItem.setEnabled(false); return; } else { biasesToggleButton.setEnabled(true); biasesToggleButton.setVisible(true); viewBiasesMenuItem.setEnabled(true); } if (biasgenFrame != null) { boolean vis = biasgenFrame.isVisible(); biasesToggleButton.setSelected(vis); } } // opens the AE interface and handles stereo mode if two identical AERetina interfaces void openAEMonitor() { if (aemon != null && aemon.isOpen()) { if (this.getPlayMode() != PlayMode.SEQUENCING) { setPlayMode(PlayMode.LIVE); } // playMode=PlayMode.LIVE; // in case (like StereoHardwareInterface) where device can be open but not by AEViewer return; } try { openHardwareIfNonambiguous(); // openHardwareIfNonambiguous will set chip's hardware interface, here we store local reference // if it's an aemon, then its an event monitor if (chip.getHardwareInterface() != null && chip.getHardwareInterface() instanceof AEMonitorInterface) { aemon = (AEMonitorInterface) chip.getHardwareInterface(); if (aemon == null || !(aemon instanceof AEMonitorInterface)) { fixDeviceControlMenuItems(); fixLoggingControls(); fixBiasgenControls(); return; } aemon.setChip(chip); aemon.open(); fixLoggingControls(); fixBiasgenControls(); tickUs = aemon.getTimestampTickUs(); // note it is important that this openAEMonitor succeeed BEFORE aemon is assigned to biasgen, which immeiately tries to openAEMonitor and download biases, creating a storm of complaints if not sucessful! if (aemon instanceof BiasgenHardwareInterface) { Biasgen biasgen = chip.getBiasgen(); if (biasgen == null) { log.warning(chip + " is BiasgenHardwareInterface but has null biasgen object, not setting biases"); } else { chip.getBiasgen().sendPotValues(chip.getBiasgen()); // chip.setHardwareInterface(aemon); // if we do this, events do not start coming again after reconnect of device // biasgen=chip.getBiasgen(); // if(biasgenFrame==null) { // biasgenFrame=new BiasgenFrame(biasgen); // should check if exists... } } if (chip.getHardwareInterface() != null && chip.getHardwareInterface() instanceof AESequencerInterface) { // the 'chip's' hardware interface is a pure sequencer enableMonSeqMenu(true); } if (this.getPlayMode() != PlayMode.SEQUENCING) { setPlayMode(PlayMode.LIVE); } } else if (chip.getHardwareInterface() != null && chip.getHardwareInterface() instanceof AESequencerInterface) { // the 'chip's' hardware interface is a pure sequencer enableMonSeqMenu(true); } setPlaybackControlsEnabledState(true); } catch (Exception e) { log.warning(e.getMessage()); if (aemon != null) { aemon.close(); } aemon = null; setPlaybackControlsEnabledState(false); fixDeviceControlMenuItems(); fixLoggingControls(); fixBiasgenControls(); setPlayMode(PlayMode.WAITING); } fixDeviceControlMenuItems(); } void setPlaybackControlsEnabledState(boolean yes) { loggingButton.setEnabled(yes); biasesToggleButton.setEnabled(yes); // filtersToggleButton.setEnabled(yes); } // volatile boolean stop=false; // volatile because multiple threads will access int renderCount = 0; int numEvents; AEPacketRaw aeRaw; // AEPacket2D ae; private EventPacket packet; // EventPacket packetFiltered; boolean skipRender = false; // volatile private boolean paused=false; // multiple threads will access boolean overrunOccurred = false; int tickUs = 1; public AEPlayer aePlayer = new AEPlayer(); int noEventCounter = 0; /** this class handles file input of AEs to control the number of events/sample or period of time in the sample, etc. *It handles the file input stream, opening a dialog box, etc. *It also handles synchronization of different viewers as follows: *<p> * If the viwer is not synchronized, then all calls from the GUI are passed directly to this instance of AEPlayer. Thus local control always happens. *<p> * If the viewer is sychronized, then all GUI calls pass instead to the CaviarViewer instance that contains (or started) this viewer. Then the CaviarViewer AEPlayer *calls all the viewers to take the player action (e.g. rewind, go to next slice, change direction). *<p> *Thus whichever controls the user uses to control playback, the viewers are all sychronized properly without recursively. The "master" is indicated by the GUI action, *which routes the request either to this instance's AEPlayer or to the CaviarViewer AEPlayer. */ public class AEPlayer implements AEFileInputStreamInterface, AEPlayerInterface { private boolean flexTimeEnabled = false; // true to play constant # of events private int samplePeriodUs = 20000; // ms/sample to shoot for private int sampleNumEvents = 256; boolean fileInputEnabled = false; AEFileInputStream fileAEInputStream = null; JFileChooser fileChooser; public boolean isChoosingFile() { return (fileChooser != null && fileChooser.isVisible()); } FileFilter lastFilter = null; /** called when user asks to open data file file dialog */ public void openAEInputFileDialog() { // try{Thread.currentThread().sleep(200);}catch(InterruptedException e){} float oldScale = chipCanvas.getScale(); fileChooser = new JFileChooser(); // new TypeAheadSelector(fileChooser); //com.sun.java.plaf.windows.WindowsFileChooserUI; // fileChooser.addKeyListener(new KeyAdapter() { // public void keyTyped(KeyEvent e){ // System.out.println("keycode="+e.getKeyCode()); // System.out.println("fileChooser.getUIClassID()="+fileChooser.getUIClassID()); // KeyListener[] keyListeners=fileChooser.getKeyListeners(); ChipDataFilePreview preview = new ChipDataFilePreview(fileChooser, chip); // from book swing hacks new FileDeleter(fileChooser, preview); fileChooser.addPropertyChangeListener(preview); fileChooser.setAccessory(preview); String lastFilePath = prefs.get("AEViewer.lastFile", ""); // get the last folder lastFile = new File(lastFilePath); // fileChooser.setFileFilter(datFileFilter); IndexFileFilter indexFileFilter = new IndexFileFilter(); fileChooser.addChoosableFileFilter(indexFileFilter); DATFileFilter datFileFilter = new DATFileFilter(); fileChooser.addChoosableFileFilter(datFileFilter); if (lastFilter == null) { fileChooser.setFileFilter(datFileFilter); } else { fileChooser.setFileFilter(lastFilter); } fileChooser.setCurrentDirectory(lastFile); // sets the working directory of the chooser // boolean wasPaused=isPaused(); setPaused(true); int retValue = fileChooser.showOpenDialog(AEViewer.this); if (retValue == JFileChooser.APPROVE_OPTION) { lastFilter = fileChooser.getFileFilter(); try { lastFile = fileChooser.getSelectedFile(); if (lastFile != null) { recentFiles.addFile(lastFile); } startPlayback(lastFile); } catch (FileNotFoundException fnf) { fnf.printStackTrace(); // exceptionOccurred(fnf,this); } } else { preview.showFile(null); // abort preview } fileChooser = null; chipCanvas.setScale(oldScale); // restore persistent scale so that we don't get tiny size on next startup setPaused(false); } public class FileDeleter extends KeyAdapter implements PropertyChangeListener { private JFileChooser chooser; private ChipDataFilePreview preview; File file = null; /** adds a keyreleased listener on the JFileChooser FilePane inner classes so that user can use Delete key to delete the file * that is presently being shown in the preview window * @param chooser the chooser * @param preview the data file preview */ public FileDeleter(JFileChooser chooser, ChipDataFilePreview preview) { this.chooser = chooser; this.preview = preview; chooser.addPropertyChangeListener(JFileChooser.SELECTED_FILE_CHANGED_PROPERTY, this); Component comp = addDeleteListener(chooser); } /** is called when the file selection is changed. Bound to the SELECTED_FILE_CHANGED_PROPERTY. */ public void propertyChange(PropertyChangeEvent evt) { // comes from chooser when new file is selected if (evt.getNewValue() instanceof File) { file = (File) evt.getNewValue(); } else { file = null; } } private Component addDeleteListener(Component comp) { // System.out.println(""); // System.out.println("comp="+comp); // if (comp.getClass() == sun.swing.FilePane.class) return comp; if (comp instanceof Container) { // System.out.println(comp+"\n"); // comp.addMouseListener(new MouseAdapter(){ // public void mouseEntered(MouseEvent e){ // System.out.println("mouse entered: "+e); // if this is a known filepane class, then add a key listener for deleting log files. // may need to remove this in future release of java and //find a portable way to detect we are in the FilePane if (comp.getClass().getEnclosingClass() == sun.swing.FilePane.class) { comp.addKeyListener(new KeyAdapter() { public void keyReleased(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_DELETE) { // System.out.println("delete key typed from "+e.getSource()); deleteFile(); } } }); } Component[] components = ((Container) comp).getComponents(); for (int i = 0; i < components.length; i++) { Component child = addDeleteListener(components[i]); if (child != null) { return child; } } } return null; } void deleteFile() { if (file == null) { return; } log.fine("trying to delete file " + file); preview.deleteCurrentFile(); } } /** Starts playback on the data file. If the file is an index file, the JAERViewer is called to start playback of the set of data files. Fires a property change event "fileopen", after playMode is changed to PLAYBACK. @param file the File to play */ synchronized public void startPlayback(File file) throws FileNotFoundException { if (file == null || !file.isFile()) { throw new FileNotFoundException("file not found: " + file); } if (IndexFileFilter.getExtension(file).equals("index")) { if (getJaerViewer() != null) { getJaerViewer().getPlayer().startPlayback(file); } return; } // System.out.println("AEViewer.starting playback for DAT file "+file); fileInputStream = new FileInputStream(file); setCurrentFile(file); fileAEInputStream = new AEFileInputStream(fileInputStream); fileAEInputStream.setNonMonotonicTimeExceptionsChecked(checkNonMonotonicTimeExceptionsEnabledCheckBoxMenuItem.isSelected()); fileAEInputStream.setFile(file); // so that users of the stream can get the file information if (getJaerViewer() != null && getJaerViewer().getViewers().size() == 1) { // if there is only one viewer, start it there try { fileAEInputStream.rewind(); } catch (IOException e) { e.printStackTrace(); } } // don't waste cycles grabbing events while playing back if (aemon != null && aemon.isOpen()) { try { if (getPlayMode().equals(getPlayMode().SEQUENCING)) { stopSequencing(); } else { aemon.setEventAcquisitionEnabled(false); } } catch (HardwareInterfaceException e) { e.printStackTrace(); } } fileAEInputStream.getSupport().addPropertyChangeListener(AEViewer.this); closeMenuItem.setEnabled(true); increasePlaybackSpeedMenuItem.setEnabled(true); decreasePlaybackSpeedMenuItem.setEnabled(true); rewindPlaybackMenuItem.setEnabled(true); flextimePlaybackEnabledCheckBoxMenuItem.setEnabled(true); togglePlaybackDirectionMenuItem.setEnabled(true); toggleMarkCheckBoxMenuItem.setEnabled(true); if (!playerControlPanel.isVisible()) { playerControlPanel.setVisible(true); } setPlayMode(PlayMode.PLAYBACK); // the aeviewer runloop thread will see this soon after and start trying to play file fixLoggingControls(); getSupport().firePropertyChange("fileopen", null, file); } /** stops playback. *If not in PLAYBACK mode, then just returns. *If playing back, could be waiting during sleep or during CyclicBarrier.await call in CaviarViewer. In case this is the case, we send *an interrupt to the the ViewLoop thread to stop this waiting. */ public void stopPlayback() { if (getPlayMode() != PlayMode.PLAYBACK) { return; } if (aemon != null && aemon.isOpen()) { try { aemon.setEventAcquisitionEnabled(true); } catch (HardwareInterfaceException e) { setPlayMode(PlayMode.WAITING); e.printStackTrace(); } setPlayMode(PlayMode.LIVE); } else { setPlayMode(PlayMode.WAITING); } playerControlPanel.setVisible(false); // closeMenuItem.setEnabled(false); toggleMarkCheckBoxMenuItem.setEnabled(false); increasePlaybackSpeedMenuItem.setEnabled(false); decreasePlaybackSpeedMenuItem.setEnabled(false); rewindPlaybackMenuItem.setEnabled(false); flextimePlaybackEnabledCheckBoxMenuItem.setEnabled(false); togglePlaybackDirectionMenuItem.setEnabled(false); toggleMarkCheckBoxMenuItem.setEnabled(false); try { if (fileAEInputStream != null) { fileAEInputStream.close(); fileAEInputStream = null; } if (fileInputStream != null) { fileInputStream.close(); fileInputStream = null; } } catch (IOException ignore) { ignore.printStackTrace(); } setTitleAccordingToState(); } public void rewind() { if (fileAEInputStream == null) { return; } // System.out.println(Thread.currentThread()+" AEViewer.AEPlayer.rewind() called, rewinding "+fileAEInputStream); try { fileAEInputStream.rewind(); filterChain.reset(); } catch (Exception e) { log.warning("rewind exception: " + e.getMessage()); e.printStackTrace(); } } public void pause() { AEViewer.this.setPaused(true); } public void resume() { AEViewer.this.setPaused(false); } /** sets the AEViewer paused flag */ public void setPaused(boolean yes) { AEViewer.this.setPaused(yes); } /** gets the AEViewer paused flag */ public boolean isPaused() { return AEViewer.this.isPaused(); } public AEPacketRaw getNextPacket() { return getNextPacket(null); } public AEPacketRaw getNextPacket(AEPlayerInterface player) { if (player != this) { throw new UnsupportedOperationException("tried to get data from some other player"); } AEPacketRaw aeRaw = null; try { if (!aePlayer.isFlexTimeEnabled()) { aeRaw = fileAEInputStream.readPacketByTime(getAePlayer().getSamplePeriodUs()); } else { aeRaw = fileAEInputStream.readPacketByNumber(getAePlayer().getSampleNumEvents()); } // if(aeRaw!=null) time=aeRaw.getLastTimestamp(); return aeRaw; } catch (EOFException e) { try { Thread.currentThread().sleep(200); } catch (InterruptedException ignore) { } // when we get to end, we now just wraps in either direction, to make it easier to explore the ends getAePlayer().rewind(); // we force a rewind on all players in case we are not the only one // if(!aePlayer.isPlayingForwards()) //getAePlayer().toggleDirection(); return aeRaw; } catch (IOException io) { io.printStackTrace(); return null; } catch (NullPointerException np) { np.printStackTrace(); return new AEPacketRaw(0); } } public void toggleDirection() { setSampleNumEvents(getSampleNumEvents() * -1); setSamplePeriodUs(getSamplePeriodUs() * -1); } public void speedUp() { setSampleNumEvents(getSampleNumEvents() * 2); setSamplePeriodUs(getSamplePeriodUs() * 2); } public void slowDown() { setSampleNumEvents(getSampleNumEvents() / 2); if (getSampleNumEvents() == 0) { setSampleNumEvents(1); } setSamplePeriodUs(getSamplePeriodUs() / 2); if (getSamplePeriodUs() == 0) { setSamplePeriodUs(1); } if (Math.abs(getSampleNumEvents()) < 1) { setSampleNumEvents((int) Math.signum(getSampleNumEvents())); } if (Math.abs(getSamplePeriodUs()) < 1) { setSamplePeriodUs((int) Math.signum(getSamplePeriodUs())); } } void toggleFlexTime() { setFlexTimeEnabled(!isFlexTimeEnabled()); } public boolean isPlayingForwards() { return getSamplePeriodUs() > 0; } public float getFractionalPosition() { if (fileAEInputStream == null) { log.warning("AEViewer.AEPlayer.getFractionalPosition: null fileAEInputStream, returning 0"); return 0; } return fileAEInputStream.getFractionalPosition(); } public void mark() throws IOException { fileAEInputStream.mark(); } public int position() { return fileAEInputStream.position(); } public void position(int event) { fileAEInputStream.position(event); } public AEPacketRaw readPacketByNumber(int n) throws IOException { return fileAEInputStream.readPacketByNumber(n); } public AEPacketRaw readPacketByTime(int dt) throws IOException { return fileAEInputStream.readPacketByTime(dt); } public long size() { return fileAEInputStream.size(); } public void unmark() { fileAEInputStream.unmark(); } // public synchronized AEPacketRaw readPacketToTime(int time, boolean forwards) throws IOException { // return fileAEInputStream.readPacketToTime(time,forwards); public void setFractionalPosition(float frac) { fileAEInputStream.setFractionalPosition(frac); } public void setTime(int time) { // System.out.println(this+".setTime("+time+")"); if (fileAEInputStream != null) { fileAEInputStream.setCurrentStartTimestamp(time); } else { log.warning("null AEInputStream"); } } public int getTime() { if (fileAEInputStream == null) { return 0; } return fileAEInputStream.getMostRecentTimestamp(); } public boolean isFlexTimeEnabled() { return flexTimeEnabled; } public void setFlexTimeEnabled(boolean flexTimeEnabled) { this.flexTimeEnabled = flexTimeEnabled; } public int getSamplePeriodUs() { return samplePeriodUs; } public void setSamplePeriodUs(int samplePeriodUs) { this.samplePeriodUs = samplePeriodUs; } public int getSampleNumEvents() { return sampleNumEvents; } public void setSampleNumEvents(int sampleNumEvents) { this.sampleNumEvents = sampleNumEvents; } public AEFileInputStream getAEInputStream() { return fileAEInputStream; } public boolean isNonMonotonicTimeExceptionsChecked() { return fileAEInputStream.isNonMonotonicTimeExceptionsChecked(); } public void setNonMonotonicTimeExceptionsChecked(boolean yes) { fileAEInputStream.setNonMonotonicTimeExceptionsChecked(yes); } } /** This thread acquires events and renders them to the RetinaCanvas for active rendering. The other components render themselves * on the usual Swing rendering thread. */ class ViewLoop extends Thread { Graphics2D g = null; // volatile boolean rerenderOtherComponents=false; // volatile boolean renderImageEnabled=true; volatile boolean singleStepEnabled = false, doSingleStep = false; int numRawEvents, numFilteredEvents; public ViewLoop() { super(); setName("AEViewer.ViewLoop"); } void renderPacket(EventPacket ae) { if (aePlayer.isChoosingFile()) { return; } // don't render while filechooser is active boolean subsamplingEnabled = renderer.isSubsamplingEnabled(); if (isPaused()) { renderer.setSubsamplingEnabled(false); } renderer.render(packet); if (isPaused()) { renderer.setSubsamplingEnabled(subsamplingEnabled); } // if(renderImageEnabled) { if (isActiveRenderingEnabled()) { if (canvasFileWriter.writingMovieEnabled) { chipCanvas.grabNextImage(); } chipCanvas.paintFrame(); // actively paint frame now, either with OpenGL or Java2D, depending on switch } else { // log.info("repaint by "+1000/frameRater.getDesiredFPS()+" ms"); chipCanvas.repaint(1000 / frameRater.getDesiredFPS()); // ask for repaint within frame time } if (canvasFileWriter.writingMovieEnabled) { canvasFileWriter.writeMovieFrame(); } } // renderEvents private EventPacket extractPacket(AEPacketRaw aeRaw) { boolean subsamplingEnabled = renderer.isSubsamplingEnabled(); if (isPaused()) { extractor.setSubsamplingEnabled(false); } EventPacket packet = extractor.extractPacket(aeRaw); if (isPaused()) { extractor.setSubsamplingEnabled(subsamplingEnabled); } return packet; } EngineeringFormat engFmt = new EngineeringFormat(); long beforeTime = 0, afterTime; int lastts = 0; volatile boolean stop = false; /** the main loop - this is the 'game loop' of the program */ /* synchronized tobi removed sync*/ public void run() { // don't know why this needs to be thread-safe while (stop == false && !isInterrupted()) { // now get the data to be displayed if (!isPaused() || isSingleStep()) { // if(isSingleStep()){ // log.info("getting data for single step"); // if !paused we always get data. below, if singleStepEnabled, we set paused after getting data. // when the user unpauses via menu, we disable singleStepEnabled // another flag, doSingleStep, tells loop to do a single data acquisition and then pause again // in this branch, get new data to show frameRater.takeBefore(); switch (getPlayMode()) { case SEQUENCING: HardwareInterface chipHardwareInterface = chip.getHardwareInterface(); if (chipHardwareInterface == null) { log.warning("AE monitor/sequencer became null while sequencing"); setPlayMode(PlayMode.WAITING); break; } AESequencerInterface aemonseq = (AESequencerInterface) chip.getHardwareInterface(); int nToSend = aemonseq.getNumEventsToSend(); int position = 0; if (nToSend != 0) { position = (int) (playerSlider.getMaximum() * (float) aemonseq.getNumEventsSent() / nToSend); } sliderDontProcess = true; playerSlider.setValue(position); if (!(chip.getHardwareInterface() instanceof AEMonitorInterface)) { continue; // if we're a monitor plus sequencer than go on to monitor events, otherwise break out since there are no events to monitor } case LIVE: openAEMonitor(); if (aemon == null || !aemon.isOpen()) { setPlayMode(PlayMode.WAITING); try { Thread.currentThread().sleep(300); } catch (InterruptedException e) { log.warning("LIVE openAEMonitor sleep interrupted"); } continue; } overrunOccurred = aemon.overrunOccurred(); try { // try to get an event to avoid rendering empty (black) frames int triesLeft = 15; do { if (!isInterrupted()) { aemon = (AEMonitorInterface) chip.getHardwareInterface(); // keep setting aemon to be chip's interface, this is kludge if (aemon == null) { System.err.println("AEViewer.ViewLoop.run(): null aeMon"); throw new HardwareInterfaceException("hardware interface became null"); } aeRaw = aemon.acquireAvailableEventsFromDriver(); // System.out.println("got "+aeRaw); } if (aeRaw.getNumEvents() > 0) { break; } // System.out.print("."); System.out.flush(); try { Thread.currentThread().sleep(3); } catch (InterruptedException e) { log.warning("LIVE attempt to get data loop interrupted"); } } while (triesLeft // if(aeRaw.getNumEvents()==0) {System.out.print("0 events ..."); System.out.flush();} } catch (HardwareInterfaceException e) { setPlayMode(PlayMode.WAITING); log.warning(e.toString()); e.printStackTrace(); aemon = null; continue; } catch (ClassCastException cce) { setPlayMode(PlayMode.WAITING); log.warning("Interface changed out from under us: " + cce.toString()); cce.printStackTrace(); aemon = null; continue; } break; case PLAYBACK: // Thread thisThread=Thread.currentThread(); // System.out.println("thread "+thisThread+" getting events for renderCount="+renderCount); aeRaw = getAePlayer().getNextPacket(aePlayer); // System.out.println("."); System.out.flush(); break; case REMOTE: if (unicastInputEnabled) { if (unicastInput == null) { log.warning("null unicastInput, going to WAITING state"); setPlayMode(PlayMode.WAITING); } else { aeRaw = unicastInput.readPacket(); } } if (socketInputEnabled) { if (getAeSocket() == null) { log.warning("null socketInputStream, going to WAITING state"); setPlayMode(PlayMode.WAITING); socketInputEnabled = false; } else { try { aeRaw = getAeSocket().readPacket(); // reads a packet if there is data available } catch (IOException e) { log.warning(e.toString() + ": closing and reconnecting..."); try { getAeSocket().close(); aeSocket = new AESocket(); // uses last values stored in preferences aeSocket.connect(); } catch (IOException ex3) { log.warning(ex3 + ": failed reconnection, sleeping 1 s before trying again"); try { Thread.currentThread().sleep(1000); } catch (InterruptedException ex2) { } } } } } if (spreadInputEnabled) { try { aeRaw = spreadInterface.readPacket(); } catch (SpreadException e) { e.printStackTrace(); } } if (multicastInputEnabled) { if (aeMulticastInput == null) { log.warning("null aeMulticastInput, going to WAITING state"); setPlayMode(PlayMode.WAITING); } else { aeRaw = aeMulticastInput.readPacket(); } } break; case WAITING: // notify(); // notify waiter on this thread that we have gone to WAITING state openAEMonitor(); if (aemon == null || !aemon.isOpen()) { statisticsLabel.setText("Choose interface from Interface menu"); // setPlayMode(PlayMode.WAITING); // we don't need to set it again try { Thread.currentThread().sleep(300); } catch (InterruptedException e) { log.info("WAITING interrupted"); } continue; } // synchronized(this){ // try{ // Thread.currentThread().sleep(300); // }catch(InterruptedException e){ // System.out.println("WAITING interrupted"); // continue; } // playMode switch to get data if (aeRaw == null) { // System.err.println("AEViewer.viewLoop.run(): null aeRaw"); fpsDelay(); continue; } numRawEvents = aeRaw.getNumEvents(); // new style packet with reused event objects packet = extractPacket(aeRaw); // filter events, do processing on them in rendering loop here if (filterChain.getProcessingMode() == FilterChain.ProcessingMode.RENDERING || playMode != playMode.LIVE) { try { packet = filterChain.filterPacket(packet); } catch (Exception e) { log.warning("Caught " + e + ", disabling all filters"); e.printStackTrace(); for (EventFilter f : filterChain) { f.setFilterEnabled(false); } } if (packet == null) { log.warning("null packet after filtering"); continue; } } // write to network socket if a client has opened a socket to us // we serve up events on this socket if (getAeServerSocket() != null && getAeServerSocket().getAESocket() != null) { AESocket s = getAeServerSocket().getAESocket(); try { if (!isLogFilteredEventsEnabled()) { s.writePacket(aeRaw); } else { // send the reconstructed packet after filtering AEPacketRaw aeRawRecon = extractor.reconstructRawPacket(packet); s.writePacket(aeRawRecon); } } catch (IOException e) { // e.printStackTrace(); log.warning("sending packet " + aeRaw + " from " + this + " to " + s + " failed, closing socket"); try { s.close(); } catch (IOException e2) { e2.printStackTrace(); } finally { getAeServerSocket().setSocket(null); } } } // spread is a network system used by projects like the caltech darpa urban challange alice vehicle if (spreadOutputEnabled) { try { if (!isLogFilteredEventsEnabled()) { spreadInterface.writePacket(aeRaw); } else { // log the reconstructed packet after filtering AEPacketRaw aeRawRecon = extractor.reconstructRawPacket(packet); spreadInterface.writePacket(aeRawRecon); } } catch (SpreadException e) { e.printStackTrace(); } } // if we are multicasting output send it out here if (multicastOutputEnabled && aeMulticastOutput != null) { try { if (!isLogFilteredEventsEnabled()) { aeMulticastOutput.writePacket(aeRaw); } else { // log the reconstructed packet after filtering AEPacketRaw aeRawRecon = extractor.reconstructRawPacket(packet); aeMulticastOutput.writePacket(aeRawRecon); } } catch (IOException e) { e.printStackTrace(); } } if (unicastOutputEnabled && unicastOutput != null) { try { if (!isLogFilteredEventsEnabled()) { unicastOutput.writePacket(aeRaw); } else { // log the reconstructed packet after filtering AEPacketRaw aeRawRecon = extractor.reconstructRawPacket(packet); unicastOutput.writePacket(aeRawRecon); } } catch (IOException e) { e.printStackTrace(); } } chip.setLastData(packet);// set the rendered data for use by various methods // if we are logging data to disk do it here if (loggingEnabled) { synchronized (loggingOutputStream) { try { if (!isLogFilteredEventsEnabled()) { loggingOutputStream.writePacket(aeRaw); // log all events } else { // log the reconstructed packet after filtering AEPacketRaw aeRawRecon = extractor.reconstructRawPacket(packet); loggingOutputStream.writePacket(aeRawRecon); } } catch (IOException e) { e.printStackTrace(); loggingEnabled = false; try { loggingOutputStream.close(); } catch (IOException e2) { e2.printStackTrace(); } } } if (loggingTimeLimit > 0) { // we may have a defined time for logging, if so, check here and abort logging if (System.currentTimeMillis() - loggingStartTime > loggingTimeLimit) { log.info("logging time limit reached, stopping logging"); try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { stopLogging(); // must run this in AWT thread because it messes with file menu } }); } catch (Exception e) { e.printStackTrace(); } } } } numEvents = packet.getSize(); numFilteredEvents = packet.getSize(); if (numFilteredEvents == 0 && !isRenderBlankFramesEnabled()) { // log.info("blank frame, not rendering it"); fpsDelay(); continue; } if (numEvents == 0) { noEventCounter++; } else { noEventCounter = 0; } singleStepDone(); } // getting data if (skipPacketsRenderingCount // we only got new events if we were NOT paused. but now we can apply filters, different rendering methods, etc in 'paused' condition makeStatisticsLabel(); renderPacket(packet); skipPacketsRenderingCount = skipPacketsRenderingNumber; } frameRater.takeAfter(); renderCount++; fpsDelay(); } log.warning("AEViewer.run(): stop=" + stop + " isInterrupted=" + isInterrupted()); if (aemon != null) { aemon.close(); } if (unicastOutput != null) { unicastOutput.close(); } if (unicastInput != null) { unicastInput.close(); } // if(windowSaver!=null) // try { // windowSaver.saveSettings(); // } catch (IOException e) { // e.printStackTrace(); chipCanvas.getCanvas().setVisible(false); remove(chipCanvas.getCanvas()); if (getJaerViewer() != null) { log.info("removing " + AEViewer.this + " viewer from caviar viewer list"); getJaerViewer().removeViewer(AEViewer.this); // we want to remove the viewer, not this inner class } dispose(); if (getJaerViewer() == null || getJaerViewer().getViewers().isEmpty()) { System.exit(0); } } // viewLoop.run() void fpsDelay() { if (!isPaused()) { frameRater.delayForDesiredFPS(); } else { synchronized (this) { // reason for grabbing monitor is because if we are sliding the slider, we need to make sure we have control of the view loop try { wait(100); } catch (java.lang.InterruptedException e) { log.info("viewLoop wait() interrupted: " + e.getMessage() + " cause is " + e.getCause()); } } } } private void makeStatisticsLabel() { if (getAePlayer().isChoosingFile()) { return; } // don't render stats while user is choosing file // if(ae==null) return; if (packet == null) { return; } float dtMs = 0; if (numEvents > 0) { // lastts=ae.getLastTimestamp(); lastts = packet.getLastTimestamp(); } if (numEvents > 1) { dtMs = (float) ((lastts - packet.getFirstTimestamp()) / (tickUs * 1e3)); } String thisTimeString = null; float ratekeps = packet.getEventRateHz() / 1e3f; switch (getPlayMode()) { case SEQUENCING: case LIVE: if (aemon == null) { return; } // ratekeps=aemon.getEstimatedEventRate()/1000f; thisTimeString = String.format("%5.2f", lastts * aemon.getTimestampTickUs() * 1e-6f); break; case PLAYBACK: // if(ae.getNumEvents()>2) ratekeps=(float)ae.getNumEvents()/(float)dtMs; // if(packet.getSize()>2) ratekeps=(float)packet.getSize()/(float)dtMs; thisTimeString = String.format("%5.2f", getAePlayer().getTime() * 1e-6f); // hack here, we don't know timestamp from data file, we assume 1us break; case REMOTE: thisTimeString = String.format("%5.2f", aeRaw.getLastTimestamp() * 1e-6f); break; } String rateString = null; if (ratekeps >= 10e3f) { rateString = " >10 Meps"; } else { rateString = String.format("%5.2f keps", ratekeps); } int cs = renderer.getColorScale(); String ovstring; if (overrunOccurred) { ovstring = "(overrun)"; } else { ovstring = ""; } String s = null; if (renderCount % 10 == 0 || isPaused() || isSingleStep() || frameRater.getDesiredFPS() < 20) { // don't draw stats too fast // if(numEvents==0) s=thisTimeString+ "s: No events"; // else { String timeExpansionString; if (getPlayMode() == PlayMode.LIVE || getPlayMode() == PlayMode.SEQUENCING) { timeExpansionString = ""; } else { float expansion = frameRater.getAverageFPS() * dtMs / 1000f; if (expansion == 0) { timeExpansionString = "???"; } else if (expansion > 1) { timeExpansionString = String.format("%5.1fX", expansion); } else { timeExpansionString = String.format("%5.1f/", 1 / expansion); } } String numEventsString; if (chip.getFilterChain().isAnyFilterEnabled()) { if (filterChain.isTimedOut()) { numEventsString = String.format("%5d/%-5d TO ", numRawEvents, numFilteredEvents); } else { numEventsString = String.format("%5d/%-5d evts", numRawEvents, numFilteredEvents); } } else { numEventsString = String.format("%5d evts", numRawEvents); } s = String.format("%8ss@%-8ss,%s %s,%s,%2.0f/%dfps,%4s,%2dms,%s=%2d", engFmt.format((float) dtMs / 1000), thisTimeString, numEventsString.toString(), ovstring, rateString, frameRater.getAverageFPS(), frameRater.getDesiredFPS(), timeExpansionString, frameRater.getLastDelayMs(), renderer.isAutoscaleEnabled() ? "AS" : "FS", // auto or fullscale rendering color cs); setStatisticsLabel(s); if (overrunOccurred) { statisticsLabel.setForeground(Color.RED); } else { statisticsLabel.setForeground(Color.BLACK); } } } } void setStatisticsLabel(final String s) { statisticsLabel.setText(s); // for some reason invoking in swing thread (as it seems you should) doesn't always update the label... mystery // try { // SwingUtilities.invokeAndWait(new Runnable(){ // public void run(){ // statisticsLabel.setText(s); //// if(statisticsLabel.getWidth()>statisticsPanel.getWidth()) { ////// System.out.println("statisticsLabel width="+statisticsLabel.getWidth()+" > statisticsPanel width="+statisticsPanel.getWidth()); //// // possibly resize statistics font size //// formComponentResized(null); // } catch (Exception e) { // e.printStackTrace(); } int getScreenRefreshRate() { int rate = 60; GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice[] gs = ge.getScreenDevices(); for (int i = 0; i < gs.length; i++) { DisplayMode dm = gs[i].getDisplayMode(); // Get refresh rate in Hz int refreshRate = dm.getRefreshRate(); if (refreshRate == DisplayMode.REFRESH_RATE_UNKNOWN) { log.warning("AEViewer.getScreenRefreshRate: got unknown refresh rate for screen " + i + ", assuming 60"); refreshRate = 60; } else { // log.info("AEViewer.getScreenRefreshRate: screen "+i+" has refresh rate "+refreshRate); } if (i == 0) { rate = refreshRate; } } return rate; }// computes and executes appropriate delayForDesiredFPS to try to maintain constant rendering rate class FrameRater { final int MAX_FPS = 120; int desiredFPS = prefs.getInt("AEViewer.FrameRater.desiredFPS", getScreenRefreshRate()); final int nSamples = 10; long[] samplesNs = new long[nSamples]; int index = 0; int delayMs = 1; int desiredPeriodMs = (int) (1000f / desiredFPS); void setDesiredFPS(int fps) { if (fps < 1) { fps = 1; } else if (fps > MAX_FPS) { fps = MAX_FPS; } desiredFPS = fps; prefs.putInt("AEViewer.FrameRater.desiredFPS", fps); desiredPeriodMs = 1000 / fps; } int getDesiredFPS() { return desiredFPS; } float getAveragePeriodNs() { int sum = 0; for (int i = 0; i < nSamples; i++) { sum += samplesNs[i]; } return (float) sum / nSamples; } float getAverageFPS() { return 1f / (getAveragePeriodNs() / 1e9f); } float getLastFPS() { return 1f / (lastdt / 1e9f); } int getLastDelayMs() { return delayMs; } long getLastDtNs() { return lastdt; } long beforeTimeNs = System.nanoTime(), lastdt, afterTimeNs; // call this ONCE after capture/render. it will store the time since the last call void takeBefore() { beforeTimeNs = System.nanoTime(); } long lastAfterTime = System.nanoTime(); // call this ONCE after capture/render. it will store the time since the last call void takeAfter() { afterTimeNs = System.nanoTime(); lastdt = afterTimeNs - beforeTimeNs; samplesNs[index++] = afterTimeNs - lastAfterTime; lastAfterTime = afterTimeNs; if (index >= nSamples) { index = 0; } } // call this to delayForDesiredFPS enough to make the total time including last sample period equal to desiredPeriodMs void delayForDesiredFPS() { delayMs = (int) Math.round(desiredPeriodMs - (float) getLastDtNs() / 1000000); if (delayMs < 0) { delayMs = 1; } try { Thread.currentThread().sleep(delayMs); } catch (java.lang.InterruptedException e) { } } } /** Fires a property change "stopme", and then stops playback or closes device */ public void stopMe() { getSupport().firePropertyChange("stopme", null, null); // log.info(Thread.currentThread()+ "AEViewer.stopMe() called"); switch (getPlayMode()) { case PLAYBACK: getAePlayer().stopPlayback(); break; case LIVE: case WAITING: viewLoop.stop = true; showBiasgen(false); break; } // viewer is removed by WindowClosing event // if(caviarViewer!=null ){ // log.info(this+" being removed from caviarViewer viewers list"); // caviarViewer.getViewers().remove(this); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jProgressBar1 = new javax.swing.JProgressBar(); renderModeButtonGroup = new javax.swing.ButtonGroup(); monSeqOpModeButtonGroup = new javax.swing.ButtonGroup(); statisticsPanel = new javax.swing.JPanel(); imagePanel = new javax.swing.JPanel(); bottomPanel = new javax.swing.JPanel(); buttonsPanel = new javax.swing.JPanel(); biasesToggleButton = new javax.swing.JToggleButton(); filtersToggleButton = new javax.swing.JToggleButton(); dontRenderToggleButton = new javax.swing.JToggleButton(); loggingButton = new javax.swing.JToggleButton(); playerControlPanel = new javax.swing.JPanel(); playerSlider = new javax.swing.JSlider(); resizePanel = new javax.swing.JPanel(); resizeLabel = new javax.swing.JLabel(); menuBar = new javax.swing.JMenuBar(); fileMenu = new javax.swing.JMenu(); newViewerMenuItem = new javax.swing.JMenuItem(); openMenuItem = new javax.swing.JMenuItem(); closeMenuItem = new javax.swing.JMenuItem(); jSeparator8 = new javax.swing.JSeparator(); saveImageMenuItem = new javax.swing.JMenuItem(); saveImageSequenceMenuItem = new javax.swing.JMenuItem(); jSeparator6 = new javax.swing.JSeparator(); loggingMenuItem = new javax.swing.JMenuItem(); loggingPlaybackImmediatelyCheckBoxMenuItem = new javax.swing.JCheckBoxMenuItem(); loggingSetTimelimitMenuItem = new javax.swing.JMenuItem(); logFilteredEventsCheckBoxMenuItem = new javax.swing.JCheckBoxMenuItem(); networkSeparator = new javax.swing.JSeparator(); remoteMenu = new javax.swing.JMenu(); openSocketInputStreamMenuItem = new javax.swing.JMenuItem(); reopenSocketInputStreamMenuItem = new javax.swing.JMenuItem(); serverSocketOptionsMenuItem = new javax.swing.JMenuItem(); jSeparator15 = new javax.swing.JSeparator(); multicastOutputEnabledCheckBoxMenuItem = new javax.swing.JCheckBoxMenuItem(); openMulticastInputMenuItem = new javax.swing.JCheckBoxMenuItem(); jSeparator14 = new javax.swing.JSeparator(); unicastOutputEnabledCheckBoxMenuItem = new javax.swing.JCheckBoxMenuItem(); openUnicastInputMenuItem = new javax.swing.JMenuItem(); syncSeperator = new javax.swing.JSeparator(); syncEnabledCheckBoxMenuItem = new javax.swing.JCheckBoxMenuItem(); electricalSyncEnabledCheckBoxMenuItem = new javax.swing.JCheckBoxMenuItem(); jSeparator16 = new javax.swing.JSeparator(); checkNonMonotonicTimeExceptionsEnabledCheckBoxMenuItem = new javax.swing.JCheckBoxMenuItem(); exitSeperator = new javax.swing.JSeparator(); exitMenuItem = new javax.swing.JMenuItem(); editMenu = new javax.swing.JMenu(); markInPointMenuItem = new javax.swing.JMenuItem(); markOutPointMenuItem = new javax.swing.JMenuItem(); cutMenuItem = new javax.swing.JMenuItem(); copyMenuItem = new javax.swing.JMenuItem(); pasteMenuItem = new javax.swing.JMenuItem(); viewMenu = new javax.swing.JMenu(); viewBiasesMenuItem = new javax.swing.JMenuItem(); dataWindowMenu = new javax.swing.JMenuItem(); filtersSubMenu = new javax.swing.JMenu(); viewFiltersMenuItem = new javax.swing.JMenuItem(); enableFiltersOnStartupCheckBoxMenuItem = new javax.swing.JCheckBoxMenuItem(); jSeparator1 = new javax.swing.JSeparator(); graphicsSubMenu = new javax.swing.JMenu(); viewOpenGLEnabledMenuItem = new javax.swing.JCheckBoxMenuItem(); viewActiveRenderingEnabledMenuItem = new javax.swing.JCheckBoxMenuItem(); viewRenderBlankFramesCheckBoxMenuItem = new javax.swing.JCheckBoxMenuItem(); jSeparator2 = new javax.swing.JSeparator(); skipPacketsRenderingCheckBoxMenuItem = new javax.swing.JCheckBoxMenuItem(); subsampleEnabledCheckBoxMenuItem = new javax.swing.JCheckBoxMenuItem(); subSampleSizeMenuItem = new javax.swing.JMenuItem(); jSeparator3 = new javax.swing.JSeparator(); cycleColorRenderingMethodMenuItem = new javax.swing.JMenuItem(); increaseContrastMenuItem = new javax.swing.JMenuItem(); decreaseContrastMenuItem = new javax.swing.JMenuItem(); autoscaleContrastEnabledCheckBoxMenuItem = new javax.swing.JCheckBoxMenuItem(); calibrationStartStop = new javax.swing.JMenuItem(); jSeparator4 = new javax.swing.JSeparator(); cycleDisplayMethodButton = new javax.swing.JMenuItem(); displayMethodMenu = new javax.swing.JMenu(); jSeparator12 = new javax.swing.JSeparator(); acccumulateImageEnabledCheckBoxMenuItem = new javax.swing.JCheckBoxMenuItem(); viewIgnorePolarityCheckBoxMenuItem = new javax.swing.JCheckBoxMenuItem(); increaseFrameRateMenuItem = new javax.swing.JMenuItem(); decreaseFrameRateMenuItem = new javax.swing.JMenuItem(); pauseRenderingCheckBoxMenuItem = new javax.swing.JCheckBoxMenuItem(); viewSingleStepMenuItem = new javax.swing.JMenuItem(); zeroTimestampsMenuItem = new javax.swing.JMenuItem(); jSeparator11 = new javax.swing.JSeparator(); increasePlaybackSpeedMenuItem = new javax.swing.JMenuItem(); decreasePlaybackSpeedMenuItem = new javax.swing.JMenuItem(); rewindPlaybackMenuItem = new javax.swing.JMenuItem(); flextimePlaybackEnabledCheckBoxMenuItem = new javax.swing.JCheckBoxMenuItem(); togglePlaybackDirectionMenuItem = new javax.swing.JMenuItem(); toggleMarkCheckBoxMenuItem = new javax.swing.JCheckBoxMenuItem(); measureTimeMenuItem = new javax.swing.JMenuItem(); jSeparator10 = new javax.swing.JSeparator(); zoomMenuItem = new javax.swing.JMenuItem(); unzoomMenuItem = new javax.swing.JMenuItem(); deviceMenu = new javax.swing.JMenu(); deviceMenuSpparator = new javax.swing.JSeparator(); customizeDevicesMenuItem = new javax.swing.JMenuItem(); interfaceMenu = new javax.swing.JMenu(); refreshInterfaceMenuItem = new javax.swing.JMenuItem(); controlMenu = new javax.swing.JMenu(); increaseBufferSizeMenuItem = new javax.swing.JMenuItem(); decreaseBufferSizeMenuItem = new javax.swing.JMenuItem(); increaseNumBuffersMenuItem = new javax.swing.JMenuItem(); decreaseNumBuffersMenuItem = new javax.swing.JMenuItem(); jSeparator9 = new javax.swing.JSeparator(); changeAEBufferSizeMenuItem = new javax.swing.JMenuItem(); jSeparator5 = new javax.swing.JSeparator(); updateFirmwareMenuItem = new javax.swing.JMenuItem(); cypressFX2EEPROMMenuItem = new javax.swing.JMenuItem(); monSeqMenu = new javax.swing.JMenu(); sequenceMenuItem = new javax.swing.JMenuItem(); enableMissedEventsCheckBox = new javax.swing.JCheckBoxMenuItem(); monSeqMissedEventsMenuItem = new javax.swing.JMenuItem(); jSeparator13 = new javax.swing.JSeparator(); monSeqOperationModeMenu = new javax.swing.JMenu(); monSeqOpMode0 = new javax.swing.JRadioButtonMenuItem(); monSeqOpMode1 = new javax.swing.JRadioButtonMenuItem(); helpMenu = new javax.swing.JMenu(); contentMenuItem = new javax.swing.JMenuItem(); helpRetinaMenuItem = new javax.swing.JMenuItem(); helpUserGuideMenuItem = new javax.swing.JMenuItem(); helpAERCablingUserGuideMenuItem = new javax.swing.JMenuItem(); javadocMenuItem = new javax.swing.JMenuItem(); javadocWebMenuItem = new javax.swing.JMenuItem(); jSeparator7 = new javax.swing.JSeparator(); aboutMenuItem = new javax.swing.JMenuItem(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("AEViewer"); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { formWindowClosing(evt); } }); addComponentListener(new java.awt.event.ComponentAdapter() { public void componentResized(java.awt.event.ComponentEvent evt) { formComponentResized(evt); } }); statisticsPanel.setFocusable(false); statisticsPanel.addComponentListener(new java.awt.event.ComponentAdapter() { public void componentResized(java.awt.event.ComponentEvent evt) { statisticsPanelComponentResized(evt); } }); getContentPane().add(statisticsPanel, java.awt.BorderLayout.NORTH); imagePanel.setEnabled(false); imagePanel.setFocusable(false); imagePanel.addMouseWheelListener(new java.awt.event.MouseWheelListener() { public void mouseWheelMoved(java.awt.event.MouseWheelEvent evt) { imagePanelMouseWheelMoved(evt); } }); imagePanel.setLayout(new java.awt.BorderLayout()); getContentPane().add(imagePanel, java.awt.BorderLayout.CENTER); bottomPanel.setLayout(new java.awt.BorderLayout()); buttonsPanel.setPreferredSize(new java.awt.Dimension(450, 30)); buttonsPanel.setLayout(new javax.swing.BoxLayout(buttonsPanel, javax.swing.BoxLayout.LINE_AXIS)); biasesToggleButton.setFont(new java.awt.Font("Tahoma", 0, 10)); biasesToggleButton.setText("Biases"); biasesToggleButton.setToolTipText("Shows or hides the bias generator control panel"); biasesToggleButton.setMargin(new java.awt.Insets(2, 2, 2, 2)); biasesToggleButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { biasesToggleButtonActionPerformed(evt); } }); buttonsPanel.add(biasesToggleButton); filtersToggleButton.setFont(new java.awt.Font("Tahoma", 0, 10)); filtersToggleButton.setText("Filters"); filtersToggleButton.setToolTipText("Shows or hides the filter window"); filtersToggleButton.setMargin(new java.awt.Insets(2, 2, 2, 2)); filtersToggleButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { filtersToggleButtonActionPerformed(evt); } }); buttonsPanel.add(filtersToggleButton); dontRenderToggleButton.setFont(new java.awt.Font("Tahoma", 0, 10)); dontRenderToggleButton.setText("Don't render"); dontRenderToggleButton.setToolTipText("Disables rendering to spped up processing"); dontRenderToggleButton.setMargin(new java.awt.Insets(2, 2, 2, 2)); dontRenderToggleButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { dontRenderToggleButtonActionPerformed(evt); } }); buttonsPanel.add(dontRenderToggleButton); loggingButton.setFont(new java.awt.Font("Tahoma", 0, 10)); loggingButton.setMnemonic('l'); loggingButton.setText("Start logging"); loggingButton.setToolTipText("Starts or stops logging or relogging"); loggingButton.setMargin(new java.awt.Insets(2, 2, 2, 2)); buttonsPanel.add(loggingButton); playerControlPanel.setToolTipText("playback controls"); playerControlPanel.setPreferredSize(new java.awt.Dimension(400, 40)); playerControlPanel.setLayout(new javax.swing.BoxLayout(playerControlPanel, javax.swing.BoxLayout.LINE_AXIS)); playerSlider.setMaximum(1000); playerSlider.setToolTipText("Shows and controls playback position (in events, not time)"); playerSlider.setValue(0); playerSlider.setMaximumSize(new java.awt.Dimension(800, 25)); playerSlider.setPreferredSize(new java.awt.Dimension(600, 25)); playerSlider.addMouseListener(new java.awt.event.MouseAdapter() { public void mousePressed(java.awt.event.MouseEvent evt) { playerSliderMousePressed(evt); } public void mouseReleased(java.awt.event.MouseEvent evt) { playerSliderMouseReleased(evt); } }); playerSlider.addChangeListener(new javax.swing.event.ChangeListener() { public void stateChanged(javax.swing.event.ChangeEvent evt) { playerSliderStateChanged(evt); } }); playerControlPanel.add(playerSlider); buttonsPanel.add(playerControlPanel); bottomPanel.add(buttonsPanel, java.awt.BorderLayout.CENTER); resizePanel.setMinimumSize(new java.awt.Dimension(0, 0)); resizePanel.setPreferredSize(new java.awt.Dimension(24, 24)); resizePanel.setLayout(new java.awt.BorderLayout()); resizeLabel.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); resizeLabel.setIcon(new TriangleSquareWindowsCornerIcon()); new TriangleSquareWindowsCornerIcon(); resizeLabel.setToolTipText("Resizes window"); resizeLabel.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { resizeLabelMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { resizeLabelMouseExited(evt); } public void mousePressed(java.awt.event.MouseEvent evt) { resizeLabelMousePressed(evt); } }); resizeLabel.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseDragged(java.awt.event.MouseEvent evt) { resizeLabelMouseDragged(evt); } }); resizePanel.add(resizeLabel, java.awt.BorderLayout.SOUTH); bottomPanel.add(resizePanel, java.awt.BorderLayout.EAST); getContentPane().add(bottomPanel, java.awt.BorderLayout.SOUTH); fileMenu.setMnemonic('f'); fileMenu.setText("File"); newViewerMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK)); newViewerMenuItem.setMnemonic('N'); newViewerMenuItem.setText("New viewer"); newViewerMenuItem.setToolTipText("Opens a new viewer"); newViewerMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { newViewerMenuItemActionPerformed(evt); } }); fileMenu.add(newViewerMenuItem); openMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, 0)); openMenuItem.setMnemonic('o'); openMenuItem.setText("Open logged data file..."); openMenuItem.setToolTipText("Opens a logged data file for playback"); openMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { openMenuItemActionPerformed(evt); } }); fileMenu.add(openMenuItem); closeMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_W, java.awt.event.InputEvent.CTRL_MASK)); closeMenuItem.setMnemonic('C'); closeMenuItem.setText("Close"); closeMenuItem.setToolTipText("Closes this viewer or the playing data file"); closeMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { closeMenuItemActionPerformed(evt); } }); fileMenu.add(closeMenuItem); fileMenu.add(jSeparator8); saveImageMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.ALT_MASK | java.awt.event.InputEvent.CTRL_MASK)); saveImageMenuItem.setText("Save image as PNG"); saveImageMenuItem.setToolTipText("Saves a single PNG of the canvas"); saveImageMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { saveImageMenuItemActionPerformed(evt); } }); fileMenu.add(saveImageMenuItem); saveImageSequenceMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_M, java.awt.event.InputEvent.ALT_MASK | java.awt.event.InputEvent.CTRL_MASK)); saveImageSequenceMenuItem.setText("Save image sequence"); saveImageSequenceMenuItem.setToolTipText("Saves sequence to a set of files in folder"); saveImageSequenceMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { saveImageSequenceMenuItemActionPerformed(evt); } }); fileMenu.add(saveImageSequenceMenuItem); fileMenu.add(jSeparator6); loggingMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_L, 0)); loggingMenuItem.setText("Start logging data"); loggingMenuItem.setToolTipText("Starts or stops logging to disk"); fileMenu.add(loggingMenuItem); loggingPlaybackImmediatelyCheckBoxMenuItem.setText("Playback logged data immediately after logging enabled"); loggingPlaybackImmediatelyCheckBoxMenuItem.setToolTipText("If enabled, logged data plays back immediately"); loggingPlaybackImmediatelyCheckBoxMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { loggingPlaybackImmediatelyCheckBoxMenuItemActionPerformed(evt); } }); fileMenu.add(loggingPlaybackImmediatelyCheckBoxMenuItem); loggingSetTimelimitMenuItem.setText("Set logging time limit..."); loggingSetTimelimitMenuItem.setToolTipText("Sets a time limit for logging"); loggingSetTimelimitMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { loggingSetTimelimitMenuItemActionPerformed(evt); } }); fileMenu.add(loggingSetTimelimitMenuItem); logFilteredEventsCheckBoxMenuItem.setText("Enable filtering of logged or network output events"); logFilteredEventsCheckBoxMenuItem.setToolTipText("Logging or network writes apply active filters first (reduces file size or network traffi)"); logFilteredEventsCheckBoxMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { logFilteredEventsCheckBoxMenuItemActionPerformed(evt); } }); fileMenu.add(logFilteredEventsCheckBoxMenuItem); fileMenu.add(networkSeparator); remoteMenu.setMnemonic('r'); remoteMenu.setText("Remote"); openSocketInputStreamMenuItem.setMnemonic('r'); openSocketInputStreamMenuItem.setText("Open remote server input stream socket..."); openSocketInputStreamMenuItem.setToolTipText("Opens a remote connection for stream (TCP) packets of events "); openSocketInputStreamMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { openSocketInputStreamMenuItemActionPerformed(evt); } }); remoteMenu.add(openSocketInputStreamMenuItem); reopenSocketInputStreamMenuItem.setMnemonic('l'); reopenSocketInputStreamMenuItem.setText("Reopen last stream socket input stream"); reopenSocketInputStreamMenuItem.setToolTipText("After an input socket has been opened, this quickly closes and reopens it"); reopenSocketInputStreamMenuItem.setEnabled(false); reopenSocketInputStreamMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { reopenSocketInputStreamMenuItemActionPerformed(evt); } }); remoteMenu.add(reopenSocketInputStreamMenuItem); serverSocketOptionsMenuItem.setText("Stream socket server options..."); serverSocketOptionsMenuItem.setToolTipText("Sets options for server sockets"); serverSocketOptionsMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { serverSocketOptionsMenuItemActionPerformed(evt); } }); remoteMenu.add(serverSocketOptionsMenuItem); remoteMenu.add(jSeparator15); multicastOutputEnabledCheckBoxMenuItem.setMnemonic('s'); multicastOutputEnabledCheckBoxMenuItem.setText("Enable Multicast (UDP) AE Output"); multicastOutputEnabledCheckBoxMenuItem.setToolTipText("<html>Enable multicast AE output (datagrams)<br><strong>Warning! Will flood network if there are no listeners.</strong></html>"); multicastOutputEnabledCheckBoxMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { multicastOutputEnabledCheckBoxMenuItemActionPerformed(evt); } }); remoteMenu.add(multicastOutputEnabledCheckBoxMenuItem); openMulticastInputMenuItem.setMnemonic('s'); openMulticastInputMenuItem.setText("Enable Multicast (UDP) AE input"); openMulticastInputMenuItem.setToolTipText("Enable multicast AE input (datagrams)"); openMulticastInputMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { openMulticastInputMenuItemActionPerformed(evt); } }); remoteMenu.add(openMulticastInputMenuItem); remoteMenu.add(jSeparator14); unicastOutputEnabledCheckBoxMenuItem.setMnemonic('o'); unicastOutputEnabledCheckBoxMenuItem.setText("Enable unicast datagram (UDP) output..."); unicastOutputEnabledCheckBoxMenuItem.setToolTipText("Enables unicast datagram (UDP) outputs to a single receiver"); unicastOutputEnabledCheckBoxMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { unicastOutputEnabledCheckBoxMenuItemActionPerformed(evt); } }); remoteMenu.add(unicastOutputEnabledCheckBoxMenuItem); openUnicastInputMenuItem.setMnemonic('i'); openUnicastInputMenuItem.setText("Open Unicast (UDP) remote AE input..."); openUnicastInputMenuItem.setToolTipText("Opens a remote UDP unicast AE input"); openUnicastInputMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { openUnicastInputMenuItemActionPerformed(evt); } }); remoteMenu.add(openUnicastInputMenuItem); fileMenu.add(remoteMenu); fileMenu.add(syncSeperator); syncEnabledCheckBoxMenuItem.setText("Synchronized logging/playback enabled"); syncEnabledCheckBoxMenuItem.setToolTipText("All viwers start/stop logging in synchrony and playback times are synchronized"); fileMenu.add(syncEnabledCheckBoxMenuItem); electricalSyncEnabledCheckBoxMenuItem.setText("Electrical sync time enabled"); electricalSyncEnabledCheckBoxMenuItem.setToolTipText("If enabled, specifies that boards can electrically synchronize timestamps. Ony a single CaviarViewer window device has timestamp zeroed - the rest must sync electrically from this. If disabled, then each viewer's device is zeroed in software."); electricalSyncEnabledCheckBoxMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { electricalSyncEnabledCheckBoxMenuItemActionPerformed(evt); } }); fileMenu.add(electricalSyncEnabledCheckBoxMenuItem); fileMenu.add(jSeparator16); checkNonMonotonicTimeExceptionsEnabledCheckBoxMenuItem.setSelected(true); checkNonMonotonicTimeExceptionsEnabledCheckBoxMenuItem.setText("Check for non-monotonic time in input streams"); checkNonMonotonicTimeExceptionsEnabledCheckBoxMenuItem.setToolTipText("If enabled, nonmonotonic time stamps are checked for in input streams from file or network"); fileMenu.add(checkNonMonotonicTimeExceptionsEnabledCheckBoxMenuItem); fileMenu.add(exitSeperator); exitMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X, 0)); exitMenuItem.setMnemonic('x'); exitMenuItem.setText("Exit"); exitMenuItem.setToolTipText("Exits all viewers"); exitMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { exitMenuItemActionPerformed(evt); } }); fileMenu.add(exitMenuItem); menuBar.add(fileMenu); editMenu.setMnemonic('e'); editMenu.setText("Edit"); editMenu.setEnabled(false); markInPointMenuItem.setMnemonic('i'); markInPointMenuItem.setText("Mark IN point"); editMenu.add(markInPointMenuItem); markOutPointMenuItem.setMnemonic('o'); markOutPointMenuItem.setText("Mark OUT point"); editMenu.add(markOutPointMenuItem); cutMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.CTRL_MASK)); cutMenuItem.setText("Cut"); editMenu.add(cutMenuItem); copyMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.CTRL_MASK)); copyMenuItem.setText("Copy"); editMenu.add(copyMenuItem); pasteMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_V, java.awt.event.InputEvent.CTRL_MASK)); pasteMenuItem.setText("Paste"); editMenu.add(pasteMenuItem); menuBar.add(editMenu); viewMenu.setMnemonic('v'); viewMenu.setText("View"); viewBiasesMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_B, java.awt.event.InputEvent.CTRL_MASK)); viewBiasesMenuItem.setMnemonic('b'); viewBiasesMenuItem.setText("Biases"); viewBiasesMenuItem.setToolTipText("Shows chip or board biasing controls"); viewBiasesMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { viewBiasesMenuItemActionPerformed(evt); } }); viewMenu.add(viewBiasesMenuItem); dataWindowMenu.setText("Data Window"); dataWindowMenu.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { dataWindowMenuActionPerformed(evt); } }); viewMenu.add(dataWindowMenu); filtersSubMenu.setMnemonic('f'); filtersSubMenu.setText("Event Filtering"); viewFiltersMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F, java.awt.event.InputEvent.CTRL_MASK)); viewFiltersMenuItem.setMnemonic('f'); viewFiltersMenuItem.setText("Filters"); viewFiltersMenuItem.setToolTipText("Shows filter controls"); viewFiltersMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { viewFiltersMenuItemActionPerformed(evt); } }); filtersSubMenu.add(viewFiltersMenuItem); enableFiltersOnStartupCheckBoxMenuItem.setText("Enable filters on startup"); enableFiltersOnStartupCheckBoxMenuItem.setToolTipText("Enables creation of event processing filters on startup"); enableFiltersOnStartupCheckBoxMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { enableFiltersOnStartupCheckBoxMenuItemActionPerformed(evt); } }); filtersSubMenu.add(enableFiltersOnStartupCheckBoxMenuItem); viewMenu.add(filtersSubMenu); viewMenu.add(jSeparator1); graphicsSubMenu.setMnemonic('g'); graphicsSubMenu.setText("Graphics options"); viewOpenGLEnabledMenuItem.setText("Enable OpenGL rendering"); viewOpenGLEnabledMenuItem.setToolTipText("Enables use of JOGL OpenGL library for rendering"); viewOpenGLEnabledMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { viewOpenGLEnabledMenuItemActionPerformed(evt); } }); graphicsSubMenu.add(viewOpenGLEnabledMenuItem); viewActiveRenderingEnabledMenuItem.setText("Active rendering enabled"); viewActiveRenderingEnabledMenuItem.setToolTipText("Enables active display of each rendered frame"); viewActiveRenderingEnabledMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { viewActiveRenderingEnabledMenuItemActionPerformed(evt); } }); graphicsSubMenu.add(viewActiveRenderingEnabledMenuItem); viewRenderBlankFramesCheckBoxMenuItem.setText("Render blank frames"); viewRenderBlankFramesCheckBoxMenuItem.setToolTipText("If enabled, frames without events are rendered"); viewRenderBlankFramesCheckBoxMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { viewRenderBlankFramesCheckBoxMenuItemActionPerformed(evt); } }); graphicsSubMenu.add(viewRenderBlankFramesCheckBoxMenuItem); graphicsSubMenu.add(jSeparator2); skipPacketsRenderingCheckBoxMenuItem.setText("Skip packets rendering enabled..."); skipPacketsRenderingCheckBoxMenuItem.setToolTipText("Enables skipping rendering of packets"); skipPacketsRenderingCheckBoxMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { skipPacketsRenderingCheckBoxMenuItemActionPerformed(evt); } }); graphicsSubMenu.add(skipPacketsRenderingCheckBoxMenuItem); subsampleEnabledCheckBoxMenuItem.setText("Enable subsample rendering"); subsampleEnabledCheckBoxMenuItem.setToolTipText("use to speed up rendering"); subsampleEnabledCheckBoxMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { subsampleEnabledCheckBoxMenuItemActionPerformed(evt); } }); graphicsSubMenu.add(subsampleEnabledCheckBoxMenuItem); subSampleSizeMenuItem.setText("Choose rendering subsample limit..."); subSampleSizeMenuItem.setToolTipText("Sets the number of events rendered in subsampling mode"); subSampleSizeMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { subSampleSizeMenuItemActionPerformed(evt); } }); graphicsSubMenu.add(subSampleSizeMenuItem); viewMenu.add(graphicsSubMenu); viewMenu.add(jSeparator3); cycleColorRenderingMethodMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, 0)); cycleColorRenderingMethodMenuItem.setText("Cycle color rendering mode"); cycleColorRenderingMethodMenuItem.setToolTipText("Changes rendering mode (gray, contrast, RG, color-time)"); cycleColorRenderingMethodMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cycleColorRenderingMethodMenuItemActionPerformed(evt); } }); viewMenu.add(cycleColorRenderingMethodMenuItem); increaseContrastMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_UP, 0)); increaseContrastMenuItem.setText("Increase contrast"); increaseContrastMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { increaseContrastMenuItemActionPerformed(evt); } }); viewMenu.add(increaseContrastMenuItem); decreaseContrastMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_DOWN, 0)); decreaseContrastMenuItem.setText("Decrease contrast"); decreaseContrastMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { decreaseContrastMenuItemActionPerformed(evt); } }); viewMenu.add(decreaseContrastMenuItem); autoscaleContrastEnabledCheckBoxMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_A, 0)); autoscaleContrastEnabledCheckBoxMenuItem.setText("Autoscale contrast enabled"); autoscaleContrastEnabledCheckBoxMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { autoscaleContrastEnabledCheckBoxMenuItemActionPerformed(evt); } }); viewMenu.add(autoscaleContrastEnabledCheckBoxMenuItem); calibrationStartStop.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_K, 0)); calibrationStartStop.setText("Start Calibration"); calibrationStartStop.setToolTipText("Hold uniform surface in front of lens and start calibration. Wait a few seconds and stop calibration."); calibrationStartStop.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { calibrationStartStopActionPerformed(evt); } }); viewMenu.add(calibrationStartStop); viewMenu.add(jSeparator4); cycleDisplayMethodButton.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_3, 0)); cycleDisplayMethodButton.setText("Cycle display method"); cycleDisplayMethodButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cycleDisplayMethodButtonActionPerformed(evt); } }); viewMenu.add(cycleDisplayMethodButton); displayMethodMenu.setText("display methods (placeholder)"); viewMenu.add(displayMethodMenu); viewMenu.add(jSeparator12); acccumulateImageEnabledCheckBoxMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_P, 0)); acccumulateImageEnabledCheckBoxMenuItem.setText("Accumulate image"); acccumulateImageEnabledCheckBoxMenuItem.setToolTipText("Rendered data accumulates over frames"); acccumulateImageEnabledCheckBoxMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { acccumulateImageEnabledCheckBoxMenuItemActionPerformed(evt); } }); viewMenu.add(acccumulateImageEnabledCheckBoxMenuItem); viewIgnorePolarityCheckBoxMenuItem.setText("Ignore cell type"); viewIgnorePolarityCheckBoxMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { viewIgnorePolarityCheckBoxMenuItemActionPerformed(evt); } }); viewMenu.add(viewIgnorePolarityCheckBoxMenuItem); increaseFrameRateMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_RIGHT, 0)); increaseFrameRateMenuItem.setText("Increase rendering frame rate"); increaseFrameRateMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { increaseFrameRateMenuItemActionPerformed(evt); } }); viewMenu.add(increaseFrameRateMenuItem); decreaseFrameRateMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_LEFT, 0)); decreaseFrameRateMenuItem.setText("Decrease rendering frame rate"); decreaseFrameRateMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { decreaseFrameRateMenuItemActionPerformed(evt); } }); viewMenu.add(decreaseFrameRateMenuItem); pauseRenderingCheckBoxMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_SPACE, 0)); pauseRenderingCheckBoxMenuItem.setText("Paused"); pauseRenderingCheckBoxMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { pauseRenderingCheckBoxMenuItemActionPerformed(evt); } }); viewMenu.add(pauseRenderingCheckBoxMenuItem); viewSingleStepMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_PERIOD, 0)); viewSingleStepMenuItem.setText("Single step"); viewSingleStepMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { viewSingleStepMenuItemActionPerformed(evt); } }); viewMenu.add(viewSingleStepMenuItem); zeroTimestampsMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_0, 0)); zeroTimestampsMenuItem.setText("Zero timestamps"); zeroTimestampsMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { zeroTimestampsMenuItemActionPerformed(evt); } }); viewMenu.add(zeroTimestampsMenuItem); viewMenu.add(jSeparator11); increasePlaybackSpeedMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F, 0)); increasePlaybackSpeedMenuItem.setText("Increase playback speed"); increasePlaybackSpeedMenuItem.setEnabled(false); increasePlaybackSpeedMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { increasePlaybackSpeedMenuItemActionPerformed(evt); } }); viewMenu.add(increasePlaybackSpeedMenuItem); decreasePlaybackSpeedMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, 0)); decreasePlaybackSpeedMenuItem.setText("Decrease playback speed"); decreasePlaybackSpeedMenuItem.setEnabled(false); decreasePlaybackSpeedMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { decreasePlaybackSpeedMenuItemActionPerformed(evt); } }); viewMenu.add(decreasePlaybackSpeedMenuItem); rewindPlaybackMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_R, 0)); rewindPlaybackMenuItem.setText("Rewind"); rewindPlaybackMenuItem.setEnabled(false); rewindPlaybackMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { rewindPlaybackMenuItemActionPerformed(evt); } }); viewMenu.add(rewindPlaybackMenuItem); flextimePlaybackEnabledCheckBoxMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_T, 0)); flextimePlaybackEnabledCheckBoxMenuItem.setText("Flextime playback enabled"); flextimePlaybackEnabledCheckBoxMenuItem.setToolTipText("Enables playback with constant number of events"); flextimePlaybackEnabledCheckBoxMenuItem.setEnabled(false); flextimePlaybackEnabledCheckBoxMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { flextimePlaybackEnabledCheckBoxMenuItemActionPerformed(evt); } }); viewMenu.add(flextimePlaybackEnabledCheckBoxMenuItem); togglePlaybackDirectionMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_B, 0)); togglePlaybackDirectionMenuItem.setText("Toggle playback direction"); togglePlaybackDirectionMenuItem.setEnabled(false); togglePlaybackDirectionMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { togglePlaybackDirectionMenuItemActionPerformed(evt); } }); viewMenu.add(togglePlaybackDirectionMenuItem); toggleMarkCheckBoxMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_M, 0)); toggleMarkCheckBoxMenuItem.setText("Toggle mark present location for rewind"); toggleMarkCheckBoxMenuItem.setEnabled(false); toggleMarkCheckBoxMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { toggleMarkCheckBoxMenuItemActionPerformed(evt); } }); viewMenu.add(toggleMarkCheckBoxMenuItem); measureTimeMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_1, 0)); measureTimeMenuItem.setText("Measure time"); measureTimeMenuItem.setToolTipText("Each click reports statistics about timing since last click"); measureTimeMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { measureTimeMenuItemActionPerformed(evt); } }); viewMenu.add(measureTimeMenuItem); viewMenu.add(jSeparator10); zoomMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Z, 0)); zoomMenuItem.setMnemonic('z'); zoomMenuItem.setText("Zoom"); zoomMenuItem.setToolTipText("drag mouse to draw zoom box"); zoomMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { zoomMenuItemActionPerformed(evt); } }); viewMenu.add(zoomMenuItem); unzoomMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_HOME, 0)); unzoomMenuItem.setText("Unzoom"); unzoomMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { unzoomMenuItemActionPerformed(evt); } }); viewMenu.add(unzoomMenuItem); menuBar.add(viewMenu); deviceMenu.setMnemonic('a'); deviceMenu.setText("AEChip"); deviceMenu.setToolTipText("Specifies which chip is connected"); deviceMenu.add(deviceMenuSpparator); customizeDevicesMenuItem.setMnemonic('C'); customizeDevicesMenuItem.setText("Customize..."); customizeDevicesMenuItem.setToolTipText("Let's you customize which AEChip's are available"); customizeDevicesMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { customizeDevicesMenuItemActionPerformed(evt); } }); deviceMenu.add(customizeDevicesMenuItem); menuBar.add(deviceMenu); interfaceMenu.setMnemonic('i'); interfaceMenu.setText("Interface"); interfaceMenu.setToolTipText("Select the HW interface to use"); interfaceMenu.addMenuListener(new javax.swing.event.MenuListener() { public void menuCanceled(javax.swing.event.MenuEvent evt) { } public void menuDeselected(javax.swing.event.MenuEvent evt) { } public void menuSelected(javax.swing.event.MenuEvent evt) { interfaceMenuMenuSelected(evt); } }); interfaceMenu.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { interfaceMenuActionPerformed(evt); } }); refreshInterfaceMenuItem.setText("Refresh"); refreshInterfaceMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { refreshInterfaceMenuItemActionPerformed(evt); } }); interfaceMenu.add(refreshInterfaceMenuItem); menuBar.add(interfaceMenu); controlMenu.setMnemonic('c'); controlMenu.setText("CypressFX2"); controlMenu.setToolTipText("control CypresFX2 driver parameters"); increaseBufferSizeMenuItem.setText("Increase hardware buffer size"); increaseBufferSizeMenuItem.setToolTipText("Increases the host USB fifo size"); increaseBufferSizeMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { increaseBufferSizeMenuItemActionPerformed(evt); } }); controlMenu.add(increaseBufferSizeMenuItem); decreaseBufferSizeMenuItem.setText("Decrease hardware buffer size"); decreaseBufferSizeMenuItem.setToolTipText("Decreases the host USB fifo size"); decreaseBufferSizeMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { decreaseBufferSizeMenuItemActionPerformed(evt); } }); controlMenu.add(decreaseBufferSizeMenuItem); increaseNumBuffersMenuItem.setText("Increase number of hardware buffers"); increaseNumBuffersMenuItem.setToolTipText("Increases the host number of USB read buffers"); increaseNumBuffersMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { increaseNumBuffersMenuItemActionPerformed(evt); } }); controlMenu.add(increaseNumBuffersMenuItem); decreaseNumBuffersMenuItem.setText("Decrease num hardware buffers"); decreaseNumBuffersMenuItem.setToolTipText("Decreases the host number of USB read buffers"); decreaseNumBuffersMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { decreaseNumBuffersMenuItemActionPerformed(evt); } }); controlMenu.add(decreaseNumBuffersMenuItem); controlMenu.add(jSeparator9); changeAEBufferSizeMenuItem.setMnemonic('b'); changeAEBufferSizeMenuItem.setText("Set rendering AE buffer size"); changeAEBufferSizeMenuItem.setToolTipText("sets size of host raw event buffers used for render/capture data exchnage"); changeAEBufferSizeMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { changeAEBufferSizeMenuItemActionPerformed(evt); } }); controlMenu.add(changeAEBufferSizeMenuItem); controlMenu.add(jSeparator5); updateFirmwareMenuItem.setText("Update firmware..."); updateFirmwareMenuItem.setToolTipText("Updates device firmware with confirm dialog"); updateFirmwareMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { updateFirmwareMenuItemActionPerformed(evt); } }); controlMenu.add(updateFirmwareMenuItem); cypressFX2EEPROMMenuItem.setText("(Advanced users only) CypressFX2 EEPPROM Utility"); cypressFX2EEPROMMenuItem.setToolTipText("(advanced users) Opens dialog to download device firmware "); cypressFX2EEPROMMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cypressFX2EEPROMMenuItemActionPerformed(evt); } }); controlMenu.add(cypressFX2EEPROMMenuItem); menuBar.add(controlMenu); monSeqMenu.setText("MonSeq"); monSeqMenu.setToolTipText("For sequencer or monitor+sequencer devices"); monSeqMenu.setEnabled(false); sequenceMenuItem.setMnemonic('f'); sequenceMenuItem.setText("Sequence data file..."); sequenceMenuItem.setToolTipText("You can select a recorded data file to sequence"); sequenceMenuItem.setActionCommand("start"); sequenceMenuItem.setEnabled(false); sequenceMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { sequenceMenuItemActionPerformed(evt); } }); monSeqMenu.add(sequenceMenuItem); enableMissedEventsCheckBox.setText("Enable Missed Events"); enableMissedEventsCheckBox.setEnabled(false); enableMissedEventsCheckBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { enableMissedEventsCheckBoxActionPerformed(evt); } }); monSeqMenu.add(enableMissedEventsCheckBox); monSeqMissedEventsMenuItem.setText("Get number of missed events"); monSeqMissedEventsMenuItem.setToolTipText("If the device is a monitor, this will show how many events were missed"); monSeqMissedEventsMenuItem.setEnabled(false); monSeqMissedEventsMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { monSeqMissedEventsMenuItemActionPerformed(evt); } }); monSeqMenu.add(monSeqMissedEventsMenuItem); monSeqMenu.add(jSeparator13); monSeqOperationModeMenu.setText("Timestamp tick"); monSeqOpModeButtonGroup.add(monSeqOpMode0); monSeqOpMode0.setSelected(true); monSeqOpMode0.setText("1 microsecond "); monSeqOpMode0.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { monSeqOpMode0ActionPerformed(evt); } }); monSeqOperationModeMenu.add(monSeqOpMode0); monSeqOpModeButtonGroup.add(monSeqOpMode1); monSeqOpMode1.setText("0.2 microsecond"); monSeqOpMode1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { monSeqOpMode1ActionPerformed(evt); } }); monSeqOperationModeMenu.add(monSeqOpMode1); monSeqMenu.add(monSeqOperationModeMenu); menuBar.add(monSeqMenu); helpMenu.setMnemonic('h'); helpMenu.setText("Help"); contentMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F1, 0)); contentMenuItem.setMnemonic('c'); contentMenuItem.setText("jAER project web (jaer.wiki.sourceforge.net)"); contentMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { contentMenuItemActionPerformed(evt); } }); helpMenu.add(contentMenuItem); helpRetinaMenuItem.setText("Silicon retina web"); helpRetinaMenuItem.setToolTipText("Goes to web site for silicon retina"); helpRetinaMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { helpRetinaMenuItemActionPerformed(evt); } }); helpMenu.add(helpRetinaMenuItem); helpUserGuideMenuItem.setText("USB2 Mini user guide (PDF)"); helpUserGuideMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { helpUserGuideMenuItemActionPerformed(evt); } }); helpMenu.add(helpUserGuideMenuItem); helpAERCablingUserGuideMenuItem.setText("AER cabling pin description (PDF)"); helpAERCablingUserGuideMenuItem.setToolTipText("Cabling for AER headers"); helpAERCablingUserGuideMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { helpAERCablingUserGuideMenuItemActionPerformed(evt); } }); helpMenu.add(helpAERCablingUserGuideMenuItem); javadocMenuItem.setText("Javadoc (local)"); javadocMenuItem.setToolTipText("Shows Javadoc for classes if it has been built"); javadocMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { javadocMenuItemActionPerformed(evt); } }); helpMenu.add(javadocMenuItem); javadocWebMenuItem.setText("Javadoc (SourceForge snapshot)"); javadocWebMenuItem.setToolTipText("Goes to online snapshot of javadoc"); javadocWebMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { javadocWebMenuItemActionPerformed(evt); } }); helpMenu.add(javadocWebMenuItem); helpMenu.add(jSeparator7); aboutMenuItem.setText("About"); aboutMenuItem.setToolTipText("Version information"); aboutMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { aboutMenuItemActionPerformed(evt); } }); helpMenu.add(aboutMenuItem); menuBar.add(helpMenu); setJMenuBar(menuBar); pack(); }// </editor-fold>//GEN-END:initComponents private void javadocWebMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_javadocWebMenuItemActionPerformed try { BrowserLauncher.openURL(HELP_URL_JAVADOC_WEB); } catch (IOException e) { JOptionPane.showMessageDialog(this, "<html>" + e.getMessage() + "<br>" + HELP_URL_JAVADOC_WEB + " is not available.", "Javadoc not available", JOptionPane.INFORMATION_MESSAGE); } }//GEN-LAST:event_javadocWebMenuItemActionPerformed // volatile boolean playerSliderMousePressed=false; volatile boolean playerSliderWasPaused = false; private void playerSliderMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_playerSliderMouseReleased // playerSliderMousePressed=false; // log.info("playerSliderWasPaused="+playerSliderWasPaused); if (!playerSliderWasPaused) { synchronized (aePlayer) { setDoSingleStepEnabled(false); aePlayer.resume(); // might be in middle of single step in viewLoop, which will just pause again } } }//GEN-LAST:event_playerSliderMouseReleased private void playerSliderMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_playerSliderMousePressed // playerSliderMousePressed=true; playerSliderWasPaused = isPaused(); // log.info("playerSliderWasPaused="+playerSliderWasPaused); }//GEN-LAST:event_playerSliderMousePressed private void resizeLabelMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_resizeLabelMouseExited setCursor(preResizeCursor); }//GEN-LAST:event_resizeLabelMouseExited Cursor preResizeCursor = Cursor.getDefaultCursor(); private void resizeLabelMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_resizeLabelMouseEntered preResizeCursor = getCursor(); setCursor(Cursor.getPredefinedCursor(Cursor.SE_RESIZE_CURSOR)); }//GEN-LAST:event_resizeLabelMouseEntered private void resizeLabelMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_resizeLabelMousePressed oldSize = getSize(); startResizePoint = evt.getPoint(); }//GEN-LAST:event_resizeLabelMousePressed private void resizeLabelMouseDragged(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_resizeLabelMouseDragged Point resizePoint = evt.getPoint(); int widthInc = resizePoint.x - startResizePoint.x; int heightInc = resizePoint.y - startResizePoint.y; setSize(getWidth() + widthInc, getHeight() + heightInc); }//GEN-LAST:event_resizeLabelMouseDragged private void helpRetinaMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_helpRetinaMenuItemActionPerformed try { BrowserLauncher.openURL(HELP_URL_RETINA); } catch (IOException e) { contentMenuItem.setText(e.getMessage()); } }//GEN-LAST:event_helpRetinaMenuItemActionPerformed private void dataWindowMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_dataWindowMenuActionPerformed jaerViewer.globalDataViewer.setVisible(!jaerViewer.globalDataViewer.isVisible()); }//GEN-LAST:event_dataWindowMenuActionPerformed private void serverSocketOptionsMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_serverSocketOptionsMenuItemActionPerformed if (aeServerSocket == null) { log.warning("null aeServerSocket"); JOptionPane.showMessageDialog(this, "No server socket to configure - maybe port is already bound? (Check the output logging)", "No server socket", JOptionPane.WARNING_MESSAGE); return; } AEServerSocketOptionsDialog dlg = new AEServerSocketOptionsDialog(this, true, aeServerSocket); dlg.setVisible(true); int ret = dlg.getReturnStatus(); if (ret != AEServerSocketOptionsDialog.RET_OK) { return; } // TODO change options on server socket and reopen it - presently need to restart Viewer }//GEN-LAST:event_serverSocketOptionsMenuItemActionPerformed private void enableFiltersOnStartupCheckBoxMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_enableFiltersOnStartupCheckBoxMenuItemActionPerformed enableFiltersOnStartup = enableFiltersOnStartupCheckBoxMenuItem.isSelected(); prefs.putBoolean("AEViewer.enableFiltersOnStartup", enableFiltersOnStartup); }//GEN-LAST:event_enableFiltersOnStartupCheckBoxMenuItemActionPerformed private void dontRenderToggleButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_dontRenderToggleButtonActionPerformed if (dontRenderToggleButton.isSelected()) { skipPacketsRenderingNumber = 100; } else { skipPacketsRenderingNumber = 0; } }//GEN-LAST:event_dontRenderToggleButtonActionPerformed void fixSkipPacketsRenderingMenuItems() { skipPacketsRenderingCheckBoxMenuItem.setSelected(skipPacketsRenderingNumber > 0); skipPacketsRenderingCheckBoxMenuItem.setText("Skip rendering packets (skipping " + skipPacketsRenderingNumber + " packets)"); } private void skipPacketsRenderingCheckBoxMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_skipPacketsRenderingCheckBoxMenuItemActionPerformed // come here when user wants to skip rendering except every n packets if (!skipPacketsRenderingCheckBoxMenuItem.isSelected()) { skipPacketsRenderingNumber = 0; prefs.putInt("AEViewer.skipPacketsRenderingNumber", skipPacketsRenderingNumber); fixSkipPacketsRenderingMenuItems(); return; } String s = "Number of packets to skip over between rendering (currently " + skipPacketsRenderingNumber + ")"; boolean gotIt = false; while (!gotIt) { String retString = JOptionPane.showInputDialog(this, s, Integer.toString(skipPacketsRenderingNumber)); if (retString == null) { return; } // cancelled try { skipPacketsRenderingNumber = Integer.parseInt(retString); gotIt = true; } catch (NumberFormatException e) { log.warning(e.toString()); } } prefs.putInt("AEViewer.skipPacketsRenderingNumber", skipPacketsRenderingNumber); fixSkipPacketsRenderingMenuItems(); }//GEN-LAST:event_skipPacketsRenderingCheckBoxMenuItemActionPerformed private void customizeDevicesMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_customizeDevicesMenuItemActionPerformed // log.info("customizing chip classes"); ClassChooserDialog dlg = new ClassChooserDialog(this, AEChip.class, chipClassNames, null); dlg.setVisible(true); int ret = dlg.getReturnStatus(); if (ret == ClassChooserDialog.RET_OK) { chipClassNames = dlg.getList(); putChipClassPrefs(); buildDeviceMenu(); } }//GEN-LAST:event_customizeDevicesMenuItemActionPerformed private void openMulticastInputMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openMulticastInputMenuItemActionPerformed multicastInputEnabled = openMulticastInputMenuItem.isSelected(); if (multicastInputEnabled) { try { aeMulticastInput = new AEMulticastInput(); aeMulticastInput.start(); setPlayMode(PlayMode.REMOTE); } catch (IOException e) { log.warning(e.getMessage()); openMulticastInputMenuItem.setSelected(false); } } else { if (aeMulticastInput != null) { aeMulticastInput.close(); } setPlayMode(PlayMode.WAITING); } }//GEN-LAST:event_openMulticastInputMenuItemActionPerformed private void multicastOutputEnabledCheckBoxMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_multicastOutputEnabledCheckBoxMenuItemActionPerformed multicastOutputEnabled = multicastOutputEnabledCheckBoxMenuItem.isSelected(); if (multicastOutputEnabled) { aeMulticastOutput = new AEMulticastOutput(); } else { if (aeMulticastOutput != null) { aeMulticastOutput.close(); } } }//GEN-LAST:event_multicastOutputEnabledCheckBoxMenuItemActionPerformed // private void spreadInputCheckBoxMenuItemActionPerformed(java.awt.event.ActionEvent evt) { // if(spreadInputCheckBoxMenuItem.isSelected()){ // if(spreadInterface==null){ // spreadInterface=new AESpreadInterface(); // try{ // spreadInterface.connect(); // spreadInputEnabled=true; // setPlayMode(PlayMode.REMOTE); // }catch(Exception e){ // log.warning(e.getMessage()); // spreadInputCheckBoxMenuItem.setSelected(false); // return; // }else{ // setPlayMode(PlayMode.WAITING); // spreadInputEnabled=false; // private void spreadServerCheckBoxMenuItemActionPerformed(java.awt.event.ActionEvent evt) { // if(spreadServerCheckBoxMenuItem.isSelected()){ // try{ // spreadInterface=new AESpreadInterface(); // spreadInterface.connect(); // spreadOutputEnabled=true; // }catch(Exception e){ // log.warning(e.getMessage()); // spreadServerCheckBoxMenuItem.setSelected(false); // return; // }else{ // spreadInterface.disconnect(); // spreadOutputEnabled=false; private void helpAERCablingUserGuideMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_helpAERCablingUserGuideMenuItemActionPerformed try { BrowserLauncher.openURL(HELP_URL_USER_GUIDE_AER_CABLING); } catch (IOException e) { contentMenuItem.setText(e.getMessage()); } }//GEN-LAST:event_helpAERCablingUserGuideMenuItemActionPerformed private void openSocketInputStreamMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openSocketInputStreamMenuItemActionPerformed if (socketInputEnabled) { if (aeSocket != null) { try { aeSocket.close(); log.info("closed " + aeSocket); } catch (IOException e) { e.printStackTrace(); } finally { openSocketInputStreamMenuItem.setText("Open socket input stream"); aeSocket = null; } } socketInputEnabled = false; setPlayMode(PlayMode.WAITING); } else { try { aeSocket = new AESocket(); AESocketOkCancelDialog dlg = new AESocketOkCancelDialog(this, true, aeSocket); dlg.setVisible(true); int ret = dlg.getReturnStatus(); if (ret != AESocketOkCancelDialog.RET_OK) { return; } aeSocket.connect(); setPlayMode(PlayMode.REMOTE); openSocketInputStreamMenuItem.setText("Close socket input stream from " + aeSocket.getHost() + ":" + aeSocket.getPort()); reopenSocketInputStreamMenuItem.setEnabled(true); log.info("opened socket input stream " + aeSocket); socketInputEnabled = true; } catch (Exception e) { log.warning(e.toString()); JOptionPane.showMessageDialog(this, "<html>Couldn't open AESocket input stream: <br>" + e.toString() + "</html>"); } } // if(socketInputStream==null){ // try{ //// socketInputStream=new AEUnicastInput(); // String host=JOptionPane.showInputDialog(this,"Hostname to receive from",socketInputStream.getHost()); // if(host==null) return; // aeSocket=new AESocket(host); //// socketInputStream.setHost(host); //// socketInputStream.start(); // setPlayMode(PlayMode.REMOTE); // openSocketInputStreamMenuItem.setText("Close socket input stream"); // }catch(Exception e){ // e.printStackTrace(); // }else{ // if(aeSocket!=null){ // aeSocket // if(socketInputStream!=null){ // socketInputStream.close(); // socketInputStream=null; // log.info("set socketInputStream to null"); // openSocketInputStreamMenuItem.setText("Open socket input stream"); }//GEN-LAST:event_openSocketInputStreamMenuItemActionPerformed private void logFilteredEventsCheckBoxMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_logFilteredEventsCheckBoxMenuItemActionPerformed setLogFilteredEventsEnabled(logFilteredEventsCheckBoxMenuItem.isSelected()); }//GEN-LAST:event_logFilteredEventsCheckBoxMenuItemActionPerformed private void sequenceMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sequenceMenuItemActionPerformed if (evt.getActionCommand().equals("start")) { float oldScale = chipCanvas.getScale(); AESequencerInterface aemonseq = (AESequencerInterface) chip.getHardwareInterface(); try { if (aemonseq != null && aemonseq instanceof AEMonitorSequencerInterface) { ((AEMonitorSequencerInterface) aemonseq).stopMonitoringSequencing(); } } catch (HardwareInterfaceException e) { e.printStackTrace(); } JFileChooser fileChooser = new JFileChooser(); ChipDataFilePreview preview = new ChipDataFilePreview(fileChooser, chip); // from book swing hacks fileChooser.addPropertyChangeListener(preview); fileChooser.setAccessory(preview); String lastFilePath = prefs.get("AEViewer.lastFile", ""); // get the last folder lastFile = new File(lastFilePath); DATFileFilter datFileFilter = new DATFileFilter(); fileChooser.addChoosableFileFilter(datFileFilter); fileChooser.setCurrentDirectory(lastFile); // sets the working directory of the chooser // boolean wasPaused=isPaused(); // setPaused(true); int retValue = fileChooser.showOpenDialog(this); if (retValue == JFileChooser.APPROVE_OPTION) { lastFile = fileChooser.getSelectedFile(); if (lastFile != null) { recentFiles.addFile(lastFile); } SwingUtilities.invokeLater(new Runnable() { public void run() { sequenceFile(lastFile); } }); } fileChooser = null; // setPaused(false); chipCanvas.setScale(oldScale); } else if (evt.getActionCommand() == "stop") { setPlayMode(PlayMode.LIVE); stopSequencing(); } }//GEN-LAST:event_sequenceMenuItemActionPerformed private void sequenceFile(File file) { try { fileInputStream = new FileInputStream(file); setCurrentFile(file); AEFileInputStream fileAEInputStream = new AEFileInputStream(fileInputStream); fileAEInputStream.setFile(file); fileAEInputStream.setNonMonotonicTimeExceptionsChecked(checkNonMonotonicTimeExceptionsEnabledCheckBoxMenuItem.isSelected()); int numberOfEvents = (int) fileAEInputStream.size(); AEPacketRaw seqPkt = fileAEInputStream.readPacketByNumber(numberOfEvents); if (seqPkt.getNumEvents() < numberOfEvents) { int[] ad = new int[numberOfEvents]; int[] ts = new int[numberOfEvents]; int remainingevents = numberOfEvents; int ind = 0; do { remainingevents = remainingevents - AEFileInputStream.MAX_BUFFER_SIZE_EVENTS; System.arraycopy(seqPkt.getTimestamps(), 0, ts, ind * AEFileInputStream.MAX_BUFFER_SIZE_EVENTS, seqPkt.getNumEvents()); System.arraycopy(seqPkt.getAddresses(), 0, ad, ind * AEFileInputStream.MAX_BUFFER_SIZE_EVENTS, seqPkt.getNumEvents()); seqPkt = fileAEInputStream.readPacketByNumber(remainingevents); ind++; } while (remainingevents > AEFileInputStream.MAX_BUFFER_SIZE_EVENTS); seqPkt = new AEPacketRaw(ad, ts); } // calculate interspike intervals int[] ts = seqPkt.getTimestamps(); int[] isi = new int[seqPkt.getNumEvents()]; isi[0] = ts[0]; for (int i = 1; i < seqPkt.getNumEvents(); i++) { isi[i] = ts[i] - ts[i - 1]; if (isi[i] < 0) { // if (!(ts[i-1]>0 && ts[i]<0)) //if it is not an overflow, it is non-monotonic time, so set isi to zero log.info("non-monotonic time at event " + i + ", set interspike interval to zero"); isi[i] = 0; } } seqPkt.setTimestamps(isi); AESequencerInterface aemonseq = (AESequencerInterface) chip.getHardwareInterface(); setPaused(false); if (aemonseq instanceof AEMonitorSequencerInterface) { ((AEMonitorSequencerInterface) aemonseq).startMonitoringSequencing(seqPkt); } else { ((AESequencerInterface) aemonseq).startSequencing(seqPkt); } aemonseq.setLoopedSequencingEnabled(true); setPlayMode(PlayMode.SEQUENCING); sequenceMenuItem.setActionCommand("stop"); sequenceMenuItem.setText("Stop sequencing data file"); if (!playerControlPanel.isVisible()) { playerControlPanel.setVisible(true); } // playerSlider.setVisible(true); playerSlider.setEnabled(false); // System.gc(); // garbage collect... } catch (Exception e) { e.printStackTrace(); } } private void stopSequencing() { try { if (chip != null && chip.getHardwareInterface() != null) { ((AESequencerInterface) chip.getHardwareInterface()).stopSequencing(); } } catch (HardwareInterfaceException e) { e.printStackTrace(); } sequenceMenuItem.setActionCommand("start"); sequenceMenuItem.setText("Sequence data file..."); playerControlPanel.setVisible(false); // playerSlider.setVisible(true); playerSlider.setEnabled(true); } Dimension oldSize; Point startResizePoint; private void cycleDisplayMethodButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cycleDisplayMethodButtonActionPerformed chipCanvas.cycleDisplayMethod(); }//GEN-LAST:event_cycleDisplayMethodButtonActionPerformed private void unzoomMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_unzoomMenuItemActionPerformed chipCanvas.unzoom(); }//GEN-LAST:event_unzoomMenuItemActionPerformed private void zoomMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_zoomMenuItemActionPerformed chipCanvas.setZoomMode(true); }//GEN-LAST:event_zoomMenuItemActionPerformed private void viewIgnorePolarityCheckBoxMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_viewIgnorePolarityCheckBoxMenuItemActionPerformed chip.getRenderer().setIgnorePolarityEnabled(viewIgnorePolarityCheckBoxMenuItem.isSelected()); }//GEN-LAST:event_viewIgnorePolarityCheckBoxMenuItemActionPerformed private void cypressFX2EEPROMMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cypressFX2EEPROMMenuItemActionPerformed new CypressFX2EEPROM().setVisible(true); }//GEN-LAST:event_cypressFX2EEPROMMenuItemActionPerformed private void loggingSetTimelimitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loggingSetTimelimitMenuItemActionPerformed String ans = JOptionPane.showInputDialog(this, "Enter logging time limit in ms (0 for no limit)", loggingTimeLimit); try { int n = Integer.parseInt(ans); loggingTimeLimit = n; } catch (NumberFormatException e) { Toolkit.getDefaultToolkit().beep(); } }//GEN-LAST:event_loggingSetTimelimitMenuItemActionPerformed private void helpUserGuideMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_helpUserGuideMenuItemActionPerformed try { BrowserLauncher.openURL(HELP_URL_USER_GUIDE_USB2_MINI); } catch (IOException e) { contentMenuItem.setText(e.getMessage()); } }//GEN-LAST:event_helpUserGuideMenuItemActionPerformed private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed // log.info("window closed event, calling stopMe"); stopMe(); }//GEN-LAST:event_formWindowClosed private void javadocMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_javadocMenuItemActionPerformed try { BrowserLauncher.openURL(HELP_URL_JAVADOC); } catch (IOException e) { JOptionPane.showMessageDialog(this, "<html>" + e.getMessage() + "<br>" + HELP_URL_JAVADOC + " is not available.<br>You may need to build the javadoc </html>", "Javadoc not available", JOptionPane.INFORMATION_MESSAGE); } }//GEN-LAST:event_javadocMenuItemActionPerformed private void viewRenderBlankFramesCheckBoxMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_viewRenderBlankFramesCheckBoxMenuItemActionPerformed setRenderBlankFramesEnabled(viewRenderBlankFramesCheckBoxMenuItem.isSelected()); }//GEN-LAST:event_viewRenderBlankFramesCheckBoxMenuItemActionPerformed private void monSeqMissedEventsMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_monSeqMissedEventsMenuItemActionPerformed if (aemon instanceof CypressFX2MonitorSequencer) { CypressFX2MonitorSequencer fx = (CypressFX2MonitorSequencer) aemon; try { JOptionPane.showMessageDialog(this, fx + " missed approximately " + fx.getNumMissedEvents() + " events"); } catch (Exception e) { e.printStackTrace(); aemon.close(); } } }//GEN-LAST:event_monSeqMissedEventsMenuItemActionPerformed volatile boolean doSingleStepEnabled = false; synchronized public void doSingleStep() { // log.info("doSingleStep"); setDoSingleStepEnabled(true); } public void setDoSingleStepEnabled(boolean yes) { doSingleStepEnabled = yes; } synchronized public boolean isSingleStep() { // boolean isSingle=caviarViewer.getPlayer().isSingleStep(); // return isSingle; return doSingleStepEnabled; } synchronized public void singleStepDone() { if (isSingleStep()) { setDoSingleStepEnabled(false); setPaused(true); } // caviarViewer.getPlayer().singleStepDone(); } private void viewSingleStepMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_viewSingleStepMenuItemActionPerformed // setPaused(true); jaerViewer.getPlayer().doSingleStep(this); // viewLoop.doSingleStep=true; // viewLoop.singleStepEnabled=true; // System.out.println("set singleStepEnabled=true, doSingleStep=true"); }//GEN-LAST:event_viewSingleStepMenuItemActionPerformed private void electricalSyncEnabledCheckBoxMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_electricalSyncEnabledCheckBoxMenuItemActionPerformed if (jaerViewer != null) { jaerViewer.setElectricalSyncEnabled(electricalSyncEnabledCheckBoxMenuItem.isSelected()); } }//GEN-LAST:event_electricalSyncEnabledCheckBoxMenuItemActionPerformed private void buildMonSeqMenu() { monSeqMenu.getPopupMenu().setLightWeightPopupEnabled(false); // canvas is heavyweight so we need this to make menu popup show monSeqOperationModeMenu.getPopupMenu().setLightWeightPopupEnabled(false); // canvas is heavyweight so we need this to make menu popup show monSeqOperationModeMenu.setText("MonitorSequencer Operation Mode"); this.monSeqOpMode0.setText("Tick: 1us"); this.monSeqOpMode1.setText("Tick: 0.2us"); this.monSeqMissedEventsMenuItem.setText("Get number of missed events"); } private void enableMonSeqMenu(boolean state) { this.monSeqMenu.setEnabled(state); if (chip.getHardwareInterface() instanceof AEMonitorInterface) { this.monSeqOperationModeMenu.setEnabled(state); this.monSeqOpMode0.setEnabled(state); this.monSeqOpMode1.setEnabled(state); this.monSeqMissedEventsMenuItem.setEnabled(state); this.enableMissedEventsCheckBox.setEnabled(state); } this.sequenceMenuItem.setEnabled(state); } // used to print dt for measuring frequency from playback by using '1' keystrokes class Statistics { JFrame statFrame; JLabel statLabel; int lastTime = 0, thisTime; EngineeringFormat fmt = new EngineeringFormat(); { fmt.precision = 2; } void printStats() { synchronized (aePlayer) { thisTime = aePlayer.getTime(); int dt = lastTime - thisTime; float dtSec = (float) ((float) dt / 1e6f + Float.MIN_VALUE); float freqHz = 1 / dtSec; // System.out.println(String.format("dt=%.2g s, freq=%.2g Hz",dtSec,freqHz)); if (statFrame == null) { statFrame = new JFrame("Statistics"); statLabel = new JLabel(); statLabel.setFont(statLabel.getFont().deriveFont(16f)); statLabel.setToolTipText("Type \"1\" to update interval statistics"); statFrame.getContentPane().setLayout(new BorderLayout()); statFrame.getContentPane().add(statLabel, BorderLayout.CENTER); statFrame.pack(); } String s = " dt=" + fmt.format(dtSec) + "s, freq=" + fmt.format(freqHz) + " Hz "; log.info(s); statLabel.setText(s); statLabel.revalidate(); statFrame.pack(); if (!statFrame.isVisible()) { statFrame.setVisible(true); } requestFocus(); // leave the focus here lastTime = thisTime; } } } Statistics statistics; private void measureTimeMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_measureTimeMenuItemActionPerformed if (statistics == null) { statistics = new Statistics(); } statistics.printStats(); }//GEN-LAST:event_measureTimeMenuItemActionPerformed private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing if (aeServerSocket != null) { try { aeServerSocket.close(); } catch (IOException e) { log.warning(e.toString()); } } if (unicastInput != null) { unicastInput.close(); } if (jaerViewer.getViewers().size() == 1) { log.info("window closing event, only 1 viewer so calling System.exit"); stopMe(); System.exit(0); } else { log.info("window closing event, calling stopMe"); if (filterFrame != null && filterFrame.isVisible()) { filterFrame.dispose(); // close this frame if the window is closed } stopMe(); } }//GEN-LAST:event_formWindowClosing private void newViewerMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newViewerMenuItemActionPerformed new AEViewer(jaerViewer).setVisible(true); }//GEN-LAST:event_newViewerMenuItemActionPerformed private void interfaceMenuMenuSelected(javax.swing.event.MenuEvent evt) {//GEN-FIRST:event_interfaceMenuMenuSelected buildInterfaceMenu(); }//GEN-LAST:event_interfaceMenuMenuSelected private void interfaceMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_interfaceMenuActionPerformed buildInterfaceMenu(); }//GEN-LAST:event_interfaceMenuActionPerformed private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized // handle statistics label font sizing here double fw = getWidth(); if (statisticsLabel == null) { return; } // not realized yet double lw = statisticsLabel.getWidth(); if (fw < 200) { fw = 200; } double r = fw / lw; final double mn = .3, mx = 2.3; if (r < mn) { r = mn; } if (r > mx) { r = mx; } final int minFont = 10, maxFont = 36; // System.out.println("frame/label width="+r); Font f = statisticsLabel.getFont(); int size = f.getSize(); int newsize = (int) Math.floor(size * r); if (newsize < minFont) { newsize = minFont; } if (newsize > maxFont) { newsize = maxFont; } if (size == newsize) { return; } Font nf = f.deriveFont((float) newsize); // System.out.println("old font="+f); // System.out.println("new font="+nf); statisticsLabel.setFont(nf); }//GEN-LAST:event_formComponentResized private void statisticsPanelComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_statisticsPanelComponentResized // statisticsPanel.revalidate(); }//GEN-LAST:event_statisticsPanelComponentResized private void saveImageSequenceMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveImageSequenceMenuItemActionPerformed if (canvasFileWriter.writingMovieEnabled) { canvasFileWriter.stopWritingMovie(); saveImageSequenceMenuItem.setText("Start writing image sequence"); } else { canvasFileWriter.startWritingMovie(); saveImageSequenceMenuItem.setText("Stop writing sequence"); } }//GEN-LAST:event_saveImageSequenceMenuItemActionPerformed CanvasFileWriter canvasFileWriter = new CanvasFileWriter(); private void saveImageMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveImageMenuItemActionPerformed synchronized (chipCanvas) { canvasFileWriter.writeSnapshotImage(); // chipCanvas must be drawn with java (not openGL) for this to work } }//GEN-LAST:event_saveImageMenuItemActionPerformed private void refreshInterfaceMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_refreshInterfaceMenuItemActionPerformed // TODO add your handling code here: }//GEN-LAST:event_refreshInterfaceMenuItemActionPerformed private void toggleMarkCheckBoxMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_toggleMarkCheckBoxMenuItemActionPerformed try { synchronized (getAePlayer()) { if (toggleMarkCheckBoxMenuItem.isSelected()) { getAePlayer().mark(); // Dictionary<Integer,JLabel> dict=new Dictionary<Integer,JLabel>(); Hashtable<Integer, JLabel> markTable = new Hashtable<Integer, JLabel>(); markTable.put(playerSlider.getValue(), new JLabel("^")); playerSlider.setLabelTable(markTable); playerSlider.setPaintLabels(true); } else { getAePlayer().unmark(); playerSlider.setPaintLabels(false); } } } catch (IOException e) { e.printStackTrace(); } }//GEN-LAST:event_toggleMarkCheckBoxMenuItemActionPerformed private void subSampleSizeMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_subSampleSizeMenuItemActionPerformed String ans = JOptionPane.showInputDialog(this, "Enter limit to number of rendered events", renderer.getSubsampleThresholdEventCount()); try { int n = Integer.parseInt(ans); renderer.setSubsampleThresholdEventCount(n); extractor.setSubsampleThresholdEventCount(n); } catch (NumberFormatException e) { Toolkit.getDefaultToolkit().beep(); } }//GEN-LAST:event_subSampleSizeMenuItemActionPerformed private void filtersToggleButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_filtersToggleButtonActionPerformed showFilters(filtersToggleButton.isSelected()); }//GEN-LAST:event_filtersToggleButtonActionPerformed private void biasesToggleButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_biasesToggleButtonActionPerformed showBiasgen(biasesToggleButton.isSelected()); }//GEN-LAST:event_biasesToggleButtonActionPerformed private void imagePanelMouseWheelMoved(java.awt.event.MouseWheelEvent evt) {//GEN-FIRST:event_imagePanelMouseWheelMoved int rotation = evt.getWheelRotation(); renderer.setColorScale(renderer.getColorScale() + rotation); }//GEN-LAST:event_imagePanelMouseWheelMoved private void loggingPlaybackImmediatelyCheckBoxMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loggingPlaybackImmediatelyCheckBoxMenuItemActionPerformed setLoggingPlaybackImmediatelyEnabled(!isLoggingPlaybackImmediatelyEnabled()); }//GEN-LAST:event_loggingPlaybackImmediatelyCheckBoxMenuItemActionPerformed private void togglePlaybackDirectionMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_togglePlaybackDirectionMenuItemActionPerformed getAePlayer().toggleDirection(); }//GEN-LAST:event_togglePlaybackDirectionMenuItemActionPerformed private void flextimePlaybackEnabledCheckBoxMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_flextimePlaybackEnabledCheckBoxMenuItemActionPerformed if (jaerViewer == null) { return; } if (!jaerViewer.isSyncEnabled() || jaerViewer.getViewers().size() == 1) { aePlayer.toggleFlexTime(); } else { JOptionPane.showMessageDialog(this, "Flextime playback doesn't make sense for sychronized viewing"); flextimePlaybackEnabledCheckBoxMenuItem.setSelected(false); } }//GEN-LAST:event_flextimePlaybackEnabledCheckBoxMenuItemActionPerformed private void rewindPlaybackMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rewindPlaybackMenuItemActionPerformed getAePlayer().rewind(); }//GEN-LAST:event_rewindPlaybackMenuItemActionPerformed private void decreasePlaybackSpeedMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_decreasePlaybackSpeedMenuItemActionPerformed getAePlayer().slowDown(); }//GEN-LAST:event_decreasePlaybackSpeedMenuItemActionPerformed private void increasePlaybackSpeedMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_increasePlaybackSpeedMenuItemActionPerformed getAePlayer().speedUp(); }//GEN-LAST:event_increasePlaybackSpeedMenuItemActionPerformed private void autoscaleContrastEnabledCheckBoxMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_autoscaleContrastEnabledCheckBoxMenuItemActionPerformed renderer.setAutoscaleEnabled(!renderer.isAutoscaleEnabled()); ; }//GEN-LAST:event_autoscaleContrastEnabledCheckBoxMenuItemActionPerformed private void acccumulateImageEnabledCheckBoxMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_acccumulateImageEnabledCheckBoxMenuItemActionPerformed renderer.setAccumulateEnabled(!renderer.isAccumulateEnabled()); }//GEN-LAST:event_acccumulateImageEnabledCheckBoxMenuItemActionPerformed private void zeroTimestampsMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_zeroTimestampsMenuItemActionPerformed if (jaerViewer != null && jaerViewer.isSyncEnabled() && !jaerViewer.isElectricalSyncEnabled()) { jaerViewer.zeroTimestamps(); } else { zeroTimestamps(); log.info("zeroing timestamps only on current AEViewer"); } }//GEN-LAST:event_zeroTimestampsMenuItemActionPerformed private void pauseRenderingCheckBoxMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pauseRenderingCheckBoxMenuItemActionPerformed setPaused(!isPaused()); if (!isPaused()) { // viewLoop.singleStepEnabled=false; // System.out.println("pauseRenderingCheckBoxMenuItemActionPerformed: set singleStepEnabled=false"); } }//GEN-LAST:event_pauseRenderingCheckBoxMenuItemActionPerformed private void decreaseFrameRateMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_decreaseFrameRateMenuItemActionPerformed // case KeyEvent.VK_LEFT: // slower setFrameRate(getFrameRate() / 2); // break; // case KeyEvent.VK_RIGHT: //faster // setFrameRate(getFrameRate()*2); // break; }//GEN-LAST:event_decreaseFrameRateMenuItemActionPerformed private void increaseFrameRateMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_increaseFrameRateMenuItemActionPerformed // case KeyEvent.VK_LEFT: // slower // setFrameRate(getFrameRate()/2); // break; // case KeyEvent.VK_RIGHT: //faster setFrameRate(getFrameRate() * 2); // break; }//GEN-LAST:event_increaseFrameRateMenuItemActionPerformed private void decreaseContrastMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_decreaseContrastMenuItemActionPerformed renderer.setColorScale(renderer.getColorScale() + 1); }//GEN-LAST:event_decreaseContrastMenuItemActionPerformed private void increaseContrastMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_increaseContrastMenuItemActionPerformed renderer.setColorScale(renderer.getColorScale() - 1); }//GEN-LAST:event_increaseContrastMenuItemActionPerformed private void cycleColorRenderingMethodMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cycleColorRenderingMethodMenuItemActionPerformed renderer.cycleColorMode(); }//GEN-LAST:event_cycleColorRenderingMethodMenuItemActionPerformed private void subsampleEnabledCheckBoxMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_subsampleEnabledCheckBoxMenuItemActionPerformed chip.setSubSamplingEnabled(subsampleEnabledCheckBoxMenuItem.isSelected()); }//GEN-LAST:event_subsampleEnabledCheckBoxMenuItemActionPerformed private void closeMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_closeMenuItemActionPerformed stopMe(); }//GEN-LAST:event_closeMenuItemActionPerformed private void viewOpenGLEnabledMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_viewOpenGLEnabledMenuItemActionPerformed synchronized (chip.getCanvas()) { setOpenGLRenderingEnabled(viewOpenGLEnabledMenuItem.isSelected()); } }//GEN-LAST:event_viewOpenGLEnabledMenuItemActionPerformed private void viewActiveRenderingEnabledMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_viewActiveRenderingEnabledMenuItemActionPerformed setActiveRenderingEnabled(viewActiveRenderingEnabledMenuItem.isSelected()); }//GEN-LAST:event_viewActiveRenderingEnabledMenuItemActionPerformed void fixDeviceControlMenuItems() { // log.info("fixing device control menu"); int k = controlMenu.getMenuComponentCount(); if (aemon == null || (!(aemon instanceof ReaderBufferControl) && !aemon.isOpen())) { for (int i = 0; i < k; i++) { if (controlMenu.getMenuComponent(i) instanceof JMenuItem) { ((JMenuItem) controlMenu.getMenuComponent(i)).setEnabled(false); } } } else if (aemon != null && (aemon instanceof ReaderBufferControl) && aemon.isOpen()) { ReaderBufferControl readerControl = (ReaderBufferControl) aemon; try { CypressFX2 fx2 = (CypressFX2) aemon; PropertyChangeSupport support = fx2.getSupport(); // propertyChange method in this file deals with these events if (!support.hasListeners("readerStarted")) { support.addPropertyChangeListener("readerStarted", this); // when the reader starts running, we get called back to fix device control menu } } catch (ClassCastException e) { log.warning("tried to add " + aemon + " as listener for reader start/stop in device control menu but this is probably a stereo interface"); } if (readerControl == null) { return; } int n = readerControl.getNumBuffers(); int f = readerControl.getFifoSize(); decreaseNumBuffersMenuItem.setText("Decrease num buffers to " + (n - 1)); increaseNumBuffersMenuItem.setText("Increase num buffers to " + (n + 1)); decreaseBufferSizeMenuItem.setText("Decrease FIFO size to " + (f / 2)); increaseBufferSizeMenuItem.setText("Increase FIFO size to " + (f * 2)); for (int i = 0; i < k; i++) { if (controlMenu.getMenuComponent(i) instanceof JMenuItem) { ((JMenuItem) controlMenu.getMenuComponent(i)).setEnabled(true); } } } cypressFX2EEPROMMenuItem.setEnabled(true); // always set the true to be able to launch utility even if the device is not a retina if (aemon != null && (aemon instanceof HasUpdatableFirmware)) { updateFirmwareMenuItem.setEnabled(true); } else { updateFirmwareMenuItem.setEnabled(false); } } private void decreaseNumBuffersMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_decreaseNumBuffersMenuItemActionPerformed if (aemon != null && aemon instanceof ReaderBufferControl && aemon.isOpen()) { ReaderBufferControl reader = (ReaderBufferControl) aemon; int n = reader.getNumBuffers() - 1; if (n < 1) { n = 1; } reader.setNumBuffers(n); fixDeviceControlMenuItems(); } }//GEN-LAST:event_decreaseNumBuffersMenuItemActionPerformed private void increaseNumBuffersMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_increaseNumBuffersMenuItemActionPerformed if (aemon != null && aemon instanceof ReaderBufferControl && aemon.isOpen()) { ReaderBufferControl reader = (ReaderBufferControl) aemon; int n = reader.getNumBuffers() + 1; reader.setNumBuffers(n); fixDeviceControlMenuItems(); } }//GEN-LAST:event_increaseNumBuffersMenuItemActionPerformed private void decreaseBufferSizeMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_decreaseBufferSizeMenuItemActionPerformed if (aemon != null && aemon instanceof ReaderBufferControl && aemon.isOpen()) { ReaderBufferControl reader = (ReaderBufferControl) aemon; int n = reader.getFifoSize() / 2; reader.setFifoSize(n); fixDeviceControlMenuItems(); } }//GEN-LAST:event_decreaseBufferSizeMenuItemActionPerformed private void increaseBufferSizeMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_increaseBufferSizeMenuItemActionPerformed if (aemon != null && aemon instanceof ReaderBufferControl && aemon.isOpen()) { ReaderBufferControl reader = (ReaderBufferControl) aemon; int n = reader.getFifoSize() * 2; reader.setFifoSize(n); fixDeviceControlMenuItems(); } }//GEN-LAST:event_increaseBufferSizeMenuItemActionPerformed private void viewFiltersMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_viewFiltersMenuItemActionPerformed showFilters(true); }//GEN-LAST:event_viewFiltersMenuItemActionPerformed private void viewBiasesMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_viewBiasesMenuItemActionPerformed showBiasgen(true); }//GEN-LAST:event_viewBiasesMenuItemActionPerformed //avoid stateChanged events from slider that is set by player volatile boolean sliderDontProcess = false; /** messages come back here from e.g. programmatic state changes, like a new aePlayer file posiiton. * This methods sets the GUI components to a consistent state, using a flag to tell the slider that it has not been set by * a user mouse action */ public void propertyChange(PropertyChangeEvent evt) { if (evt.getPropertyName().equals("position")) { // comes from AEFileInputStream // System.out.println("slider property change new val="+evt.getNewValue()); sliderDontProcess = true; // note this cool semaphore/flag trick to avoid processing the // event generated when we programmatically set the slider position here playerSlider.setValue(Math.round(aePlayer.getFractionalPosition() * playerSlider.getMaximum())); } else if (evt.getPropertyName().equals("readerStarted")) { // comes from hardware interface AEReader thread // log.info("AEViewer.propertyChange: AEReader started, fixing device control menu"); // cypress reader started, can set device control for cypress usbio reader thread fixDeviceControlMenuItems(); } } private void playerSliderStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_playerSliderStateChanged if (sliderDontProcess) { sliderDontProcess = false; // to avoid player callbacks generating more AWT events return; } float fracPos = (float) playerSlider.getValue() / (playerSlider.getMaximum()); synchronized (aePlayer) { try { int oldtime = aePlayer.getAEInputStream().getMostRecentTimestamp(); aePlayer.setFractionalPosition(fracPos); // sets position in events int time = aePlayer.getAEInputStream().getMostRecentTimestamp(); aePlayer.getAEInputStream().setCurrentStartTimestamp(time); // log.info(this+" slider set time to "+time); if (jaerViewer.getViewers().size() > 1) { if (time < oldtime) { // we need to set position in all viewers so that we catch up to present desired time AEPlayerInterface p; AEFileInputStream is; try { for (AEViewer v : jaerViewer.getViewers()) { if (true) { p = v.aePlayer; // we want local play here! is = p.getAEInputStream(); if (is != null) { is.rewind(); } else { log.warning("null ae input stream on reposition"); } } } jaerViewer.getPlayer().setTime(time); } catch (Exception e) { e.printStackTrace(); } } } } catch (IllegalArgumentException e) { e.printStackTrace(); } jaerViewer.getPlayer().doSingleStep(this); // System.out.println("playerSlider state changed new pos="+pos); } }//GEN-LAST:event_playerSliderStateChanged private void contentMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_contentMenuItemActionPerformed try { BrowserLauncher.openURL(HELP_URL_USER_GUIDE); } catch (IOException e) { contentMenuItem.setText(e.getMessage()); } }//GEN-LAST:event_contentMenuItemActionPerformed private void aboutMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_aboutMenuItemActionPerformed new AEViewerAboutDialog(new javax.swing.JFrame(), true).setVisible(true); }//GEN-LAST:event_aboutMenuItemActionPerformed private void openMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openMenuItemActionPerformed getAePlayer().openAEInputFileDialog(); }//GEN-LAST:event_openMenuItemActionPerformed void showFilters(boolean yes) { if (yes && !filterFrameBuilt) { filterFrameBuilt = true; filterFrame = new FilterFrame(chip); filterFrame.addWindowListener(new WindowAdapter() { public void windowClosed(WindowEvent e) { // log.info(e.toString()); filtersToggleButton.setSelected(false); } }); } if (filterFrame != null) { filterFrame.setVisible(yes); } filtersToggleButton.setSelected(yes); } void showBiasgen(final boolean yes) { if (chip == null) { if (yes) { log.warning("null chip, can't try to show biasgen"); } // only show warning if trying to show biasgen for null chip return; } SwingUtilities.invokeLater(new Runnable() { public void run() { if (chip.getBiasgen() == null) { // this chip has no biasgen - but it won't have one until HW interface is opened for it successfully if (biasgenFrame != null) { biasgenFrame.dispose(); } // biasesToggleButton.setEnabled(false); // chip don't have biasgen until it has HW interface, which it doesn't at first.... return; } else { biasesToggleButton.setEnabled(true); viewBiasesMenuItem.setEnabled(true); } if (biasgen != chip.getBiasgen()) { // biasgen changed if (biasgenFrame != null) { biasgenFrame.dispose(); } biasgenFrame = new BiasgenFrame(chip); biasgenFrame.addWindowListener(new WindowAdapter() { public void windowClosed(WindowEvent e) { // log.info(e.toString()); biasesToggleButton.setSelected(false); } }); } if (biasgenFrame != null) { biasgenFrame.setVisible(yes); } biasesToggleButton.setSelected(yes); biasgen = chip.getBiasgen(); } }); } synchronized public void toggleLogging() { if (jaerViewer != null && jaerViewer.isSyncEnabled() && jaerViewer.getViewers().size() > 1) { jaerViewer.toggleSynchronizedLogging(); } else { if (loggingEnabled) { stopLogging(); } else { startLogging(); } } // if(loggingButton.isSelected()){ // if(caviarViewer!=null && caviarViewer.isSyncEnabled() ) caviarViewer.startSynchronizedLogging(); else startLogging(); // }else{ // if(caviarViewer!=null && caviarViewer.isSyncEnabled()) caviarViewer.stopSynchronizedLogging(); else stopLogging(); } void fixLoggingControls() { // System.out.println("fixing logging controls, loggingEnabled="+loggingEnabled); if ((playMode != PlayMode.REMOTE) && (aemon == null || (aemon != null && !aemon.isOpen())) && playMode != playMode.PLAYBACK) { // we can log from live input or from playing file (e.g. after refiltering it) or we can log network data // TODO: not ideal logic here, too confusing loggingButton.setEnabled(false); loggingMenuItem.setEnabled(false); return; } else { loggingButton.setEnabled(true); loggingMenuItem.setEnabled(true); } if (!loggingEnabled && playMode == PlayMode.PLAYBACK) { loggingButton.setText("Start Re-logging"); loggingMenuItem.setText("Start re-logging data"); } else if (loggingEnabled) { loggingButton.setText("Stop logging"); loggingButton.setSelected(true); loggingMenuItem.setText("Stop logging data"); } else { loggingButton.setText("Start logging"); loggingButton.setSelected(false); loggingMenuItem.setText("Start logging data"); } } public void openLoggingFolderWindow() { String osName = System.getProperty("os.name"); if (osName == null) { log.warning("no OS name property, cannot open browser"); return; } String curDir = System.getProperty("user.dir"); // log.info("opening folder window for folder "+curDir); if (osName.startsWith("Windows")) { try { Runtime.getRuntime().exec("explorer.exe " + curDir); } catch (IOException e) { log.warning(e.getMessage()); } } else if (System.getProperty("os.name").indexOf("Linux") != -1) { log.warning("cannot open linux folder browsing window"); } } synchronized public File startLogging() { // if(playMode!=PlayMode.LIVE) return null; String dateString = AEDataFile.DATE_FORMAT.format(new Date()); String className = chip.getClass().getSimpleName(); int suffixNumber = 0; boolean suceeded = false; String filename; do { // log files to tmp folder initially, later user will move or delete file on end of logging filename = lastLoggingFolder + File.separator + className + "-" + dateString + "-" + suffixNumber + AEDataFile.DATA_FILE_EXTENSION; loggingFile = new File(filename); if (!loggingFile.isFile()) { suceeded = true; } } while (suceeded == false && suffixNumber++ <= 5); if (suceeded == false) { System.err.println("AEViewer.startLogging(): could not open a unigue new file for logging after trying up to " + filename); return null; } try { loggingOutputStream = new AEFileOutputStream(new BufferedOutputStream(new FileOutputStream(loggingFile))); loggingEnabled = true; log.info("starting logging at " + dateString); setCurrentFile(loggingFile); loggingEnabled = true; fixLoggingControls(); if (loggingTimeLimit > 0) { loggingStartTime = System.currentTimeMillis(); } // aemon.resetTimestamps(); } catch (FileNotFoundException e) { loggingFile = null; e.printStackTrace(); } return loggingFile; } /** Stops logging and opens file dialog for where to save file. */ synchronized public File stopLogging() { // the file has already been logged somewhere with a timestamped name, what this method does is // to move the already logged file to a possibly different location with a new name, or if cancel is hit, // to delete it. if (loggingEnabled) { if (loggingButton.isSelected()) { loggingButton.setSelected(false); } loggingButton.setText("Start logging"); loggingMenuItem.setText("Start logging data"); try { log.info("stopping logging at " + AEDataFile.DATE_FORMAT.format(new Date())); synchronized (loggingOutputStream) { loggingEnabled = false; loggingOutputStream.close(); } // if jaer viewer is logging synchronized data files, then just save the file where it was logged originally if (jaerViewer.getNumViewers() == 1) { JFileChooser chooser = new JFileChooser(); chooser.setCurrentDirectory(lastLoggingFolder); chooser.setFileFilter(new DATFileFilter()); chooser.setDialogTitle("Save logged data"); String fn = loggingFile.getName(); // System.out.println("fn="+fn); // strip off .dat to make it easier to add comment to filename String base = fn.substring(0, fn.lastIndexOf(AEDataFile.DATA_FILE_EXTENSION)); // System.out.println("base="+base); // we'll add the extension back later chooser.setSelectedFile(new File(base)); // chooser.setAccessory(new ResetFileButton(base,chooser)); chooser.setDialogType(JFileChooser.SAVE_DIALOG); chooser.setMultiSelectionEnabled(false); // Component[] comps=chooser.getComponents(); // for(Component c:comps){ // if(c.getName().equals("buttonPanel")){ // ((JPanel)c).add(new ResetFileButton(base,chooser)); boolean savedIt = false; do { // clear the text input buffer to prevent multiply typed characters from destroying proposed datetimestamped filename int retValue = chooser.showSaveDialog(AEViewer.this); if (retValue == JFileChooser.APPROVE_OPTION) { File newFile = chooser.getSelectedFile(); // make sure filename ends with .dat if (!newFile.getName().endsWith(AEDataFile.DATA_FILE_EXTENSION)) { newFile = new File(newFile.getCanonicalPath() + AEDataFile.DATA_FILE_EXTENSION); } // we'll rename the logged data file to the selection boolean renamed = loggingFile.renameTo(newFile); if (renamed) { // if successful, cool, save persistence savedIt = true; lastLoggingFolder = chooser.getCurrentDirectory(); prefs.put("AEViewer.lastLoggingFolder", lastLoggingFolder.getCanonicalPath()); recentFiles.addFile(newFile); loggingFile = newFile; // so that we play it back if it was saved and playback immediately is selected } else { // confirm overwrite int overwrite = JOptionPane.showConfirmDialog(chooser, "Overwrite file?", "Overwrite warning", JOptionPane.WARNING_MESSAGE, JOptionPane.OK_CANCEL_OPTION); if (overwrite == JOptionPane.OK_OPTION) { // we need to delete the file boolean deletedOld = newFile.delete(); if (deletedOld) { savedIt = loggingFile.renameTo(newFile); } } else { chooser.setDialogTitle("Couldn't save file there, try again"); } } } else { // user hit cancel, delete logged data boolean deleted = loggingFile.delete(); if (deleted) { log.info("Deleted temporary logging file " + loggingFile); } else { log.warning("couldn't delete temporary logging file " + loggingFile); } savedIt = true; } } while (savedIt == false); // keep trying until user is happy (unless they deleted some crucial data!) } } catch (IOException e) { e.printStackTrace(); } if (isLoggingPlaybackImmediatelyEnabled()) { try { getAePlayer().startPlayback(loggingFile); } catch (FileNotFoundException e) { e.printStackTrace(); } } loggingEnabled = false; } fixLoggingControls(); return loggingFile; } // doesn't actually reset the test in the dialog' class ResetFileButton extends JButton { String fn; ResetFileButton(final String fn, final JFileChooser chooser) { this.fn = fn; setText("Reset filename"); addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println("reset file"); chooser.setSelectedFile(new File(fn)); } }); } } public String toString() { return getTitle(); } private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitMenuItemActionPerformed // System.exit(0); stopMe(); try { Thread.currentThread().sleep(100); } catch (InterruptedException e) { } if (aemon != null && aemon.isOpen()) { aemon.close(); } System.exit(0); }//GEN-LAST:event_exitMenuItemActionPerformed private void changeAEBufferSizeMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_changeAEBufferSizeMenuItemActionPerformed if (aemon == null) { JOptionPane.showMessageDialog(this, "No hardware interface open, can't set size", "Can't set buffer size", JOptionPane.WARNING_MESSAGE); return; } String ans = JOptionPane.showInputDialog(this, "Enter size of render/capture exchange buffer in events", aemon.getAEBufferSize()); try { int n = Integer.parseInt(ans); aemon.setAEBufferSize(n); } catch (NumberFormatException e) { Toolkit.getDefaultToolkit().beep(); } }//GEN-LAST:event_changeAEBufferSizeMenuItemActionPerformed private void openUnicastInputMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openUnicastInputMenuItemActionPerformed if (unicastInputEnabled) { if (unicastInput != null) { unicastInput.close(); log.info("closed " + unicastInput); openUnicastInputMenuItem.setText("Open unicast UDP input..."); unicastInput = null; } unicastInputEnabled = false; setPlayMode(PlayMode.WAITING); } else { try { unicastInput = new AEUnicastInput(); AEUnicastDialog dlg = new AEUnicastDialog(this, true, unicastInput); dlg.setVisible(true); int ret = dlg.getReturnStatus(); if (ret != AEUnicastDialog.RET_OK) { return; } setPlayMode(PlayMode.REMOTE); openUnicastInputMenuItem.setText("Close unicast input from " + unicastInput.getHost() + ":" + unicastInput.getPort()); log.info("opened unicast input " + unicastInput); unicastInputEnabled = true; unicastInput.start(); } catch (Exception e) { log.warning(e.toString()); JOptionPane.showMessageDialog(this, "<html>Couldn't open AEUnicastInput input: <br>" + e.toString() + "</html>"); } } }//GEN-LAST:event_openUnicastInputMenuItemActionPerformed private void unicastOutputEnabledCheckBoxMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_unicastOutputEnabledCheckBoxMenuItemActionPerformed if (unicastOutputEnabled) { if (unicastOutput != null) { unicastOutput.close(); log.info("closed " + unicastOutput); unicastOutput = null; } unicastOutputEnabled = false; setPlayMode(PlayMode.WAITING); } else { try { unicastOutput = new AEUnicastOutput(); AEUnicastDialog dlg = new AEUnicastDialog(this, true, unicastOutput); dlg.setVisible(true); int ret = dlg.getReturnStatus(); if (ret != AEUnicastDialog.RET_OK) { return; } log.info("opened unicast output " + unicastOutput); unicastOutputEnabled = true; } catch (Exception e) { log.warning(e.toString()); JOptionPane.showMessageDialog(this, "<html>Couldn't open AEUnicastOutput: <br>" + e.toString() + "</html>"); } } }//GEN-LAST:event_unicastOutputEnabledCheckBoxMenuItemActionPerformed private void updateFirmwareMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_updateFirmwareMenuItemActionPerformed if (aemon == null) { return; } if (!(aemon instanceof HasUpdatableFirmware)) { JOptionPane.showMessageDialog(this, "Device does not have updatable firmware", "Firmware update failed", JOptionPane.WARNING_MESSAGE); return; } int DID = aemon.getDID(); int ret = JOptionPane.showConfirmDialog(this, "Current firmware device ID=" + DID + ": Are you sure you want to update the firmware?", "Really update?", JOptionPane.YES_NO_OPTION); if (!(ret == JOptionPane.YES_OPTION)) { return; } try { HasUpdatableFirmware d = (HasUpdatableFirmware) aemon; setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); d.updateFirmware(); setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); JOptionPane.showMessageDialog(this, "Update successful - unplug and replug the device to activate new firmware", "Firmware update complete", JOptionPane.INFORMATION_MESSAGE); } catch (Exception e) { JOptionPane.showMessageDialog(this, "Update failed: " + e.toString(), "Firmware update failed", JOptionPane.WARNING_MESSAGE); } finally { setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } }//GEN-LAST:event_updateFirmwareMenuItemActionPerformed private void monSeqOpMode0ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_monSeqOpMode0ActionPerformed if (aemon instanceof CypressFX2MonitorSequencer) { CypressFX2MonitorSequencer fx = (CypressFX2MonitorSequencer) aemon; try { fx.setOperationMode(0); JOptionPane.showMessageDialog(this, "Timestamp tick set to " + fx.getOperationMode() + " us."); } catch (Exception e) { e.printStackTrace(); aemon.close(); } } }//GEN-LAST:event_monSeqOpMode0ActionPerformed private void monSeqOpMode1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_monSeqOpMode1ActionPerformed if (aemon instanceof CypressFX2MonitorSequencer) { CypressFX2MonitorSequencer fx = (CypressFX2MonitorSequencer) aemon; try { fx.setOperationMode(1); JOptionPane.showMessageDialog(this, "Timestamp tick set to " + fx.getOperationMode() + " us. Note that jAER will treat the ticks as 1us anyway."); } catch (Exception e) { e.printStackTrace(); aemon.close(); } } }//GEN-LAST:event_monSeqOpMode1ActionPerformed private void enableMissedEventsCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_enableMissedEventsCheckBoxActionPerformed if (aemon instanceof CypressFX2MonitorSequencer) { CypressFX2MonitorSequencer fx = (CypressFX2MonitorSequencer) aemon; try { fx.enableMissedEvents(enableMissedEventsCheckBox.getState()); // JOptionPane.showMessageDialog(this, "Timestamp tick set to " + fx.getOperationMode() + " us. Note that jAER will treat the ticks as 1us anyway."); } catch (Exception e) { e.printStackTrace(); aemon.close(); } } }//GEN-LAST:event_enableMissedEventsCheckBoxActionPerformed private void calibrationStartStopActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_calibrationStartStopActionPerformed if (renderer instanceof AdaptiveIntensityRenderer) { ((AdaptiveIntensityRenderer) renderer).setCalibrationInProgress(!((AdaptiveIntensityRenderer) renderer).isCalibrationInProgress()); if (((AdaptiveIntensityRenderer) renderer).isCalibrationInProgress()) { calibrationStartStop.setText("Stop Calibration"); } else { calibrationStartStop.setText("Start Calibration"); } } }//GEN-LAST:event_calibrationStartStopActionPerformed private void reopenSocketInputStreamMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_reopenSocketInputStreamMenuItemActionPerformed log.info("closing and reopening socket " + aeSocket); if (aeSocket != null) { try { aeSocket.close(); } catch (Exception e) { log.warning("closing existing socket: caught " + e); } } try { aeSocket = new AESocket(); aeSocket.connect(); setPlayMode(PlayMode.REMOTE); openSocketInputStreamMenuItem.setText("Close socket input stream from " + aeSocket.getHost() + ":" + aeSocket.getPort()); log.info("opened socket input stream " + aeSocket); socketInputEnabled = true; } catch (Exception e) { JOptionPane.showMessageDialog(this, "Exception reopening socket: " + e, "AESocket Exception", JOptionPane.WARNING_MESSAGE); } }//GEN-LAST:event_reopenSocketInputStreamMenuItemActionPerformed public int getFrameRate() { return frameRater.getDesiredFPS(); } public void setFrameRate(int renderDesiredFrameRateHz) { frameRater.setDesiredFPS(renderDesiredFrameRateHz); } public boolean isPaused() { return jaerViewer.getPlayer().isPaused(); } /** sets paused. If viewing is synchronized, then all viwewers will be paused. *@param paused true to pause */ public void setPaused(boolean paused) { jaerViewer.getPlayer().setPaused(paused); // log.info("paused="+paused); } public boolean isActiveRenderingEnabled() { return activeRenderingEnabled; } public void setActiveRenderingEnabled(boolean activeRenderingEnabled) { this.activeRenderingEnabled = activeRenderingEnabled; prefs.putBoolean("AEViewer.activeRenderingEnabled", activeRenderingEnabled); } public boolean isOpenGLRenderingEnabled() { return openGLRenderingEnabled; } public void setOpenGLRenderingEnabled(boolean openGLRenderingEnabled) { this.openGLRenderingEnabled = openGLRenderingEnabled; getChip().getCanvas().setOpenGLEnabled(openGLRenderingEnabled); prefs.putBoolean("AEViewer.openGLRenderingEnabled", openGLRenderingEnabled); // makeCanvas(); } // drag and drop data file onto frame to play it // Called while a drag operation is ongoing, when the mouse pointer enters the operable part of the drop site for the DropTarget registered with this listener. public void dragEnter(DropTargetDragEvent dtde) { Transferable transferable = dtde.getTransferable(); try { if (transferable.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) { java.util.List<File> files = (java.util.List<File>) transferable.getTransferData(DataFlavor.javaFileListFlavor); for (File f : files) { if (f.getName().endsWith(AEDataFile.DATA_FILE_EXTENSION) || f.getName().endsWith(AEDataFile.INDEX_FILE_EXTENSION)) { draggedFile = f; } else { draggedFile = null; } } // System.out.println("AEViewer.dragEnter(): draqged file="+draggedFile); } } catch (UnsupportedFlavorException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } // Called while a drag operation is ongoing, when the mouse pointer has exited the operable part of the drop site for the DropTarget registered with this listener. public void dragExit(DropTargetEvent dte) { draggedFile = null; } // Called when a drag operation is ongoing, while the mouse pointer is still over the operable part of the drop site for the DropTarget registered with this listener. public void dragOver(DropTargetDragEvent dtde) { } // Called when the drag operation has terminated with a drop on the operable part of the drop site for the DropTarget registered with this listener. public void drop(DropTargetDropEvent dtde) { if (draggedFile != null) { // log.info("AEViewer.drop(): opening file "+draggedFile); try { recentFiles.addFile(draggedFile); aePlayer.startPlayback(draggedFile); } catch (FileNotFoundException e) { e.printStackTrace(); } } } // Called if the user has modified the current drop gesture. public void dropActionChanged(DropTargetDragEvent dtde) { } public boolean isLoggingPlaybackImmediatelyEnabled() { return loggingPlaybackImmediatelyEnabled; } public void setLoggingPlaybackImmediatelyEnabled(boolean loggingPlaybackImmediatelyEnabled) { this.loggingPlaybackImmediatelyEnabled = loggingPlaybackImmediatelyEnabled; prefs.putBoolean("AEViewer.loggingPlaybackImmediatelyEnabled", loggingPlaybackImmediatelyEnabled); } /** @return the chip we are displaying */ public AEChip getChip() { return chip; } public void setChip(AEChip chip) { this.chip = chip; } public boolean isRenderBlankFramesEnabled() { return renderBlankFramesEnabled; } public void setRenderBlankFramesEnabled(boolean renderBlankFramesEnabled) { this.renderBlankFramesEnabled = renderBlankFramesEnabled; prefs.putBoolean("AEViewer.renderBlankFramesEnabled", renderBlankFramesEnabled); // log.info("renderBlankFramesEnabled="+renderBlankFramesEnabled); } public javax.swing.JMenu getFileMenu() { return fileMenu; } /** used in CaviarViewer to control sync'ed logging */ public javax.swing.JMenuItem getLoggingMenuItem() { return loggingMenuItem; } public void setLoggingMenuItem(javax.swing.JMenuItem loggingMenuItem) { this.loggingMenuItem = loggingMenuItem; } /** this toggle button is used in CaviarViewer to assign an action to start and stop logging for (possibly) all viewers */ public javax.swing.JToggleButton getLoggingButton() { return loggingButton; } public void setLoggingButton(javax.swing.JToggleButton b) { this.loggingButton = b; } public JCheckBoxMenuItem getSyncEnabledCheckBoxMenuItem() { return syncEnabledCheckBoxMenuItem; } public void setSyncEnabledCheckBoxMenuItem(javax.swing.JCheckBoxMenuItem syncEnabledCheckBoxMenuItem) { this.syncEnabledCheckBoxMenuItem = syncEnabledCheckBoxMenuItem; } /** @return the local player, unless we are part of a synchronized playback gruop */ public AEPlayerInterface getAePlayer() { if (jaerViewer == null || !jaerViewer.isSyncEnabled() || jaerViewer.getViewers().size() == 1) { return aePlayer; } return jaerViewer.getPlayer(); } public javax.swing.JCheckBoxMenuItem getElectricalSyncEnabledCheckBoxMenuItem() { return electricalSyncEnabledCheckBoxMenuItem; } /** returns the playing mode * @return the mode */ public PlayMode getPlayMode() { return playMode; } /** Sets mode, LIVE, PLAYBACK, WAITING, etc, sets window title, and fires property change event @param playMode the new play mode */ public void setPlayMode(PlayMode playMode) { // there can be a race condition where user tries to open file, this sets // playMode to PLAYBACK but run() method in ViewLoop sets it back to WAITING String oldmode = playMode.toString(); this.playMode = playMode; // log.info("set playMode="+playMode); setTitleAccordingToState(); fixLoggingControls(); getSupport().firePropertyChange("playmode", oldmode, playMode.toString()); // won't fire if old and new are the same, // e.g. playing a file and then start playing a new one } public boolean isLogFilteredEventsEnabled() { return logFilteredEventsEnabled; } public void setLogFilteredEventsEnabled(boolean logFilteredEventsEnabled) { // log.info("logFilteredEventsEnabled="+logFilteredEventsEnabled); this.logFilteredEventsEnabled = logFilteredEventsEnabled; prefs.putBoolean("AEViewer.logFilteredEventsEnabled", logFilteredEventsEnabled); logFilteredEventsCheckBoxMenuItem.setSelected(logFilteredEventsEnabled); } public JAERViewer getJaerViewer() { return jaerViewer; } public void setJaerViewer(JAERViewer jaerViewer) { this.jaerViewer = jaerViewer; } /** AEViewer makes a ServerSocket that accepts incoming connections. A connecting client gets served the events being rendered. @return the server socket. This holds the client socket. */ public AEServerSocket getAeServerSocket() { return aeServerSocket; } /** If we have opened a socket to a server of events, then this is it @return the input socket */ public AESocket getAeSocket() { return aeSocket; } /** gets the RecentFiles handler for use, e.g. in storing sychronized logging index files @return refernce to RecentFiles object */ public RecentFiles getRecentFiles() { return recentFiles; } /** AEViewer supports property change events. See the class description for supported events @return the support */ public PropertyChangeSupport getSupport() { return support; } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JMenuItem aboutMenuItem; private javax.swing.JCheckBoxMenuItem acccumulateImageEnabledCheckBoxMenuItem; private javax.swing.JCheckBoxMenuItem autoscaleContrastEnabledCheckBoxMenuItem; private javax.swing.JToggleButton biasesToggleButton; private javax.swing.JPanel bottomPanel; private javax.swing.JPanel buttonsPanel; private javax.swing.JMenuItem calibrationStartStop; private javax.swing.JMenuItem changeAEBufferSizeMenuItem; private javax.swing.JCheckBoxMenuItem checkNonMonotonicTimeExceptionsEnabledCheckBoxMenuItem; private javax.swing.JMenuItem closeMenuItem; private javax.swing.JMenuItem contentMenuItem; private javax.swing.JMenu controlMenu; private javax.swing.JMenuItem copyMenuItem; private javax.swing.JMenuItem customizeDevicesMenuItem; private javax.swing.JMenuItem cutMenuItem; private javax.swing.JMenuItem cycleColorRenderingMethodMenuItem; private javax.swing.JMenuItem cycleDisplayMethodButton; private javax.swing.JMenuItem cypressFX2EEPROMMenuItem; private javax.swing.JMenuItem dataWindowMenu; private javax.swing.JMenuItem decreaseBufferSizeMenuItem; private javax.swing.JMenuItem decreaseContrastMenuItem; private javax.swing.JMenuItem decreaseFrameRateMenuItem; private javax.swing.JMenuItem decreaseNumBuffersMenuItem; private javax.swing.JMenuItem decreasePlaybackSpeedMenuItem; private javax.swing.JMenu deviceMenu; private javax.swing.JSeparator deviceMenuSpparator; private javax.swing.JMenu displayMethodMenu; private javax.swing.JToggleButton dontRenderToggleButton; private javax.swing.JMenu editMenu; private javax.swing.JCheckBoxMenuItem electricalSyncEnabledCheckBoxMenuItem; private javax.swing.JCheckBoxMenuItem enableFiltersOnStartupCheckBoxMenuItem; private javax.swing.JCheckBoxMenuItem enableMissedEventsCheckBox; private javax.swing.JMenuItem exitMenuItem; private javax.swing.JSeparator exitSeperator; private javax.swing.JMenu fileMenu; private javax.swing.JMenu filtersSubMenu; private javax.swing.JToggleButton filtersToggleButton; private javax.swing.JCheckBoxMenuItem flextimePlaybackEnabledCheckBoxMenuItem; private javax.swing.JMenu graphicsSubMenu; private javax.swing.JMenuItem helpAERCablingUserGuideMenuItem; private javax.swing.JMenu helpMenu; private javax.swing.JMenuItem helpRetinaMenuItem; private javax.swing.JMenuItem helpUserGuideMenuItem; private javax.swing.JPanel imagePanel; private javax.swing.JMenuItem increaseBufferSizeMenuItem; private javax.swing.JMenuItem increaseContrastMenuItem; private javax.swing.JMenuItem increaseFrameRateMenuItem; private javax.swing.JMenuItem increaseNumBuffersMenuItem; private javax.swing.JMenuItem increasePlaybackSpeedMenuItem; private javax.swing.JMenu interfaceMenu; private javax.swing.JProgressBar jProgressBar1; private javax.swing.JSeparator jSeparator1; private javax.swing.JSeparator jSeparator10; private javax.swing.JSeparator jSeparator11; private javax.swing.JSeparator jSeparator12; private javax.swing.JSeparator jSeparator13; private javax.swing.JSeparator jSeparator14; private javax.swing.JSeparator jSeparator15; private javax.swing.JSeparator jSeparator16; private javax.swing.JSeparator jSeparator2; private javax.swing.JSeparator jSeparator3; private javax.swing.JSeparator jSeparator4; private javax.swing.JSeparator jSeparator5; private javax.swing.JSeparator jSeparator6; private javax.swing.JSeparator jSeparator7; private javax.swing.JSeparator jSeparator8; private javax.swing.JSeparator jSeparator9; private javax.swing.JMenuItem javadocMenuItem; private javax.swing.JMenuItem javadocWebMenuItem; private javax.swing.JCheckBoxMenuItem logFilteredEventsCheckBoxMenuItem; private javax.swing.JToggleButton loggingButton; private javax.swing.JMenuItem loggingMenuItem; private javax.swing.JCheckBoxMenuItem loggingPlaybackImmediatelyCheckBoxMenuItem; private javax.swing.JMenuItem loggingSetTimelimitMenuItem; private javax.swing.JMenuItem markInPointMenuItem; private javax.swing.JMenuItem markOutPointMenuItem; private javax.swing.JMenuItem measureTimeMenuItem; private javax.swing.JMenuBar menuBar; private javax.swing.JMenu monSeqMenu; private javax.swing.JMenuItem monSeqMissedEventsMenuItem; private javax.swing.JRadioButtonMenuItem monSeqOpMode0; private javax.swing.JRadioButtonMenuItem monSeqOpMode1; private javax.swing.ButtonGroup monSeqOpModeButtonGroup; private javax.swing.JMenu monSeqOperationModeMenu; private javax.swing.JCheckBoxMenuItem multicastOutputEnabledCheckBoxMenuItem; private javax.swing.JSeparator networkSeparator; private javax.swing.JMenuItem newViewerMenuItem; private javax.swing.JMenuItem openMenuItem; private javax.swing.JCheckBoxMenuItem openMulticastInputMenuItem; private javax.swing.JMenuItem openSocketInputStreamMenuItem; private javax.swing.JMenuItem openUnicastInputMenuItem; private javax.swing.JMenuItem pasteMenuItem; private javax.swing.JCheckBoxMenuItem pauseRenderingCheckBoxMenuItem; private javax.swing.JPanel playerControlPanel; private javax.swing.JSlider playerSlider; private javax.swing.JMenuItem refreshInterfaceMenuItem; private javax.swing.JMenu remoteMenu; private javax.swing.ButtonGroup renderModeButtonGroup; private javax.swing.JMenuItem reopenSocketInputStreamMenuItem; private javax.swing.JLabel resizeLabel; private javax.swing.JPanel resizePanel; private javax.swing.JMenuItem rewindPlaybackMenuItem; private javax.swing.JMenuItem saveImageMenuItem; private javax.swing.JMenuItem saveImageSequenceMenuItem; private javax.swing.JMenuItem sequenceMenuItem; private javax.swing.JMenuItem serverSocketOptionsMenuItem; private javax.swing.JCheckBoxMenuItem skipPacketsRenderingCheckBoxMenuItem; private javax.swing.JPanel statisticsPanel; private javax.swing.JMenuItem subSampleSizeMenuItem; private javax.swing.JCheckBoxMenuItem subsampleEnabledCheckBoxMenuItem; private javax.swing.JCheckBoxMenuItem syncEnabledCheckBoxMenuItem; private javax.swing.JSeparator syncSeperator; private javax.swing.JCheckBoxMenuItem toggleMarkCheckBoxMenuItem; private javax.swing.JMenuItem togglePlaybackDirectionMenuItem; private javax.swing.JCheckBoxMenuItem unicastOutputEnabledCheckBoxMenuItem; private javax.swing.JMenuItem unzoomMenuItem; private javax.swing.JMenuItem updateFirmwareMenuItem; private javax.swing.JCheckBoxMenuItem viewActiveRenderingEnabledMenuItem; private javax.swing.JMenuItem viewBiasesMenuItem; private javax.swing.JMenuItem viewFiltersMenuItem; private javax.swing.JCheckBoxMenuItem viewIgnorePolarityCheckBoxMenuItem; private javax.swing.JMenu viewMenu; private javax.swing.JCheckBoxMenuItem viewOpenGLEnabledMenuItem; private javax.swing.JCheckBoxMenuItem viewRenderBlankFramesCheckBoxMenuItem; private javax.swing.JMenuItem viewSingleStepMenuItem; private javax.swing.JMenuItem zeroTimestampsMenuItem; private javax.swing.JMenuItem zoomMenuItem; // End of variables declaration//GEN-END:variables }
package foam.nanos.http; import foam.core.X; import foam.nanos.http.Command; import foam.nanos.http.Format; import foam.nanos.http.HttpParameters; import foam.nanos.logger.Logger; import foam.nanos.logger.PrefixLogger; import foam.util.SafetyUtil; import java.io.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class HttpParametersWebAgent extends ProxyWebAgent { public static final int BUFFER_SIZE = 4096; protected static ThreadLocal<StringBuilder> sb = new ThreadLocal<StringBuilder>() { @Override protected StringBuilder initialValue() { return new StringBuilder(); } @Override public StringBuilder get() { StringBuilder b = super.get(); b.setLength(0); return b; } }; protected Class parametersClass = DefaultHttpParameters.class; public HttpParametersWebAgent() {} public HttpParametersWebAgent(WebAgent delegate) { setDelegate(delegate); } public HttpParametersWebAgent(String parametersClassName, WebAgent delegate) { setParametersClass(parametersClassName); setDelegate(delegate); } public void setParametersClass(String parametersClassName) { try { this.parametersClass = Class.forName(parametersClassName); } catch (ClassNotFoundException exception) { throw new RuntimeException(exception); } } public void execute(X x) { Logger logger = (Logger) x.get("logger"); HttpServletRequest req = x.get(HttpServletRequest.class); HttpServletResponse resp = x.get(HttpServletResponse.class); logger = new PrefixLogger(new Object[] { this.getClass().getSimpleName() }, logger); if ( req == null || resp == null ) { logger.error(new java.lang.IllegalArgumentException("Context missing HttpServletRequest, HttpServletResponse")); return; } String methodName = req.getMethod(); String accept = req.getHeader("Accept"); String contentType = req.getHeader("Content-Type"); HttpParameters parameters = null; Command command = null; String cmd = req.getParameter("cmd"); logger.debug("methodName", methodName); try { parameters = (HttpParameters) x.create(this.parametersClass); } catch (ClassCastException exception) { throw new RuntimeException(exception); } // Capture 'data' on all requests if ( ! SafetyUtil.isEmpty(req.getParameter("data")) ) { logger.debug("data", req.getParameter("data")); logger.debug("cmd", req.getParameter("cmd")); logger.debug("format", req.getParameter("format")); parameters.set("data", req.getParameter("data")); } else { // When content-type is other than application/x-www-form-urlencoded, the // HttpServletRequest.reader stream must be processes manually to extract // parameters from the body. // Future considerations for partial parameters in the POST URI try { int read = 0; int count = 0; int length = req.getContentLength(); StringBuilder builder = sb.get(); char[] cbuffer = new char[BUFFER_SIZE]; BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream())); while ( ( read = reader.read(cbuffer, 0, BUFFER_SIZE)) != -1 && count < length ) { builder.append(cbuffer, 0, read); count += read; } logger.debug("reader data:", builder.toString()); if ( ! SafetyUtil.isEmpty(builder.toString()) ) { parameters.set("data", builder.toString()); } } catch (IOException e) { try { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Failed to parse body/data."); } catch (IOException ioe) { // nop } return; } } if ( ! "application/x-www-form-urlencoded".equals(contentType) ) { if ( ! SafetyUtil.isEmpty(cmd) ) { switch ( cmd.toLowerCase() ) { case "put": command = Command.put; break; case "select": command = Command.select; if ( ! SafetyUtil.isEmpty(req.getParameter("id")) ) { parameters.set("id", req.getParameter("id")); logger.debug("id", req.getParameter("id")); } break; case "remove": command = Command.remove; parameters.set("id", req.getParameter("id")); logger.debug("id", req.getParameter("id")); break; } } else { switch ( methodName.toUpperCase() ) { // set default command case "POST": command = Command.put; break; case "PUT": command = Command.put; break; case "DELETE": command = Command.remove; break; case "GET": command = Command.select; break; default: command = Command.select; logger.warning("cmd/method could not be determined, defaulting to SELECT."); break; } } // switch ( methodName.toUpperCase() ) { // case "POST": // command = Command.put; // break; // case "PUT": // command = Command.put; // break; // case "DELETE": // command = Command.remove; // break; //// case "HELP": //// command = Command.help; //// resp.setContentType("text/html"); //// break; // case "GET": // if ( ! SafetyUtil.isEmpty(cmd) ) { // switch ( cmd.toLowerCase() ) { // case "put": // command = Command.put; // break; // case "select": // command = Command.select; // if ( ! SafetyUtil.isEmpty(req.getParameter("id")) ) { // parameters.set("id", req.getParameter("id")); // logger.debug("id", req.getParameter("id")); // break; // case "remove": // command = Command.remove; // parameters.set("id", req.getParameter("id")); // logger.debug("id", req.getParameter("id")); // break; // } else { // logger.warning("cmd/method could not be determined, defaulting to SELECT."); // break; } else { cmd = req.getParameter("cmd"); logger.debug("command", cmd); if ( ! SafetyUtil.isEmpty(cmd) ) { switch ( cmd.toLowerCase() ) { case "put": command = Command.put; break; case "select": command = Command.select; if ( ! SafetyUtil.isEmpty(req.getParameter("id")) ) { parameters.set("id", req.getParameter("id")); logger.debug("id", req.getParameter("id")); } break; case "remove": command = Command.remove; parameters.set("id", req.getParameter("id")); logger.debug("id", req.getParameter("id")); break; } } else { logger.warning("cmd/method could not be determined, defaulting to SELECT."); } } parameters.set("cmd", command); parameters.set(Command.class, command); Format format = Format.JSON; resp.setContentType("text/html"); if ( req.getParameter("format") != null && ! "".equals(req.getParameter("format").trim()) ) { String f = req.getParameter("format"); switch ( f.toUpperCase() ) { case "XML": format = Format.XML; resp.setContentType("application/xml"); break; case "JSON": format = Format.JSON; resp.setContentType("application/json"); break; case "JSONJ": format = Format.JSONJ; resp.setContentType("application/json"); break; case "CSV": format = Format.CSV; resp.setContentType("text/plain"); break; case "HTML": format = Format.HTML; resp.setContentType("text/html"); break; default: logger.warning("accept/format could not be determined, default to JSON."); } } else if ( ! SafetyUtil.isEmpty(accept) && ! "application/x-www-form-urlencoded".equals(contentType) ) { logger.debug("accept", accept); String[] formats = accept.split(";"); int i; for ( i = 0 ; i < formats.length; i++ ) { String f = formats[i].trim(); if ( f.contains("application/json") ) { format = Format.JSON; resp.setContentType("application/json"); break; } if ( f.contains("application/jsonj") ) { format = Format.JSONJ; resp.setContentType("application/jsonj"); break; } if ( f.contains("application/xml") ) { format = Format.XML; resp.setContentType("application/xml"); break; } if ( f.contains("text/html") ) { format = Format.HTML; resp.setContentType("text/html"); break; } } if ( i == formats.length ) { logger.warning("accept/format could not be determined, default to JSON."); } } else { logger.warning("accept/format could not be determined, default to JSON."); } parameters.set("format", format); parameters.set(Format.class, format); logger.debug("parameters", parameters); x = x.put(HttpParameters.class, parameters); getDelegate().execute(x); } }
package fr.inria.jessy.consistency; import fr.inria.jessy.transaction.ExecutionHistory; public interface Consistency { public boolean certify(ExecutionHistory executionHistory); }
package de.dqi11.quickStarter.gui; import java.awt.Dimension; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.util.LinkedList; import java.util.Observable; import javax.swing.DefaultListModel; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import de.dqi11.quickStarter.modules.ModuleAction; /** * Represents the main-application window, which * shows the search-field and Advices. */ public class MainWindow extends Observable { private final int WIDTH = 300; private final int TEXTFIELD_HEIGHT = 50; private final int ADVICESLIST_MAXHEIGHT = 200; private boolean visible; private JFrame mainFrame; private JPanel mainPanel; private JTextField textField; @SuppressWarnings("rawtypes") private DefaultListModel moduleActionsListModel; private KeyListener keyListener; private DocumentListener documentListener; private LinkedList<ModuleAction> moduleActions; /** * Constructor. */ public MainWindow() { visible = false; initListeners(); initMainFrame(); initMainPanel(); initTextField(); initAdvicesPanel(); } /** * Initializes the actions. */ public void initListeners() { keyListener = new KeyListener() { @Override public void keyTyped(KeyEvent e) { // TODO Auto-generated method stub } @Override public void keyReleased(KeyEvent e) { // TODO Auto-generated method stub } @Override public void keyPressed(KeyEvent e) { // escape-key if(e.getKeyCode() == 27) toggleApplication(); } }; documentListener = new DocumentListener() { @Override public void removeUpdate(DocumentEvent e) { setChanged(); notifyObservers(); } @Override public void insertUpdate(DocumentEvent e) { setChanged(); notifyObservers(); } @Override public void changedUpdate(DocumentEvent e) { } }; } /** * Initializes the mainFrame. */ public void initMainFrame() { mainFrame = new JFrame(); mainFrame.setUndecorated(true); mainFrame.setSize(WIDTH, TEXTFIELD_HEIGHT + ADVICESLIST_MAXHEIGHT); mainFrame.setLocationRelativeTo(null); } /** * Initializes the mainPanel. */ public void initMainPanel() { mainPanel = new JPanel(); mainFrame.setContentPane(mainPanel); } /** * Initializes the textField. */ public void initTextField() { textField = new JTextField(); textField.setPreferredSize(new Dimension(WIDTH, TEXTFIELD_HEIGHT)); textField.addKeyListener(keyListener); textField.getDocument().addDocumentListener(documentListener); mainPanel.add(textField); } /** * Initializes the advicesPanel; */ @SuppressWarnings("rawtypes") public void initAdvicesPanel() { moduleActionsListModel = new DefaultListModel(); @SuppressWarnings("unchecked" ) JList advicesList = new JList(moduleActionsListModel); advicesList.setPreferredSize(new Dimension(WIDTH, ADVICESLIST_MAXHEIGHT)); mainPanel.add(advicesList); } /** * Updates the shown advices. */ @SuppressWarnings("unchecked") public void updateModuleActions() { moduleActionsListModel.clear(); for(ModuleAction moduleAction : moduleActions) { moduleActionsListModel.addElement(moduleAction); } } /** * Toggles the visibility of the application. */ public void toggleApplication() { visible = !visible; mainFrame.setVisible(visible); } /** * Returns the current search-string. * * @return The search-string. */ public String getSearchString() { return textField.getText(); } /** * Sets the Advices and updates the GUI. * * @param advices The List of Advices. */ public void setModuleActions(LinkedList<ModuleAction> moduleActions) { this.moduleActions = moduleActions; updateModuleActions(); } }
package de.uxnr.tsoexpert.file; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.security.Key; import javax.crypto.Cipher; import javax.crypto.CipherInputStream; import javax.crypto.spec.SecretKeySpec; import sun.misc.BASE64Decoder; public class FileDecrypter { public static final String PRIVATE_KEY_FILE = "PRIVATE_KEY"; private final byte[] keyarr; private final Key key; public FileDecrypter() throws IOException { this.keyarr = this.readPrivateKey(); this.key = new SecretKeySpec(this.keyarr, "Blowfish"); } public FileData decryptFile(FileData fd) throws IOException { ByteArrayInputStream input = fd.getInputStream(); ByteArrayOutputStream output = new ByteArrayOutputStream(); BASE64Decoder base64 = new BASE64Decoder(); byte[] bytearr = base64.decodeBuffer(input); input = new ByteArrayInputStream(bytearr); Cipher cipher = null; try { cipher = Cipher.getInstance("Blowfish/ECB/PKCS5Padding"); } catch (Exception e) { throw new IOException(e); } try { cipher.init(Cipher.DECRYPT_MODE, key); } catch (Exception e) { throw new IOException(e); } int length = -1; CipherInputStream stream = new CipherInputStream(input, cipher); while ((length = stream.read(bytearr)) != -1) { output.write(bytearr, 0, length); } output.close(); stream.close(); String path = fd.getPath().replaceAll("\\.(.*)_enc", "\\.$1"); return new FileData(path, output.toByteArray()); } private byte[] readPrivateKey() throws IOException { File keyFile = new File(PRIVATE_KEY_FILE); FileInputStream input = new FileInputStream(keyFile); ByteArrayOutputStream output = new ByteArrayOutputStream(); int length = -1; byte[] bytearr = new byte[1024]; while ((length = input.read(bytearr)) != -1) { output.write(bytearr, 0, length); } output.close(); input.close(); String key = new String(output.toByteArray()); return key.trim().getBytes("UTF8"); } public static void main(String[] args) throws IOException { File file = new File("res/GFX/game_settings.xml_enc"); FileInputStream fileStream = new FileInputStream(file); FileDecrypter fileDecrypter = new FileDecrypter(); FileData fileData = new FileData(file.getPath(), fileStream); fileDecrypter.decryptFile(fileData); } }
package org.jetbrains.debugger.memory.view; import com.intellij.debugger.DebuggerManager; import com.intellij.debugger.engine.DebugProcessImpl; import com.intellij.debugger.engine.JavaValue; import com.intellij.debugger.engine.SuspendContextImpl; import com.intellij.debugger.engine.evaluation.EvaluateException; import com.intellij.debugger.engine.evaluation.EvaluationContext; import com.intellij.debugger.engine.evaluation.EvaluationContextImpl; import com.intellij.debugger.engine.evaluation.TextWithImportsImpl; import com.intellij.debugger.engine.evaluation.expression.ExpressionEvaluator; import com.intellij.debugger.engine.events.DebuggerContextCommandImpl; import com.intellij.debugger.ui.impl.watch.DebuggerTreeNodeImpl; import com.intellij.debugger.ui.impl.watch.MessageDescriptor; import com.intellij.debugger.ui.impl.watch.NodeManagerImpl; import com.intellij.debugger.ui.tree.NodeDescriptor; import com.intellij.debugger.ui.tree.render.CachedEvaluator; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.actionSystem.ex.AnActionListener; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Pair; import com.intellij.openapi.wm.IdeFocusManager; import com.intellij.ui.JBColor; import com.intellij.ui.SimpleTextAttributes; import com.intellij.ui.components.JBLabel; import com.intellij.ui.components.JBPanel; import com.intellij.ui.components.JBScrollPane; import com.intellij.util.ui.JBDimension; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.UIUtil; import com.intellij.util.ui.update.UiNotifyConnector; import com.intellij.xdebugger.XDebugSession; import com.intellij.xdebugger.XDebugSessionListener; import com.intellij.xdebugger.XExpression; import com.intellij.xdebugger.frame.*; import com.intellij.xdebugger.impl.XDebugSessionImpl; import com.intellij.xdebugger.impl.actions.XDebuggerActionBase; import com.intellij.xdebugger.impl.evaluate.quick.XDebuggerTreeCreator; import com.intellij.xdebugger.impl.frame.XValueMarkers; import com.intellij.xdebugger.impl.ui.XDebuggerExpressionEditor; import com.intellij.xdebugger.impl.ui.XDebuggerUIConstants; import com.intellij.xdebugger.impl.ui.tree.ValueMarkup; import com.intellij.xdebugger.impl.ui.tree.XDebuggerTree; import com.intellij.xdebugger.impl.ui.tree.XDebuggerTreeState; import com.intellij.xdebugger.impl.ui.tree.actions.XDebuggerTreeActionBase; import com.intellij.xdebugger.impl.ui.tree.nodes.XDebuggerTreeNode; import com.intellij.xdebugger.impl.ui.tree.nodes.XValueNodeImpl; import com.sun.jdi.BooleanValue; import com.sun.jdi.ObjectReference; import com.sun.jdi.ReferenceType; import com.sun.jdi.Value; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.debugger.memory.utils.ErrorsValueGroup; import org.jetbrains.debugger.memory.utils.InstanceJavaValue; import org.jetbrains.debugger.memory.utils.InstanceValueDescriptor; import org.jetbrains.java.debugger.JavaDebuggerEditorsProvider; import javax.swing.*; import javax.swing.tree.TreeNode; import java.awt.*; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import static java.lang.Math.min; public class InstancesWindow extends DialogWrapper { private static final int DEFAULT_WINDOW_WIDTH = 700; private static final int DEFAULT_WINDOW_HEIGHT = 400; private static final int FILTERING_BUTTON_ADDITIONAL_WIDTH = 30; private static final int BORDER_LAYOUT_DEFAULT_GAP = 5; private final Project myProject; private final XDebugSession myDebugSession; private final ReferenceType myReferenceType; private MyInstancesView myInstancesView; public InstancesWindow(@NotNull XDebugSession session, @NotNull ReferenceType referenceType) { super(session.getProject(), false); myProject = session.getProject(); myDebugSession = session; myReferenceType = referenceType; setTitle("Instances of " + referenceType.name()); myDebugSession.addSessionListener(new XDebugSessionListener() { @Override public void sessionStopped() { SwingUtilities.invokeLater(() -> close(OK_EXIT_CODE)); } }, myDisposable); setModal(false); init(); JRootPane root = myInstancesView.getRootPane(); root.setDefaultButton(myInstancesView.myFilterButton); } enum FilteringCompletionReason { ALL_CHECKED, INTERRUPTED, LIMIT_REACHED } @NotNull @Override protected String getDimensionServiceKey() { return "#org.jetbrains.debugger.memory.view.InstancesWindow"; } @Nullable @Override protected JComponent createCenterPanel() { myInstancesView = new MyInstancesView(); myInstancesView.setPreferredSize( new JBDimension(DEFAULT_WINDOW_WIDTH, DEFAULT_WINDOW_HEIGHT)); return myInstancesView; } @Nullable @Override protected JComponent createSouthPanel() { JComponent comp = super.createSouthPanel(); if (comp != null) { comp.add(myInstancesView.myProgress, BorderLayout.WEST); } return comp; } @Override protected void dispose() { super.dispose(); myInstancesView.dispose(); } @NotNull @Override protected Action[] createActions() { return new Action[]{new DialogWrapperExitAction("Close", CLOSE_EXIT_CODE)}; } private class MyInstancesView extends JBPanel implements Disposable { private static final int MAX_TREE_NODE_COUNT = 2000; private static final int FILTERING_CHUNK_SIZE = 30; private final XDebuggerTree myInstancesTree; private final XDebuggerExpressionEditor myFilterConditionEditor; private final XDebugSessionListener myDebugSessionListener = new MySessionListener(); private final MyCachedEvaluator myEvaluator = new MyCachedEvaluator(); private final MyNodeManager myNodeManager = new MyNodeManager(myProject); private final JButton myFilterButton = new JButton("Filter"); private final FilteringProgressView myProgress = new FilteringProgressView(); private final AnActionListener.Adapter myActionListener = new MyActionListener(); private final Object myFilteringTaskLock = new Object(); private volatile MyFilteringWorker myFilteringTask = null; MyInstancesView() { super(new BorderLayout(0, JBUI.scale(BORDER_LAYOUT_DEFAULT_GAP))); XValueMarkers<?, ?> markers = getValueMarkers(); ActionManager.getInstance().addAnActionListener(myActionListener, InstancesWindow.this.myDisposable); myDebugSession.addSessionListener(myDebugSessionListener, InstancesWindow.this.myDisposable); JavaDebuggerEditorsProvider editorsProvider = new JavaDebuggerEditorsProvider(); myFilterConditionEditor = new ExpressionEditorWithHistory(myProject, myReferenceType, editorsProvider, InstancesWindow.this.myDisposable); myFilterButton.setBorder(BorderFactory.createEmptyBorder()); Dimension filteringButtonSize = myFilterConditionEditor.getEditorComponent().getPreferredSize(); filteringButtonSize.width = JBUI.scale(FILTERING_BUTTON_ADDITIONAL_WIDTH) + myFilterButton.getPreferredSize().width; myFilterButton.setPreferredSize(filteringButtonSize); JBPanel filteringPane = new JBPanel(new BorderLayout(JBUI.scale(BORDER_LAYOUT_DEFAULT_GAP), 0)); JBLabel sideEffectsWarning = new JBLabel("Warning: filtering may have side effects", SwingConstants.RIGHT); sideEffectsWarning.setBorder(JBUI.Borders.empty(1, 0, 0, 0)); sideEffectsWarning.setComponentStyle(UIUtil.ComponentStyle.SMALL); sideEffectsWarning.setFontColor(UIUtil.FontColor.BRIGHTER); filteringPane.add(new JBLabel("Condition:"), BorderLayout.WEST); filteringPane.add(myFilterConditionEditor.getComponent(), BorderLayout.CENTER); filteringPane.add(myFilterButton, BorderLayout.EAST); filteringPane.add(sideEffectsWarning, BorderLayout.SOUTH); myProgress.addStopActionListener(this::cancelFilteringTask); XDebuggerTreeCreator treeCreator = new XDebuggerTreeCreator(myProject, editorsProvider, null, markers); myInstancesTree = (XDebuggerTree) treeCreator.createTree(getTreeRootDescriptor()); myInstancesTree.setRootVisible(false); myInstancesTree.getRoot().setLeaf(false); myInstancesTree.setExpandableItemsEnabled(true); myFilterButton.addActionListener(e -> { String expression = myFilterConditionEditor.getExpression().getExpression(); if (!expression.isEmpty()) { myFilterConditionEditor.saveTextInHistory(); } myFilterButton.setEnabled(false); myInstancesTree.rebuildAndRestore(XDebuggerTreeState.saveState(myInstancesTree)); }); JBScrollPane treeScrollPane = new JBScrollPane(myInstancesTree); add(filteringPane, BorderLayout.NORTH); add(treeScrollPane, BorderLayout.CENTER); JComponent focusedComponent = myFilterConditionEditor.getEditorComponent(); UiNotifyConnector.doWhenFirstShown(focusedComponent, () -> IdeFocusManager.findInstanceByComponent(focusedComponent) .requestFocus(focusedComponent, true)); } @Override public void dispose() { ActionManager.getInstance().removeAnActionListener(myActionListener); myDebugSession.removeSessionListener(myDebugSessionListener); cancelFilteringTask(); Disposer.dispose(myInstancesTree); } private void updateInstances() { DebugProcessImpl debugProcess = (DebugProcessImpl) DebuggerManager.getInstance(myProject) .getDebugProcess(myDebugSession.getDebugProcess().getProcessHandler()); cancelFilteringTask(); debugProcess.getManagerThread().schedule(new DebuggerContextCommandImpl(debugProcess.getDebuggerContext()) { @Override public Priority getPriority() { return Priority.LOWEST; } @Override public void threadAction(@NotNull SuspendContextImpl suspendContext) { List<ObjectReference> instances = myReferenceType.instances(0); EvaluationContextImpl evaluationContext = debugProcess .getDebuggerContext().createEvaluationContext(); if (evaluationContext != null) { synchronized (myFilteringTaskLock) { myFilteringTask = new MyFilteringWorker(instances, evaluationContext, createEvaluator()); SwingUtilities.invokeLater(() -> { myProgress.start(instances.size()); myFilteringTask.execute(); }); myFilteringTask.execute(); } } } }); } @Nullable private ExpressionEvaluator createEvaluator() { ExpressionEvaluator evaluator = null; XExpression expression = myFilterConditionEditor.getExpression(); if (expression != null && !expression.getExpression().isEmpty()) { try { myEvaluator.setReferenceExpression(TextWithImportsImpl. fromXExpression(expression)); evaluator = myEvaluator.getEvaluator(); } catch (EvaluateException ignored) { } } return evaluator; } private void cancelFilteringTask() { if (myFilteringTask != null) { synchronized (myFilteringTaskLock) { if (myFilteringTask != null) { myFilteringTask.cancel(true); myFilteringTask = null; } } } } private XValueMarkers<?, ?> getValueMarkers() { return myDebugSession instanceof XDebugSessionImpl ? ((XDebugSessionImpl) myDebugSession).getValueMarkers() : null; } private void addChildrenToTree(XValueChildrenList children, boolean last) { XDebuggerTreeNode root = myInstancesTree.getRoot(); if (root != null) { ((XValueNodeImpl) root).addChildren(children, last); } } @NotNull private Pair<XValue, String> getTreeRootDescriptor() { return Pair.pair(new XValue() { @Override public void computeChildren(@NotNull XCompositeNode node) { updateInstances(); } @Override public void computePresentation(@NotNull XValueNode node, @NotNull XValuePlace place) { node.setPresentation(null, "", "", true); } }, "root"); } private class MySessionListener implements XDebugSessionListener { private volatile XDebuggerTreeState myTreeState = null; @Override public void sessionResumed() { SwingUtilities.invokeLater(() -> { myTreeState = XDebuggerTreeState.saveState(myInstancesTree); cancelFilteringTask(); myInstancesTree.getRoot().clearChildren(); XCompositeNode root = (XCompositeNode) myInstancesTree.getRoot(); root.setMessage("The application is running", XDebuggerUIConstants.INFORMATION_MESSAGE_ICON, SimpleTextAttributes.REGULAR_ATTRIBUTES, null); myProgress.setVisible(false); }); } @Override public void sessionPaused() { SwingUtilities.invokeLater(() -> { myProgress.setVisible(true); myInstancesTree.rebuildAndRestore(myTreeState); }); } } private class MyActionListener extends AnActionListener.Adapter { @Override public void beforeActionPerformed(AnAction action, DataContext dataContext, AnActionEvent event) { if (dataContext.getData(PlatformDataKeys.CONTEXT_COMPONENT) == myInstancesView.myInstancesTree && (isAddToWatchesAction(action) || isEvaluateExpressionAction(action))) { XValueNodeImpl selectedNode = XDebuggerTreeActionBase.getSelectedNode(dataContext); XValueMarkers<?, ?> markers = getValueMarkers(); if (markers != null && selectedNode != null) { TreeNode currentNode = selectedNode; while (!myInstancesTree.getRoot().equals(currentNode.getParent())) { currentNode = currentNode.getParent(); } XValue valueContainer = ((XValueNodeImpl) currentNode).getValueContainer(); String expression = valueContainer.getEvaluationExpression(); if (expression != null) { markers.markValue(valueContainer, new ValueMarkup(expression.replace("@", ""), new JBColor(0, 0), null)); } SwingUtilities.invokeLater(() -> myInstancesTree.rebuildAndRestore(XDebuggerTreeState.saveState(myInstancesTree))); } } } private boolean isAddToWatchesAction(AnAction action) { String className = action.getClass().getSimpleName(); return action instanceof XDebuggerTreeActionBase && className.equals("XAddToWatchesAction"); } private boolean isEvaluateExpressionAction(AnAction action) { String className = action.getClass().getSimpleName(); return action instanceof XDebuggerActionBase && className.equals("EvaluateAction"); } } private final class MyCachedEvaluator extends CachedEvaluator { @Override @NotNull protected String getClassName() { return myReferenceType.name(); } ExpressionEvaluator getEvaluator() throws EvaluateException { return getEvaluator(myProject); } } private class MyFilteringWorker extends SwingWorker<Void, Void> { private final List<ObjectReference> myReferences; private final EvaluationContextImpl myEvaluationContext; private final ExpressionEvaluator myExpressionEvaluator; private final ErrorsValueGroup myErrorsGroup = new ErrorsValueGroup("Errors"); private volatile boolean myDebuggerTaskCompleted = false; @NotNull private volatile FilteringCompletionReason myCompletionReason = FilteringCompletionReason.INTERRUPTED; MyFilteringWorker(@NotNull List<ObjectReference> refs, @NotNull EvaluationContextImpl evaluationContext, @Nullable ExpressionEvaluator evaluator) { myReferences = refs; myEvaluationContext = evaluationContext; myExpressionEvaluator = evaluator; } @Override protected void done() { if (!myErrorsGroup.isEmpty()) { XValueChildrenList lst = new XValueChildrenList(); lst.addBottomGroup(myErrorsGroup); addChildrenToTree(lst, true); } else { addChildrenToTree(XValueChildrenList.EMPTY, true); } myFilterButton.setEnabled(true); SwingUtilities.invokeLater(() -> myProgress.complete(myCompletionReason)); } @Override protected Void doInBackground() throws Exception { DebugProcessImpl debugProcess = (DebugProcessImpl) DebuggerManager.getInstance(myProject) .getDebugProcess(myDebugSession.getDebugProcess().getProcessHandler()); AtomicInteger totalChildren = new AtomicInteger(0); AtomicInteger totalViewed = new AtomicInteger(0); for (int i = 0, size = myReferences.size(); i < size && totalChildren.get() < MAX_TREE_NODE_COUNT; i += FILTERING_CHUNK_SIZE) { myDebuggerTaskCompleted = false; final int chunkBegin = i; debugProcess.getManagerThread().schedule(new DebuggerContextCommandImpl(debugProcess.getDebuggerContext()) { @Override public Priority getPriority() { return Priority.LOWEST; } @Override public void threadAction(@NotNull SuspendContextImpl suspendContext) { // TODO: need to rewrite this XValueChildrenList children = new XValueChildrenList(); int endOfChunk = min(chunkBegin + FILTERING_CHUNK_SIZE, size); int errorCount = 0; for (int j = chunkBegin; j < endOfChunk && totalChildren.get() < MAX_TREE_NODE_COUNT; j++) { ObjectReference ref = myReferences.get(j); totalViewed.incrementAndGet(); Pair<MyFilteringResult, String> comparison = null; if (myExpressionEvaluator != null) { comparison = isSatisfy(myExpressionEvaluator, ref); if (comparison.first == MyFilteringResult.EVAL_ERROR) { errorCount++; } if (comparison.first == MyFilteringResult.NO_MATCH) { continue; } } JavaValue val = new InstanceJavaValue(null, new InstanceValueDescriptor(myProject, ref), myEvaluationContext, myNodeManager, true); if (comparison == null || comparison.first == MyFilteringResult.MATCH) { children.add(val); } else { myErrorsGroup.addErrorValue(comparison.second, val); } totalChildren.incrementAndGet(); } if (children.size() > 0) { SwingUtilities.invokeLater(() -> { if (MyFilteringWorker.this == myFilteringTask) { addChildrenToTree(children, false); } }); } final int childrenSize = children.size(); final int finalErrorsCount = errorCount; SwingUtilities.invokeLater(() -> myProgress.updateProgress(endOfChunk - chunkBegin, childrenSize, finalErrorsCount)); synchronized (MyFilteringWorker.this) { myDebuggerTaskCompleted = true; MyFilteringWorker.this.notify(); } } }); synchronized (MyFilteringWorker.this) { while (!myDebuggerTaskCompleted) { MyFilteringWorker.this.wait(); } } } myCompletionReason = totalViewed.get() == myReferences.size() ? FilteringCompletionReason.ALL_CHECKED : FilteringCompletionReason.LIMIT_REACHED; return null; } private Pair<MyFilteringResult, String> isSatisfy(@NotNull ExpressionEvaluator evaluator, @NotNull Value value) { try { Value result = evaluator.evaluate(myEvaluationContext.createEvaluationContext(value)); if (result instanceof BooleanValue && ((BooleanValue) result).value()) { return Pair.create(MyFilteringResult.MATCH, ""); } } catch (EvaluateException e) { return Pair.create(MyFilteringResult.EVAL_ERROR, e.getMessage()); } return Pair.create(MyFilteringResult.NO_MATCH, ""); } } } private final static class MyNodeManager extends NodeManagerImpl { MyNodeManager(Project project) { super(project, null); } @Override public DebuggerTreeNodeImpl createNode(final NodeDescriptor descriptor, EvaluationContext evaluationContext) { return new DebuggerTreeNodeImpl(null, descriptor); } @Override public DebuggerTreeNodeImpl createMessageNode(MessageDescriptor descriptor) { return new DebuggerTreeNodeImpl(null, descriptor); } @Override public DebuggerTreeNodeImpl createMessageNode(String message) { return new DebuggerTreeNodeImpl(null, new MessageDescriptor(message)); } } private enum MyFilteringResult { MATCH, NO_MATCH, EVAL_ERROR } }
package jcavern; import java.util.Observable; import java.awt.*; import jcavern.thing.Combatant; /** * Class used to describe combat activities in a World. * * @author Bill Walker * @version $Id$ */ public class CombatEvent extends WorldEvent { /** * Used to indicate the kind of change that happened to a thing. */ public static final int ATTACKED_MISSED = 103; /** * Used to indicate the kind of change that happened to a thing. */ public static final int ATTACKED_HIT = 104; /** * Used to indicate the kind of change that happened to a thing. */ public static final int ATTACKED_KILLED = 105; /** * Used to indicate the kind of change that happened to a thing. */ public static final int GAINED_POINTS = 106; /** * Used to indicate the kind of change that happened to a thing. */ public static final int LOST_POINTS = 107; /** * Creates a new CombatEvent. * * @param aLocation where the combat took place * @param attackee who attacked * @param outcome what was the outcome (one of the symbolic constants defined in CombatEvent) * @param attacker who was damaged * @param damage how much damage was done */ private CombatEvent(Location aLocation, Combatant attackee, int outcome, Combatant attacker, int damage) { super(aLocation, attackee, outcome, attacker, ""); StringBuffer theBuffer = new StringBuffer(); switch (outcome) { case ATTACKED_MISSED: theBuffer.append(attacker.getNounPhrase() + " "); theBuffer.append("cannot attack" + " " + attackee.getNounPhrase()); break; case ATTACKED_HIT: theBuffer.append(attacker.getNounPhrase() + " "); theBuffer.append(attackee.getHitVerb() + " " + attackee.getNounPhrase() + " for " + damage); break; case ATTACKED_KILLED: theBuffer.append(attacker.getNounPhrase() + " "); theBuffer.append(attackee.getKilledVerb() + " " + attackee.getNounPhrase()); break; case GAINED_POINTS: theBuffer.append(attackee.getNounPhrase()); theBuffer.append(" gained " + damage + " points"); break; case LOST_POINTS: theBuffer.append(attackee.getNounPhrase()); theBuffer.append(" lost " + damage + " points"); break; default: theBuffer.append("no such outcome " + outcome); } setMessage(theBuffer.toString()); } /** * Creates a CombatEvent for a missed attack. * * @param aLocation where the combat took place * @param attackee who attacked * @param attacker who was damaged * @return a non-null CombatEvent */ public static CombatEvent missed(Location aLocation, Combatant attackee, Combatant attacker) { return new CombatEvent(aLocation, attackee, ATTACKED_MISSED, attacker, 0); } /** * Creates a CombatEvent for a successful hit. * * @param aLocation where the combat took place * @param attackee who attacked * @param attacker who was damaged * @param damage how much damage was done * @return a non-null CombatEvent */ public static CombatEvent hit(Location aLocation, Combatant attackee, Combatant attacker, int damage) { return new CombatEvent(aLocation, attackee, ATTACKED_HIT, attacker, damage); } /** * Creates a CombatEvent for a successful kill. * * @param aLocation where the combat took place * @param attackee who attacked * @param attacker who was damaged * @param damage how much damage was done * @return a non-null CombatEvent */ public static CombatEvent killed(Location aLocation, Combatant attackee, Combatant attacker, int damage) { return new CombatEvent(aLocation, attackee, ATTACKED_KILLED, attacker, damage); } /** * Creates a CombatEvent for gained points. * * @param aLocation where the combat took place * @param gainee who gained points * @param gain how many points were gained * @return a non-null CombatEvent */ public static CombatEvent gained(Location aLocation, Combatant gainee, int gain) { return new CombatEvent(aLocation, gainee, GAINED_POINTS, null, gain); } /** * Creates a CombatEvent for lost points. * * @param aLocation where the combat took place * @param lossee who lost points * @param loss how many points were lost * @return a non-null CombatEvent */ public static CombatEvent lost(Location aLocation, Combatant lossee, int loss) { return new CombatEvent(aLocation, lossee, LOST_POINTS, null, loss); } }
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.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.actions.InstallSdkAction; import io.flutter.sdk.FlutterSdkUtil; import org.apache.commons.lang.StringUtils; 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 implements InstallSdkAction.Model { 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 JProgressBar 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(); } 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(@NotNull DocumentEvent e) { validate(); } }); // When this changes the corresponding parts of FlutterProjectStep should also be changed. 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(); } }); myInstallActionLink.setEnabled(getSdkComboPath().trim().isEmpty()); errorIcon.setVisible(false); errorPane.setVisible(false); } @SuppressWarnings("EmptyMethod") void apply() { } @NotNull public JComponent getComponent() { return myMainPanel; } private void createUIComponents() { mySdkPathComboWithBrowse = new ComboboxWithBrowseButton(new ComboBox<>()); } @Override 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(); if (StringUtils.isEmpty(sdkPath)) { return new ValidationInfo("A Flutter SDK must be specified for project creation.", mySdkPathComboWithBrowse); } 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(); } @Override @NotNull public ComboboxWithBrowseButton getSdkComboBox() { return mySdkPathComboWithBrowse; } @Override public void setSdkPath(@NotNull String sdkPath) { getSdkEditor().setItem(sdkPath); } @Override public JProgressBar getProgressBar() { return myProgressBar; } @Override public LinkLabel getInstallActionLink() { return myInstallActionLink; } @Override public JTextPane getProgressText() { return myProgressText; } @Override public JLabel getCancelProgressButton() { return myCancelProgressButton; } /** * Set error details (pass null to hide). */ @Override public void setErrorDetails(@Nullable String details) { final boolean makeVisible = details != null; if (makeVisible) { errorText.setText(details); } errorIcon.setVisible(makeVisible); errorPane.setVisible(makeVisible); } @Override public void addCancelActionListener(InstallSdkAction.CancelActionListener listener) { myListener = listener; } @Override 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 jade.mtp.iiop; import jade.mtp.MTP; import jade.mtp.TransportAddress; import jade.domain.FIPAAgentManagement.Envelope; import org.omg.CORBA.*; import FIPA.*; // OMG IDL Stubs /** Implementation of <code><b>fipa.mts.mtp.iiop.std</b></code> specification for delivering ACL messages over the OMG IIOP transport protocol. @author Giovanni Rimassa - Universita` di Parma @version $Date$ $Revision$ */ public class MessageTransportProtocol implements MTP { private static class MTSImpl extends _MTSImplBase { public void message(FipaMessage aFipaMessage) { byte[] payload = aFipaMessage.messageBody; Envelope env = new Envelope(); // Read in the envelope String s = new String(payload); System.out.println("|||||||||||||||||||||||||||||||||||||||"); System.out.println(s); System.out.println("|||||||||||||||||||||||||||||||||||||||"); } } // End of MTSImpl class private ORB myORB; private MTSImpl server; public MessageTransportProtocol() { myORB = ORB.init(new String[0], null); } public TransportAddress activate() throws MTP.MTPException { server = new MTSImpl(); myORB.connect(server); return new IIOPAddress(myORB, server); } public void activate(TransportAddress ta) throws MTP.MTPException { throw new MTP.MTPException("User supplied transport address not supported."); } public void deactivate(TransportAddress ta) throws MTP.MTPException { throw new MTP.MTPException("Individual deactivation not supported."); } public void deactivate() throws MTP.MTPException { myORB.disconnect(server); } public void deliver(TransportAddress ta, Envelope env, byte[] payload) throws MTP.MTPException { try { IIOPAddress addr = (IIOPAddress)ta; MTS objRef = addr.getObject(); FipaMessage msg = new FipaMessage(); FIPA.Envelope IDLenv = new FIPA.Envelope(); // Fill in the IDL envelope... msg.messageEnvelopes = new FIPA.Envelope[] { IDLenv }; msg.messageBody = payload; objRef.message(msg); } catch(ClassCastException cce) { throw new MTP.MTPException("Address mismatch: this is not a valid IIOP address."); } } public TransportAddress strToAddr(String rep) throws MTP.MTPException { return new IIOPAddress(myORB, rep); } public String addrToStr(TransportAddress ta) throws MTP.MTPException { try { IIOPAddress addr = (IIOPAddress)ta; return addr.getIOR(); } catch(ClassCastException cce) { throw new MTP.MTPException("Address mismatch: this is not a valid IIOP address."); } } public String getName() { return "iiop"; } } class IIOPAddress implements TransportAddress { public static final byte BIG_ENDIAN = 0; public static final byte LITTLE_ENDIAN = 1; private static final String TYPE_ID = "IDL:FIPA_Agent_97:1.0"; private static final int TAG_INTERNET_IOP = 0; private static final byte IIOP_MAJOR = 1; private static final byte IIOP_MINOR = 0; private ORB orb; private String ior; private String host; private short port; private String objectKey; private CDRCodec codecStrategy; public IIOPAddress(ORB anOrb, MTS objRef) throws MTP.MTPException { orb = anOrb; String s = orb.object_to_string(objRef); if(s.toUpperCase().startsWith("IOR:")) initFromIOR(s); else if(s.toLowerCase().startsWith("iiop: initFromURL(s, LITTLE_ENDIAN); else throw new MTP.MTPException("Invalid string prefix"); } public IIOPAddress(ORB anOrb, String s) throws MTP.MTPException { orb = anOrb; if(s.toUpperCase().startsWith("IOR:")) initFromIOR(s); else if(s.toLowerCase().startsWith("iiop: initFromURL(s, LITTLE_ENDIAN); else throw new MTP.MTPException("Invalid string prefix"); } private void initFromIOR(String s) throws MTP.MTPException { // Store stringified IOR ior = new String(s.toUpperCase()); // Remove 'IOR:' prefix to get Hex digits String hexString = ior.substring(4); short endianness = Short.parseShort(hexString.substring(0, 2), 16); switch(endianness) { case BIG_ENDIAN: codecStrategy = new BigEndianCodec(hexString); break; case LITTLE_ENDIAN: codecStrategy = new LittleEndianCodec(hexString); break; default: throw new MTP.MTPException("Invalid endianness specifier"); } // Read 'string type_id' field String typeID = codecStrategy.readString(); if(!typeID.equalsIgnoreCase(TYPE_ID)) throw new MTP.MTPException("Invalid type ID" + typeID); // Read 'sequence<TaggedProfile> profiles' field // Read sequence length int seqLen = codecStrategy.readLong(); for(int i = 0; i < seqLen; i++) { // Read 'ProfileId tag' field int tag = codecStrategy.readLong(); byte[] profile = codecStrategy.readOctetSequence(); if(tag == TAG_INTERNET_IOP) { // Process IIOP profile CDRCodec profileBodyCodec; switch(profile[0]) { case BIG_ENDIAN: profileBodyCodec = new BigEndianCodec(profile); break; case LITTLE_ENDIAN: profileBodyCodec = new LittleEndianCodec(profile); break; default: throw new MTP.MTPException("Invalid endianness specifier"); } // Read IIOP version byte versionMajor = profileBodyCodec.readOctet(); byte versionMinor = profileBodyCodec.readOctet(); if(versionMajor != 1) throw new MTP.MTPException("IIOP version not supported"); // Read 'string host' field host = profileBodyCodec.readString(); // Read 'unsigned short port' field port = profileBodyCodec.readShort(); // Read 'sequence<octet> object_key' field and convert it // into a String object byte[] keyBuffer = profileBodyCodec.readOctetSequence(); objectKey = new String(keyBuffer); codecStrategy = null; } } } private void initFromURL(String s, short endianness) throws MTP.MTPException { // Remove 'iiop://' prefix to get URL host, port and file s = s.substring(7); int colonPos = s.indexOf(':'); int slashPos = s.indexOf('/'); if((colonPos == -1) || (slashPos == -1)) throw new MTP.MTPException("Invalid URL string"); host = new String(s.substring(0, colonPos)); port = Short.parseShort(s.substring(colonPos + 1, slashPos)); objectKey = new String(s.substring(slashPos + 1, s.length())); switch(endianness) { case BIG_ENDIAN: codecStrategy = new BigEndianCodec(new byte[0]); break; case LITTLE_ENDIAN: codecStrategy = new LittleEndianCodec(new byte[0]); break; default: throw new MTP.MTPException("Invalid endianness specifier"); } codecStrategy.writeString(TYPE_ID); // Write '1' as profiles sequence length codecStrategy.writeLong(1); codecStrategy.writeLong(TAG_INTERNET_IOP); CDRCodec profileBodyCodec; switch(endianness) { case BIG_ENDIAN: profileBodyCodec = new BigEndianCodec(new byte[0]); break; case LITTLE_ENDIAN: profileBodyCodec = new LittleEndianCodec(new byte[0]); break; default: throw new MTP.MTPException("Invalid endianness specifier"); } // Write IIOP 1.0 profile to auxiliary CDR codec profileBodyCodec.writeOctet(IIOP_MAJOR); profileBodyCodec.writeOctet(IIOP_MINOR); profileBodyCodec.writeString(host); profileBodyCodec.writeShort(port); byte[] objKey = objectKey.getBytes(); profileBodyCodec.writeOctetSequence(objKey); byte[] encapsulatedProfile = profileBodyCodec.writtenBytes(); // Write encapsulated profile to main IOR codec codecStrategy.writeOctetSequence(encapsulatedProfile); String hexString = codecStrategy.writtenString(); ior = "IOR:" + hexString; codecStrategy = null; } public String getURL() { int portNum = port; if(portNum < 0) portNum += 65536; return "iiop://" + host + ":" + portNum + "/" + objectKey; } public String getIOR() { return ior; } public MTS getObject() { return MTSHelper.narrow(orb.string_to_object(ior)); } private static abstract class CDRCodec { private static final char[] HEX = { '0','1','2','3','4','5','6','7', '8','9','a','b','c','d','e','f' }; protected byte[] readBuffer; protected StringBuffer writeBuffer; protected int readIndex = 0; protected int writeIndex = 0; protected CDRCodec(String hexString) { // Put all Hex digits into a byte array readBuffer = bytesFromHexString(hexString); readIndex = 1; writeBuffer = new StringBuffer(255); } protected CDRCodec(byte[] hexDigits) { readBuffer = new byte[hexDigits.length]; System.arraycopy(hexDigits, 0, readBuffer, 0, readBuffer.length); readIndex = 1; writeBuffer = new StringBuffer(255); } public String writtenString() { return new String(writeBuffer); } public byte[] writtenBytes() { return bytesFromHexString(new String(writeBuffer)); } public byte readOctet() { return readBuffer[readIndex++]; } public byte[] readOctetSequence() { int seqLen = readLong(); byte[] result = new byte[seqLen]; System.arraycopy(readBuffer, readIndex, result, 0, seqLen); readIndex += seqLen; return result; } public String readString() { int strLen = readLong(); // This includes '\0' terminator String result = new String(readBuffer, readIndex, strLen - 1); readIndex += strLen; return result; } // These depend on endianness, so are deferred to subclasses public abstract short readShort(); // 16 bits public abstract int readLong(); // 32 bits public abstract long readLongLong(); // 64 bits // Writes a couple of hexadecimal digits representing the given byte. // All other marshalling operations ultimately use this method to modify // the write buffer public void writeOctet(byte b) { char[] digits = new char[2]; digits[0] = HEX[(b & 0xF0) >> 4]; // High nibble digits[1] = HEX[b & 0x0F]; // Low nibble writeBuffer.append(digits); writeIndex++; } public void writeOctetSequence(byte[] seq) { int seqLen = seq.length; writeLong(seqLen); for(int i = 0; i < seqLen; i++) writeOctet(seq[i]); } public void writeString(String s) { int strLen = s.length() + 1; // This includes '\0' terminator writeLong(strLen); byte[] bytes = s.getBytes(); for(int i = 0; i < s.length(); i++) writeOctet(bytes[i]); writeOctet((byte)0x00); } // These depend on endianness, so are deferred to subclasses public abstract void writeShort(short s); // 16 bits public abstract void writeLong(int i); // 32 bits public abstract void writeLongLong(long l); // 64 bits protected void setReadAlignment(int align) { while((readIndex % align) != 0) readIndex++; } protected void setWriteAlignment(int align) { while(writeIndex % align != 0) writeOctet((byte)0x00); } private byte[] bytesFromHexString(String hexString) { int hexLen = hexString.length() / 2; byte[] result = new byte[hexLen]; for(int i = 0; i < hexLen; i ++) { String currentDigit = hexString.substring(2*i, 2*(i + 1)); Short s = Short.valueOf(currentDigit, 16); result[i] = s.byteValue(); } return result; } } // End of CDRCodec class private static class BigEndianCodec extends CDRCodec { public BigEndianCodec(String ior) { super(ior); writeOctet((byte)0x00); // Writes 'Big Endian' magic number } public BigEndianCodec(byte[] hexDigits) { super(hexDigits); writeOctet((byte)0x00); // Writes 'Big Endian' magic number } public short readShort() { setReadAlignment(2); short result = (short)((readBuffer[readIndex++] << 8) + readBuffer[readIndex++]); return result; } public int readLong() { setReadAlignment(4); int result = (readBuffer[readIndex++] << 24) + (readBuffer[readIndex++] << 16); result += (readBuffer[readIndex++] << 8) + readBuffer[readIndex++]; return result; } public long readLongLong() { setReadAlignment(8); long result = (readBuffer[readIndex++] << 56) + (readBuffer[readIndex++] << 48); result += (readBuffer[readIndex++] << 40) + (readBuffer[readIndex++] << 32); result += (readBuffer[readIndex++] << 24) + (readBuffer[readIndex++] << 16); result += (readBuffer[readIndex++] << 8) + readBuffer[readIndex++]; return result; } public void writeShort(short s) { setWriteAlignment(2); writeOctet((byte)((s & 0xFF00) >> 8)); writeOctet((byte)(s & 0x00FF)); } public void writeLong(int i) { setWriteAlignment(4); writeOctet((byte)((i & 0xFF000000) >> 24)); writeOctet((byte)((i & 0x00FF0000) >> 16)); writeOctet((byte)((i & 0x0000FF00) >> 8)); writeOctet((byte)(i & 0x000000FF)); } public void writeLongLong(long l) { setWriteAlignment(8); writeOctet((byte)((l & 0xFF00000000000000L) >> 56)); writeOctet((byte)((l & 0x00FF000000000000L) >> 48)); writeOctet((byte)((l & 0x0000FF0000000000L) >> 40)); writeOctet((byte)((l & 0x000000FF00000000L) >> 32)); writeOctet((byte)((l & 0x00000000FF000000L) >> 24)); writeOctet((byte)((l & 0x0000000000FF0000L) >> 16)); writeOctet((byte)((l & 0x000000000000FF00L) >> 8)); writeOctet((byte)(l & 0x00000000000000FFL)); } } // End of BigEndianCodec class private static class LittleEndianCodec extends CDRCodec { public LittleEndianCodec(String ior) { super(ior); writeOctet((byte)0x01); // Writes 'Little Endian' magic number } public LittleEndianCodec(byte[] hexDigits) { super(hexDigits); writeOctet((byte)0x01); // Writes 'Little Endian' magic number } public short readShort() { setReadAlignment(2); short result = (short)(readBuffer[readIndex++] + (readBuffer[readIndex++] << 8)); return result; } public int readLong() { setReadAlignment(4); int result = readBuffer[readIndex++] + (readBuffer[readIndex++] << 8) + (readBuffer[readIndex++] << 16) + (readBuffer[readIndex++] << 24); return result; } public long readLongLong() { setReadAlignment(8); long result = readBuffer[readIndex++] + (readBuffer[readIndex++] << 8); result += (readBuffer[readIndex++] << 16) + (readBuffer[readIndex++] << 24); result += (readBuffer[readIndex++] << 32) + (readBuffer[readIndex++] << 40); result += (readBuffer[readIndex++] << 48) + (readBuffer[readIndex++] << 56); return result; } public void writeShort(short s) { setWriteAlignment(2); writeOctet((byte)(s & 0x00FF)); writeOctet((byte)((s & 0xFF00) >> 8)); } public void writeLong(int i) { setWriteAlignment(4); writeOctet((byte)(i & 0x000000FF)); writeOctet((byte)((i & 0x0000FF00) >> 8)); writeOctet((byte)((i & 0x00FF0000) >> 16)); writeOctet((byte)((i & 0xFF000000) >> 24)); } public void writeLongLong(long l) { setWriteAlignment(8); writeOctet((byte)(l & 0x00000000000000FFL)); writeOctet((byte)((l & 0x000000000000FF00L) >> 8)); writeOctet((byte)((l & 0x0000000000FF0000L) >> 16)); writeOctet((byte)((l & 0x00000000FF000000L) >> 24)); writeOctet((byte)((l & 0x000000FF00000000L) >> 32)); writeOctet((byte)((l & 0x0000FF0000000000L) >> 40)); writeOctet((byte)((l & 0x00FF000000000000L) >> 48)); writeOctet((byte)((l & 0xFF00000000000000L) >> 56)); } } // End of LittleEndianCodec class public String getProto() { return "iiop"; } public String getHost() { return host; } public String getPort() { return Short.toString(port); } public String getFile() { return objectKey; } public String getAnchor() { return ""; } } // End of IIOPAddress class
package aQute.libg.cryptography; import java.util.*; import aQute.lib.hex.*; public abstract class Digest { final byte[] digest; protected Digest(byte[] checksum, int width) { this.digest = checksum; if (digest.length != width) throw new IllegalArgumentException("Invalid width for digest: " + digest.length + " expected " + width); } public byte[] digest() { return digest; } @Override public String toString() { return String.format("%s(d=%s)", getAlgorithm(), Hex.toHexString(digest)); } public abstract String getAlgorithm(); public boolean equals(Object other) { if ( !(other instanceof Digest)) return false; Digest d = (Digest) other; return Arrays.equals(d.digest, digest); } public int hashCode() { return Arrays.hashCode(digest); } }
package jade.mtp.iiop; import java.io.*; import java.util.List; import java.util.ArrayList; import java.util.Iterator; import java.util.Date; import java.util.Calendar; import java.util.StringTokenizer; import java.util.NoSuchElementException; import org.omg.CORBA.*; import org.omg.CosNaming.*; import FIPA.*; // OMG IDL Stubs import jade.core.AID; import jade.core.Profile; import jade.mtp.InChannel; import jade.mtp.OutChannel; import jade.mtp.MTP; import jade.mtp.MTPException; import jade.mtp.TransportAddress; import jade.domain.FIPAAgentManagement.Envelope; import jade.domain.FIPAAgentManagement.ReceivedObject; import jade.domain.FIPAAgentManagement.Property; //FIXME: if we add the method getSize() to all the slots whose value is a set // (e.g. intendedReceiver, userdefProperties, ...) we can improve a lot // performance in marshalling and unmarshalling. /** Implementation of <code><b>fipa.mts.mtp.iiop.std</b></code> specification for delivering ACL messages over the OMG IIOP transport protocol. @author Giovanni Rimassa - Universita' di Parma @version $Date$ $Revision$ */ public class MessageTransportProtocol implements MTP { private static class MTSImpl extends FIPA._MTSImplBase { private final InChannel.Dispatcher dispatcher; public MTSImpl(InChannel.Dispatcher disp) { dispatcher = disp; } public void message(FipaMessage aFipaMessage) { FIPA.Envelope[] envelopes = aFipaMessage.messageEnvelopes; byte[] payload = aFipaMessage.messageBody; Envelope env = new Envelope(); // Read all the envelopes sequentially, so that later slots // overwrite earlier ones. for(int e = 0; e < envelopes.length; e++) { FIPA.Envelope IDLenv = envelopes[e]; // Read in the 'to' slot if(IDLenv.to.length > 0) env.clearAllTo(); for(int i = 0; i < IDLenv.to.length; i++) { AID id = unmarshalAID(IDLenv.to[i]); env.addTo(id); } // Read in the 'from' slot if(IDLenv.from.length > 0) { AID id = unmarshalAID(IDLenv.from[0]); env.setFrom(id); } // Read in the 'intended-receiver' slot if(IDLenv.intendedReceiver.length > 0) env.clearAllIntendedReceiver(); for(int i = 0; i < IDLenv.intendedReceiver.length; i++) { AID id = unmarshalAID(IDLenv.intendedReceiver[i]); env.addIntendedReceiver(id); } // Read in the 'encrypted' slot //if(IDLenv.encrypted.length > 0) // env.clearAllEncrypted(); //for(int i = 0; i < IDLenv.encrypted.length; i++) { // String word = IDLenv.encrypted[i]; // env.addEncrypted(word); // Read in the other slots if(IDLenv.comments.length() > 0) env.setComments(IDLenv.comments); if(IDLenv.aclRepresentation.length() > 0) env.setAclRepresentation(IDLenv.aclRepresentation); if(IDLenv.payloadLength > 0) env.setPayloadLength(new Long(IDLenv.payloadLength)); if(IDLenv.payloadEncoding.length() > 0) env.setPayloadEncoding(IDLenv.payloadEncoding); if(IDLenv.date.length > 0) { Date d = unmarshalDateTime(IDLenv.date[0]); env.setDate(d); } // Read in the 'received' stamp if(IDLenv.received.length > 0) env.addStamp(unmarshalReceivedObj(IDLenv.received[0])); // Read in the 'user-defined properties' slot if(IDLenv.userDefinedProperties.length > 0) env.clearAllProperties(); for(int i = 0; i < IDLenv.userDefinedProperties.length; i++) { env.addProperties(unmarshalProperty(IDLenv.userDefinedProperties[i])); } } //String tmp = "\n\n"+(new java.util.Date()).toString()+" RECEIVED IIOP MESSAGE"+ "\n" + env.toString() + "\n" + new String(payload); //System.out.println(tmp); //MessageTransportProtocol.log(tmp); //Write in a log file for iiop incoming message // Dispatch the message dispatcher.dispatchMessage(env, payload); } private AID unmarshalAID(FIPA.AgentID id) { AID result = new AID(); result.setName(id.name); for(int i = 0; i < id.addresses.length; i++) result.addAddresses(id.addresses[i]); for(int i = 0; i < id.resolvers.length; i++) result.addResolvers(unmarshalAID(id.resolvers[i])); return result; } private Date unmarshalDateTime(FIPA.DateTime d) { Date result = new Date(); return result; } private Property unmarshalProperty(FIPA.Property p) { return new Property(p.keyword, p.value.extract_Value()); } private ReceivedObject unmarshalReceivedObj(FIPA.ReceivedObject ro) { ReceivedObject result = new ReceivedObject(); result.setBy(ro.by); result.setFrom(ro.from); result.setDate(unmarshalDateTime(ro.date)); result.setId(ro.id); result.setVia(ro.via); return result; } } // End of MTSImpl class private static final String[] PROTOCOLS = new String[] { "IOR", "corbaloc", "corbaname" }; private final ORB myORB; private MTSImpl server; private static PrintWriter logFile; public MessageTransportProtocol() { myORB = ORB.init(new String[0], null); } public TransportAddress activate(InChannel.Dispatcher disp, Profile p) throws MTPException { server = new MTSImpl(disp); myORB.connect(server); IIOPAddress iiop = new IIOPAddress(myORB, server); /* //Open log file String fileName = "iiop"+iiop.getHost()+iiop.getPort()+".log"; try{ logFile = new PrintWriter(new FileWriter(fileName,true)); }catch(java.io.IOException e){e .printStackTrace();} */ return iiop; } public void activate(InChannel.Dispatcher disp, TransportAddress ta, Profile p) throws MTPException { // throw new MTPException("User supplied transport address not supported."); // Do not throw, but modify the supplied address instead. IIOPAddress iia = (IIOPAddress)ta; IIOPAddress generated = (IIOPAddress)activate(disp, p); iia.initFromIOR(generated.getIOR()); } public void deactivate(TransportAddress ta) throws MTPException { myORB.disconnect(server); } public void deactivate() throws MTPException { myORB.disconnect(server); } public void deliver(String addr, Envelope env, byte[] payload) throws MTPException { try { TransportAddress ta = strToAddr(addr); IIOPAddress iiopAddr = (IIOPAddress)ta; FIPA.MTS objRef = iiopAddr.getObject(); // verifies if the server object really exists (useful if the IOR is // valid, i.e corresponds to a good object) (e.g. old IOR) // FIXME. To check if this call slows down performance if (objRef._non_existent()) throw new MTPException("Bad IIOP server object reference:" + objRef.toString()); // Fill in the 'to' field of the IDL envelope Iterator itTo = env.getAllTo(); List to = new ArrayList(); while(itTo.hasNext()) { AID id = (AID)itTo.next(); to.add(marshalAID(id)); } FIPA.AgentID[] IDLto = new FIPA.AgentID[to.size()]; for(int i = 0; i < to.size(); i++) IDLto[i] = (FIPA.AgentID)to.get(i); // Fill in the 'from' field of the IDL envelope AID from = env.getFrom(); FIPA.AgentID[] IDLfrom = new FIPA.AgentID[] { marshalAID(from) }; // Fill in the 'intended-receiver' field of the IDL envelope Iterator itIntendedReceiver = env.getAllIntendedReceiver(); List intendedReceiver = new ArrayList(); while(itIntendedReceiver.hasNext()) { AID id = (AID)itIntendedReceiver.next(); intendedReceiver.add(marshalAID(id)); } FIPA.AgentID[] IDLintendedReceiver = new FIPA.AgentID[intendedReceiver.size()]; for(int i = 0; i < intendedReceiver.size(); i++) IDLintendedReceiver[i] = (FIPA.AgentID)intendedReceiver.get(i); // Fill in the 'encrypted' field of the IDL envelope //Iterator itEncrypted = env.getAllEncrypted(); //List encrypted = new ArrayList(); //while(itEncrypted.hasNext()) { //String word = (String)itEncrypted.next(); //encrypted.add(word); String[] IDLencrypted = new String[0]; //String[] IDLencrypted = new String[encrypted.size()]; //for(int i = 0; i < encrypted.size(); i++) //IDLencrypted[i] = (String)encrypted.get(i); // Fill in the other fields of the IDL envelope ... String IDLcomments = (env.getComments() != null)?env.getComments():""; String IDLaclRepresentation = env.getAclRepresentation(); Long payloadLength = env.getPayloadLength(); int IDLpayloadLength = payloadLength.intValue(); String IDLpayloadEncoding = (env.getPayloadEncoding() != null)?env.getPayloadEncoding():""; FIPA.DateTime[] IDLdate = new FIPA.DateTime[] { marshalDateTime(env.getDate()) }; FIPA.Property[][] IDLtransportBehaviour = new FIPA.Property[][] { }; // Fill in the 'userdefined-properties' field of the IDL envelope Iterator itUserDefProps = env.getAllProperties(); List userDefProps = new ArrayList(); while(itUserDefProps.hasNext()) { Property p = (Property)itUserDefProps.next(); userDefProps.add(marshalProperty(p)); } FIPA.Property[] IDLuserDefinedProperties = new FIPA.Property[userDefProps.size()]; for(int i = 0; i < userDefProps.size(); i++) IDLuserDefinedProperties[i] = (FIPA.Property)userDefProps.get(i); // Fill in the list of 'received' stamps /* FIXME: Maybe several IDL Envelopes should be generated, one for every 'received' stamp... ReceivedObject[] received = env.getStamps(); FIPA.ReceivedObject[] IDLreceived = new FIPA.ReceivedObject[received.length]; for(int i = 0; i < received.length; i++) IDLreceived[i] = marshalReceivedObj(received[i]); */ // FIXME: For now, only the current 'received' object is considered... ReceivedObject received = env.getReceived(); FIPA.ReceivedObject[] IDLreceived; if(received != null) IDLreceived = new FIPA.ReceivedObject[] { marshalReceivedObj(received) }; else IDLreceived = new FIPA.ReceivedObject[] { }; FIPA.Envelope IDLenv = new FIPA.Envelope(IDLto, IDLfrom, IDLcomments, IDLaclRepresentation, IDLpayloadLength, IDLpayloadEncoding, IDLdate, IDLencrypted, IDLintendedReceiver, IDLreceived, IDLtransportBehaviour, IDLuserDefinedProperties); FipaMessage msg = new FipaMessage(new FIPA.Envelope[] { IDLenv }, payload); //String tmp = "\n\n"+(new java.util.Date()).toString()+" SENT IIOP MESSAGE"+ "\n" + env.toString() + "\n" + new String(payload); //System.out.println(tmp); //MessageTransportProtocol.log(tmp); // write in a log file for sent iiop message objRef.message(msg); } catch(ClassCastException cce) { cce.printStackTrace(); throw new MTPException("Address mismatch: this is not a valid IIOP address."); } catch(Exception cce2) { cce2.printStackTrace(); throw new MTPException("Address mismatch: this is not a valid IIOP address."); } } public TransportAddress strToAddr(String rep) throws MTPException { return new IIOPAddress(myORB, rep); // FIXME: Should cache object references } public String addrToStr(TransportAddress ta) throws MTPException { try { IIOPAddress addr = (IIOPAddress)ta; return addr.getIOR(); } catch(ClassCastException cce) { throw new MTPException("Address mismatch: this is not a valid IIOP address."); } } public String getName() { return jade.domain.FIPANames.MTP.IIOP; } public String[] getSupportedProtocols() { return PROTOCOLS; } private FIPA.Property marshalProperty(jade.domain.FIPAAgentManagement.Property p) { org.omg.CORBA.Any value = myORB.create_any(); java.lang.Object v = p.getValue(); if (v instanceof java.io.Serializable) { value.insert_Value((Serializable) v); } else { if (v != null) { value.insert_Value(v.toString()); } } return new FIPA.Property(p.getName(), value); } private FIPA.AgentID marshalAID(AID id) { String name = id.getName(); String[] addresses = id.getAddressesArray(); AID[] resolvers = id.getResolversArray(); FIPA.Property[] userDefinedProperties = new FIPA.Property[] { }; int numOfResolvers = resolvers.length; FIPA.AgentID result = new FIPA.AgentID(name, addresses, new AgentID[numOfResolvers], userDefinedProperties); for(int i = 0; i < numOfResolvers; i++) { result.resolvers[i] = marshalAID(resolvers[i]); // Recursively marshal all resolvers, which are, in turn, AIDs. } return result; } private FIPA.DateTime marshalDateTime(Date d) { Calendar cal = Calendar.getInstance(); cal.setTime(d); short year = (short)cal.get(Calendar.YEAR); short month = (short)cal.get(Calendar.MONTH); short day = (short)cal.get(Calendar.DAY_OF_MONTH); short hour = (short)cal.get(Calendar.HOUR_OF_DAY); short minutes = (short)cal.get(Calendar.MINUTE); short seconds = (short)cal.get(Calendar.SECOND); short milliseconds = 0; // FIXME: This is truncated to the second char typeDesignator = ' '; // FIXME: Uses local timezone ? FIPA.DateTime result = new FIPA.DateTime(year, month, day, hour, minutes, seconds, milliseconds, typeDesignator); return result; } private FIPA.ReceivedObject marshalReceivedObj(ReceivedObject ro) { FIPA.ReceivedObject result = new FIPA.ReceivedObject(); result.by = ro.getBy(); result.from = ro.getFrom(); result.date = marshalDateTime(ro.getDate()); result.id = ro.getId(); result.via = ro.getVia(); return result; } //Method to write on a file the iiop message log file /*public static synchronized void log(String str) { logFile.println(str); logFile.flush(); }*/ } // End of class MessageTransportProtocol /** This class represents an IIOP address. Three syntaxes are allowed for an IIOP address (all case-insensitive): <code> IIOPAddress ::= "ior:" (HexDigit HexDigit+) | "corbaname://" NSHost ":" NSPort "/" NSObjectID "#" objectName | "corbaloc:" HostName ":" portNumber "/" objectID </code> Notice that, in the third case, BIG_ENDIAN is assumed by default. In the first and second case, instead, the endianess information is contained within the IOR definition. **/ class IIOPAddress implements TransportAddress { public static final byte BIG_ENDIAN = 0; public static final byte LITTLE_ENDIAN = 1; private static final String FIPA_2000_TYPE_ID = "IDL:FIPA/MTS:1.0"; private static final String NS_TYPE_ID = "IDL:omg.org/CosNaming/NamingContext"; private static final int TAG_INTERNET_IOP = 0; private static final byte IIOP_MAJOR = 1; private static final byte IIOP_MINOR = 0; private static final byte ASCII_PERCENT = getASCIIByte("%"); private static final byte ASCII_UPPER_A = getASCIIByte("A"); private static final byte ASCII_UPPER_Z = getASCIIByte("Z"); private static final byte ASCII_LOWER_A = getASCIIByte("a"); private static final byte ASCII_LOWER_Z = getASCIIByte("z"); private static final byte ASCII_ZERO = getASCIIByte("0"); private static final byte ASCII_NINE = getASCIIByte("9"); private static final byte ASCII_MINUS = getASCIIByte("-"); private static final byte ASCII_UNDERSCORE = getASCIIByte("_"); private static final byte ASCII_DOT = getASCIIByte("."); private static final byte ASCII_BANG = getASCIIByte("!"); private static final byte ASCII_TILDE = getASCIIByte("~"); private static final byte ASCII_STAR = getASCIIByte("*"); private static final byte ASCII_QUOTE = getASCIIByte("'"); private static final byte ASCII_OPEN_BRACKET = getASCIIByte("("); private static final byte ASCII_CLOSED_BRACKET = getASCIIByte("$"); private static final char[] HEX = { '0','1','2','3','4','5','6','7', '8','9','a','b','c','d','e','f' }; private static final byte getASCIIByte(String ch) { try { return (ch.getBytes("US-ASCII"))[0]; } catch(UnsupportedEncodingException uee) { return 0; } } private final ORB orb; private String ior; private String host; private short port; private String objectKey; private String anchor; private CDRCodec codecStrategy; public IIOPAddress(ORB anOrb, FIPA.MTS objRef) throws MTPException { this(anOrb, anOrb.object_to_string(objRef)); } public IIOPAddress(ORB anOrb, String s) throws MTPException { orb = anOrb; if(s.toLowerCase().startsWith("ior:")) initFromIOR(s); else if(s.toLowerCase().startsWith("corbaloc:")) initFromURL(s, BIG_ENDIAN); else if(s.toLowerCase().startsWith("corbaname:")) initFromNS(s); else throw new MTPException("Invalid string prefix"); } void initFromIOR(String s) throws MTPException { parseIOR(s, FIPA_2000_TYPE_ID); anchor = ""; } private void initFromURL(String s, short endianness) throws MTPException { // Remove 'corbaloc:' prefix to get URL host, port and file s = s.substring(9); if(s.toLowerCase().startsWith("iiop:")) { // Remove an explicit IIOP specification s = s.substring(5); } else if(s.startsWith(":")) { // Remove implicit IIOP specification s = s.substring(1); } else throw new MTPException("Invalid 'corbaloc' URL: neither 'iiop:' nor ':' was specified."); buildIOR(s, FIPA_2000_TYPE_ID, endianness); } private void initFromNS(String s) throws MTPException { // First perform a 'corbaloc::' resolution to get the IOR of the Naming Service. // Replace 'corbaname:' with 'corbaloc::' StringBuffer buf = new StringBuffer(s); // Use 'corbaloc' support to build a reference on the NamingContext // where the real object reference will be looked up. buf.replace(0, 11, "corbaloc::"); buildIOR(s.substring(11), NS_TYPE_ID, BIG_ENDIAN); org.omg.CORBA.Object o = orb.string_to_object(ior); NamingContext ctx = NamingContextHelper.narrow(o); try { // Transform the string after the '#' sign into a COSNaming::Name. StringTokenizer lexer = new StringTokenizer(anchor, "/.", true); List name = new ArrayList(); while(lexer.hasMoreTokens()) { String tok = lexer.nextToken(); NameComponent nc = new NameComponent(); nc.id = tok; name.add(nc); if(!lexer.hasMoreTokens()) break; // Out of the while loop tok = lexer.nextToken(); if(tok.equals(".")) { // An (id, kind) pair tok = lexer.nextToken(); nc.kind = tok; } else if(!tok.equals("/")) // No separator other than '.' or '/' is allowed throw new MTPException("Ill-formed path into the Naming Service: Unknown separator."); } // Get the object reference stored into the naming service... NameComponent[] path = (NameComponent[])name.toArray(new NameComponent[name.size()]); o = ctx.resolve(path); // Stringify it and use the resulting IOR to initialize yourself String realIOR = orb.object_to_string(o); initFromIOR(realIOR); } catch(NoSuchElementException nsee) { throw new MTPException("Ill-formed path into the Naming Service.", nsee); } catch(UserException ue) { throw new MTPException("CORBA Naming Service user exception.", ue); } catch(SystemException se) { throw new MTPException("CORBA Naming Service system exception.", se); } } private void parseIOR(String s, String typeName) throws MTPException { try { // Store stringified IOR ior = new String(s.toUpperCase()); // Remove 'IOR:' prefix to get Hex digits String hexString = ior.substring(4); short endianness = Short.parseShort(hexString.substring(0, 2), 16); switch(endianness) { case BIG_ENDIAN: codecStrategy = new BigEndianCodec(hexString); break; case LITTLE_ENDIAN: codecStrategy = new LittleEndianCodec(hexString); break; default: throw new MTPException("Invalid endianness specifier"); } try { // Read 'string type_id' field String typeID = codecStrategy.readString(); if(!typeID.equalsIgnoreCase(typeName)) throw new MTPException("Invalid type ID" + typeID); } catch (Exception e) { // all exceptions are converted into MTPException throw new MTPException("Invalid type ID"); } // Read 'sequence<TaggedProfile> profiles' field // Read sequence length int seqLen = codecStrategy.readLong(); for(int i = 0; i < seqLen; i++) { // Read 'ProfileId tag' field int tag = codecStrategy.readLong(); byte[] profile = codecStrategy.readOctetSequence(); if(tag == TAG_INTERNET_IOP) { // Process IIOP profile CDRCodec profileBodyCodec; switch(profile[0]) { case BIG_ENDIAN: profileBodyCodec = new BigEndianCodec(profile); break; case LITTLE_ENDIAN: profileBodyCodec = new LittleEndianCodec(profile); break; default: throw new MTPException("Invalid endianness specifier"); } // Read IIOP version byte versionMajor = profileBodyCodec.readOctet(); byte versionMinor = profileBodyCodec.readOctet(); if(versionMajor != 1) throw new MTPException("IIOP version not supported"); try { // Read 'string host' field host = profileBodyCodec.readString(); } catch (Exception e) { throw new MTPException("Invalid host string"); } // Read 'unsigned short port' field port = profileBodyCodec.readShort(); // Read 'sequence<octet> object_key' field and convert it // into a String object byte[] keyBuffer = profileBodyCodec.readOctetSequence(); ByteArrayOutputStream buf = new ByteArrayOutputStream(); // Escape every forbidden character, as for RFC 2396 (URI: Generic Syntax) for(int ii = 0; ii < keyBuffer.length; ii++) { byte b = keyBuffer[ii]; if(isUnreservedURIChar(b)) { // Write the character 'as is' buf.write(b); } else { // Escape it using '%' buf.write(ASCII_PERCENT); buf.write(HEX[(b & 0xF0) >> 4]); // High nibble buf.write(HEX[b & 0x0F]); // Low nibble } } objectKey = buf.toString("US-ASCII"); codecStrategy = null; } } } catch (Exception e) { // all exceptions are converted into MTPException throw new MTPException(e.getMessage()); } } private void buildIOR(String s, String typeName, short endianness) throws MTPException { int colonPos = s.indexOf(':'); int slashPos = s.indexOf('/'); int poundPos = s.indexOf(' if((colonPos == -1) || (slashPos == -1)) throw new MTPException("Invalid URL string"); host = new String(s.substring(0, colonPos)); port = Short.parseShort(s.substring(colonPos + 1, slashPos)); if(poundPos == -1) { objectKey = new String(s.substring(slashPos + 1, s.length())); anchor = ""; } else { objectKey = new String(s.substring(slashPos + 1, poundPos)); anchor = new String(s.substring(poundPos + 1, s.length())); } switch(endianness) { case BIG_ENDIAN: codecStrategy = new BigEndianCodec(new byte[0]); break; case LITTLE_ENDIAN: codecStrategy = new LittleEndianCodec(new byte[0]); break; default: throw new MTPException("Invalid endianness specifier"); } codecStrategy.writeString(typeName); // Write '1' as profiles sequence length codecStrategy.writeLong(1); codecStrategy.writeLong(TAG_INTERNET_IOP); CDRCodec profileBodyCodec; switch(endianness) { case BIG_ENDIAN: profileBodyCodec = new BigEndianCodec(new byte[0]); break; case LITTLE_ENDIAN: profileBodyCodec = new LittleEndianCodec(new byte[0]); break; default: throw new MTPException("Invalid endianness specifier"); } // Write IIOP 1.0 profile to auxiliary CDR codec profileBodyCodec.writeOctet(IIOP_MAJOR); profileBodyCodec.writeOctet(IIOP_MINOR); profileBodyCodec.writeString(host); profileBodyCodec.writeShort(port); try { byte[] objKey = objectKey.getBytes("US-ASCII"); // Remove all the RFC 2396 escape sequences... ByteArrayOutputStream buf = new ByteArrayOutputStream(); for(int i = 0; i < objKey.length; i++) { byte b = objKey[i]; if(b != ASCII_PERCENT) buf.write(b); else { // Get the hex value represented by the two bytes after '%' try { String hexPair = new String(objKey, i + 1, 2, "US-ASCII"); short sh = Short.parseShort(hexPair, 16); if(sh > Byte.MAX_VALUE) b = (byte)(sh + 2*Byte.MIN_VALUE); // Conversion from unsigned to signed else b = (byte)sh; } catch(UnsupportedEncodingException uee) { b = 0; } buf.write(b); i += 2; } } profileBodyCodec.writeOctetSequence(buf.toByteArray()); byte[] encapsulatedProfile = profileBodyCodec.writtenBytes(); // Write encapsulated profile to main IOR codec codecStrategy.writeOctetSequence(encapsulatedProfile); String hexString = codecStrategy.writtenString(); ior = "IOR:" + hexString; codecStrategy = null; } catch(UnsupportedEncodingException uee) { // It should never happen uee.printStackTrace(); } } // This method returns true if and only if the supplied byte, // interpreted as an US-ASCII encoded character, corresponds to an // unreserved URI character. See RFC 2396 for details. private boolean isUnreservedURIChar(byte b) { // An upper case letter? if((ASCII_UPPER_A <= b)&&(ASCII_UPPER_Z >= b)) return true; // A lower case letter? if((ASCII_LOWER_A <= b)&&(ASCII_LOWER_Z >= b)) return true; // A decimal digit? if((ASCII_ZERO <= b)&&(ASCII_NINE >= b)) return true; // An unreserved, but not alphanumeric character? if((b == ASCII_MINUS)||(b == ASCII_UNDERSCORE)||(b == ASCII_DOT)||(b == ASCII_BANG)||(b == ASCII_TILDE)|| (b == ASCII_STAR)||(b == ASCII_QUOTE)||(b == ASCII_OPEN_BRACKET)||(b == ASCII_CLOSED_BRACKET)) return true; // Anything else is not allowed return false; } public String getURL() { int portNum = port; if(portNum < 0) portNum += 65536; return "corbaloc::" + host + ":" + portNum + "/" + objectKey; } public String getIOR() { return ior; } public FIPA.MTS getObject() { return FIPA.MTSHelper.narrow(orb.string_to_object(ior)); } private static abstract class CDRCodec { protected byte[] readBuffer; protected StringBuffer writeBuffer; protected int readIndex = 0; protected int writeIndex = 0; protected CDRCodec(String hexString) { // Put all Hex digits into a byte array readBuffer = bytesFromHexString(hexString); readIndex = 1; writeBuffer = new StringBuffer(255); } protected CDRCodec(byte[] hexDigits) { readBuffer = new byte[hexDigits.length]; System.arraycopy(hexDigits, 0, readBuffer, 0, readBuffer.length); readIndex = 1; writeBuffer = new StringBuffer(255); } public String writtenString() { return new String(writeBuffer); } public byte[] writtenBytes() { return bytesFromHexString(new String(writeBuffer)); } public byte readOctet() { return readBuffer[readIndex++]; } public byte[] readOctetSequence() { int seqLen = readLong(); byte[] result = new byte[seqLen]; System.arraycopy(readBuffer, readIndex, result, 0, seqLen); readIndex += seqLen; return result; } public String readString() { int strLen = readLong(); // This includes '\0' terminator String result = new String(readBuffer, readIndex, strLen - 1); readIndex += strLen; return result; } // These depend on endianness, so are deferred to subclasses public abstract short readShort(); // 16 bits public abstract int readLong(); // 32 bits public abstract long readLongLong(); // 64 bits // Writes a couple of hexadecimal digits representing the given byte. // All other marshalling operations ultimately use this method to modify // the write buffer public void writeOctet(byte b) { char[] digits = new char[2]; digits[0] = HEX[(b & 0xF0) >> 4]; // High nibble digits[1] = HEX[b & 0x0F]; // Low nibble writeBuffer.append(digits); writeIndex++; } public void writeOctetSequence(byte[] seq) { int seqLen = seq.length; writeLong(seqLen); for(int i = 0; i < seqLen; i++) writeOctet(seq[i]); } public void writeString(String s) { int strLen = s.length() + 1; // This includes '\0' terminator writeLong(strLen); byte[] bytes = s.getBytes(); for(int i = 0; i < s.length(); i++) writeOctet(bytes[i]); writeOctet((byte)0x00); } // These depend on endianness, so are deferred to subclasses public abstract void writeShort(short s); // 16 bits public abstract void writeLong(int i); // 32 bits public abstract void writeLongLong(long l); // 64 bits protected void setReadAlignment(int align) { while((readIndex % align) != 0) readIndex++; } protected void setWriteAlignment(int align) { while(writeIndex % align != 0) writeOctet((byte)0x00); } private byte[] bytesFromHexString(String hexString) { int hexLen = hexString.length() / 2; byte[] result = new byte[hexLen]; for(int i = 0; i < hexLen; i ++) { String currentDigit = hexString.substring(2*i, 2*(i + 1)); Short s = Short.valueOf(currentDigit, 16); result[i] = s.byteValue(); } return result; } } // End of CDRCodec class private static class BigEndianCodec extends CDRCodec { public BigEndianCodec(String ior) { super(ior); writeOctet((byte)0x00); // Writes 'Big Endian' magic number } public BigEndianCodec(byte[] hexDigits) { super(hexDigits); writeOctet((byte)0x00); // Writes 'Big Endian' magic number } public short readShort() { setReadAlignment(2); short result = (short)((readBuffer[readIndex++] << 8) + readBuffer[readIndex++]); return result; } public int readLong() { setReadAlignment(4); int result = (readBuffer[readIndex++] << 24) + (readBuffer[readIndex++] << 16); result += (readBuffer[readIndex++] << 8) + readBuffer[readIndex++]; return result; } public long readLongLong() { setReadAlignment(8); long result = (readBuffer[readIndex++] << 56) + (readBuffer[readIndex++] << 48); result += (readBuffer[readIndex++] << 40) + (readBuffer[readIndex++] << 32); result += (readBuffer[readIndex++] << 24) + (readBuffer[readIndex++] << 16); result += (readBuffer[readIndex++] << 8) + readBuffer[readIndex++]; return result; } public void writeShort(short s) { setWriteAlignment(2); writeOctet((byte)((s & 0xFF00) >> 8)); writeOctet((byte)(s & 0x00FF)); } public void writeLong(int i) { setWriteAlignment(4); writeOctet((byte)((i & 0xFF000000) >> 24)); writeOctet((byte)((i & 0x00FF0000) >> 16)); writeOctet((byte)((i & 0x0000FF00) >> 8)); writeOctet((byte)(i & 0x000000FF)); } public void writeLongLong(long l) { setWriteAlignment(8); writeOctet((byte)((l & 0xFF00000000000000L) >> 56)); writeOctet((byte)((l & 0x00FF000000000000L) >> 48)); writeOctet((byte)((l & 0x0000FF0000000000L) >> 40)); writeOctet((byte)((l & 0x000000FF00000000L) >> 32)); writeOctet((byte)((l & 0x00000000FF000000L) >> 24)); writeOctet((byte)((l & 0x0000000000FF0000L) >> 16)); writeOctet((byte)((l & 0x000000000000FF00L) >> 8)); writeOctet((byte)(l & 0x00000000000000FFL)); } } // End of BigEndianCodec class private static class LittleEndianCodec extends CDRCodec { public LittleEndianCodec(String ior) { super(ior); writeOctet((byte)0x01); // Writes 'Little Endian' magic number } public LittleEndianCodec(byte[] hexDigits) { super(hexDigits); writeOctet((byte)0x01); // Writes 'Little Endian' magic number } public short readShort() { setReadAlignment(2); short result = (short)(readBuffer[readIndex++] + (readBuffer[readIndex++] << 8)); return result; } public int readLong() { setReadAlignment(4); int result = readBuffer[readIndex++] + (readBuffer[readIndex++] << 8) + (readBuffer[readIndex++] << 16) + (readBuffer[readIndex++] << 24); return result; } public long readLongLong() { setReadAlignment(8); long result = readBuffer[readIndex++] + (readBuffer[readIndex++] << 8); result += (readBuffer[readIndex++] << 16) + (readBuffer[readIndex++] << 24); result += (readBuffer[readIndex++] << 32) + (readBuffer[readIndex++] << 40); result += (readBuffer[readIndex++] << 48) + (readBuffer[readIndex++] << 56); return result; } public void writeShort(short s) { setWriteAlignment(2); writeOctet((byte)(s & 0x00FF)); writeOctet((byte)((s & 0xFF00) >> 8)); } public void writeLong(int i) { setWriteAlignment(4); writeOctet((byte)(i & 0x000000FF)); writeOctet((byte)((i & 0x0000FF00) >> 8)); writeOctet((byte)((i & 0x00FF0000) >> 16)); writeOctet((byte)((i & 0xFF000000) >> 24)); } public void writeLongLong(long l) { setWriteAlignment(8); writeOctet((byte)(l & 0x00000000000000FFL)); writeOctet((byte)((l & 0x000000000000FF00L) >> 8)); writeOctet((byte)((l & 0x0000000000FF0000L) >> 16)); writeOctet((byte)((l & 0x00000000FF000000L) >> 24)); writeOctet((byte)((l & 0x000000FF00000000L) >> 32)); writeOctet((byte)((l & 0x0000FF0000000000L) >> 40)); writeOctet((byte)((l & 0x00FF000000000000L) >> 48)); writeOctet((byte)((l & 0xFF00000000000000L) >> 56)); } } // End of LittleEndianCodec class public String getProto() { return "iiop"; } public String getHost() { return host; } public String getPort() { return Short.toString(port); } public String getFile() { return objectKey; } public String getAnchor() { return anchor; } } // End of IIOPAddress class
package ViewManager; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.cassandra.db.marshal.ColumnToCollectionType; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.XMLConfiguration; import org.json.simple.JSONObject; import client.client.XmlHandler; import com.datastax.driver.core.Cluster; import com.datastax.driver.core.ColumnDefinitions; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.Row; import com.datastax.driver.core.Session; import com.datastax.driver.core.policies.DCAwareRoundRobinPolicy; import com.datastax.driver.core.policies.DefaultRetryPolicy; import com.datastax.driver.core.policies.TokenAwarePolicy; public class ViewManagerController { Cluster currentCluster = null; ViewManager vm = null; private static XMLConfiguration baseTableKeysConfig; List<String> baseTableName; List<String> pkName; List<String> deltaTableName; List<String> reverseTablesNames_Join; List<String> reverseTablesNames_AggJoin; List<String> reverseTablesNames_AggJoinGroupBy; List<String> preaggTableNames; List<String> preaggJoinTableNames; List<String> rj_joinTables; List<String> rj_joinKeys; List<String> rj_joinKeyTypes; List<String> rj_nrDelta; int rjoins; List<String> pkType; Stream stream = null; public ViewManagerController() { connectToCluster(); retrieveLoadXmlHandlers(); parseXmlMapping(); stream = new Stream(); vm = new ViewManager(currentCluster); } private void retrieveLoadXmlHandlers() { baseTableKeysConfig = new XMLConfiguration(); baseTableKeysConfig.setDelimiterParsingDisabled(true); try { baseTableKeysConfig .load("ViewManager/properties/baseTableKeys.xml"); } catch (ConfigurationException e) { e.printStackTrace(); } } public void parseXmlMapping() { baseTableName = baseTableKeysConfig.getList("tableSchema.table.name"); pkName = baseTableKeysConfig.getList("tableSchema.table.pkName"); pkType = baseTableKeysConfig.getList("tableSchema.table.pkType"); deltaTableName = VmXmlHandler.getInstance().getDeltaPreaggMapping() .getList("mapping.unit.deltaTable"); reverseTablesNames_Join = VmXmlHandler.getInstance().getRjJoinMapping() .getList("mapping.unit.reverseJoin"); reverseTablesNames_AggJoin = VmXmlHandler.getInstance() .getRjJoinMapping().getList("mapping.unit.reverseJoin"); reverseTablesNames_AggJoinGroupBy = VmXmlHandler.getInstance() .getRJAggJoinGroupByMapping() .getList("mapping.unit.reverseJoin"); rj_joinTables = VmXmlHandler.getInstance().getDeltaReverseJoinMapping() .getList("mapping.unit.Join.name"); rj_joinKeys = VmXmlHandler.getInstance().getDeltaReverseJoinMapping() .getList("mapping.unit.Join.JoinKey"); rj_joinKeyTypes = VmXmlHandler.getInstance() .getDeltaReverseJoinMapping().getList("mapping.unit.Join.type"); rj_nrDelta = VmXmlHandler.getInstance().getDeltaReverseJoinMapping() .getList("mapping.unit.nrDelta"); rjoins = VmXmlHandler.getInstance().getDeltaReverseJoinMapping() .getInt("mapping.nrUnit"); preaggTableNames = VmXmlHandler.getInstance().getHavingPreAggMapping() .getList("mapping.unit.preaggTable"); preaggJoinTableNames = VmXmlHandler.getInstance() .getHavingJoinAggMapping().getList("mapping.unit.preaggTable"); } private void connectToCluster() { currentCluster = Cluster .builder() .addContactPoint( XmlHandler.getInstance().getClusterConfig() .getString("config.host.localhost")) .withRetryPolicy(DefaultRetryPolicy.INSTANCE) .withLoadBalancingPolicy( new TokenAwarePolicy(new DCAwareRoundRobinPolicy())) .build(); } public void update(JSONObject json) { // get position of basetable from xml list // retrieve pk of basetable and delta from XML mapping file int indexBaseTableName = baseTableName.indexOf((String) json .get("table")); String baseTablePrimaryKey = pkName.get(indexBaseTableName); String baseTablePrimaryKeyType = pkType.get(indexBaseTableName); Row deltaUpdatedRow = null; // 1. update Delta Table // 1.a If successful, retrieve entire updated Row from Delta to pass on // as streams if (vm.updateDelta(json, indexBaseTableName, baseTablePrimaryKey)) { deltaUpdatedRow = vm.getDeltaUpdatedRow(); } // update selection view // for each delta, loop on all selection views possible // check if selection condition is met based on selection key // if yes then update selection, if not ignore // also compare old values of selection condition, if they have changed // then delete row from table int position1 = deltaTableName.indexOf("delta_" + (String) json.get("table")); if (position1 != -1) { String temp4 = "mapping.unit("; temp4 += Integer.toString(position1); temp4 += ")"; int nrConditions = VmXmlHandler.getInstance() .getDeltaSelectionMapping().getInt(temp4 + ".nrCond"); for (int i = 0; i < nrConditions; i++) { String s = temp4 + ".Cond(" + Integer.toString(i) + ")"; String selecTable = VmXmlHandler.getInstance() .getDeltaSelectionMapping().getString(s + ".name"); String nrAnd = VmXmlHandler.getInstance() .getDeltaSelectionMapping().getString(s + ".nrAnd"); boolean eval = true; boolean eval_old = true; for (int j = 0; j < Integer.parseInt(nrAnd); j++) { String s11 = s + ".And("; s11 += Integer.toString(j); s11 += ")"; String operation = VmXmlHandler.getInstance() .getDeltaSelectionMapping() .getString(s11 + ".operation"); String value = VmXmlHandler.getInstance() .getDeltaSelectionMapping() .getString(s11 + ".value"); String type = VmXmlHandler.getInstance() .getDeltaSelectionMapping() .getString(s11 + ".type"); String selColName = VmXmlHandler.getInstance() .getDeltaSelectionMapping() .getString(s11 + ".selectionCol"); switch (type) { case "text": if (operation.equals("=")) { if (deltaUpdatedRow.getString(selColName + "_new") .equals(value)) { eval &= true; } else { eval &= false; } if (deltaUpdatedRow.getString(selColName + "_old") == null) { eval_old = false; } else if (deltaUpdatedRow.getString( selColName + "_old").equals(value)) { eval_old &= true; } else { eval_old &= false; } } else if (operation.equals("!=")) { if (!deltaUpdatedRow.getString(selColName + "_new") .equals(value)) { eval = true; } else { eval = false; } if (deltaUpdatedRow.getString(selColName + "_old") == null) { eval_old = false; } else if (!deltaUpdatedRow.getString( selColName + "_old").equals(value)) { eval_old &= true; } else { eval_old &= false; } } break; case "varchar": if (operation.equals("=")) { if (deltaUpdatedRow.getString(selColName + "_new") .equals(value)) { eval &= true; } else { eval &= false; } if (deltaUpdatedRow.getString(selColName + "_old") == null) { eval_old = false; } else if (deltaUpdatedRow.getString( selColName + "_old").equals(value)) { eval_old &= true; } else { eval_old &= false; } } else if (operation.equals("!=")) { if (!deltaUpdatedRow.getString(selColName + "_new") .equals(value)) { eval &= true; } else { eval &= false; } if (deltaUpdatedRow.getString(selColName + "_old") == null) { eval_old = false; } else if (!deltaUpdatedRow.getString( selColName + "_old").equals(value)) { eval_old &= true; } else { eval_old &= false; } } break; case "int": // for _new col String s1 = Integer.toString(deltaUpdatedRow .getInt(selColName + "_new")); Integer valueInt = new Integer(s1); int compareValue = valueInt .compareTo(new Integer(value)); if ((operation.equals(">") && (compareValue > 0))) { eval &= true; } else if ((operation.equals("<") && (compareValue < 0))) { eval &= true; } else if ((operation.equals("=") && (compareValue == 0))) { eval &= true; } else { eval &= false; } // for _old col int v = deltaUpdatedRow.getInt(selColName + "_old"); compareValue = valueInt.compareTo(new Integer(v)); if ((operation.equals(">") && (compareValue > 0))) { eval_old &= true; } else if ((operation.equals("<") && (compareValue < 0))) { eval_old &= true; } else if ((operation.equals("=") && (compareValue == 0))) { eval_old &= true; } else { eval_old &= false; } break; case "varint": // for _new col s1 = deltaUpdatedRow.getVarint(selColName + "_new") .toString(); valueInt = new Integer(new BigInteger(s1).intValue()); compareValue = valueInt.compareTo(new Integer(value)); if ((operation.equals(">") && (compareValue > 0))) { eval &= true; } else if ((operation.equals("<") && (compareValue < 0))) { eval &= true; } else if ((operation.equals("=") && (compareValue == 0))) { eval &= true; } else { eval &= false; } // for _old col BigInteger bigInt = deltaUpdatedRow .getVarint(selColName + "_old"); if (bigInt != null) { valueInt = bigInt.intValue(); } else { valueInt = 0; } compareValue = valueInt.compareTo(new Integer(value)); if ((operation.equals(">") && (compareValue > 0))) { eval_old &= true; } else if ((operation.equals("<") && (compareValue < 0))) { eval_old &= true; } else if ((operation.equals("=") && (compareValue == 0))) { eval_old &= true; } else { eval_old &= false; } break; case "float": break; } } // if condition matching now & matched before if (eval && eval_old) { vm.updateSelection(deltaUpdatedRow, (String) json.get("keyspace"), selecTable, baseTablePrimaryKey); // if matching now & not matching before } else if (eval && !eval_old) { vm.updateSelection(deltaUpdatedRow, (String) json.get("keyspace"), selecTable, baseTablePrimaryKey); // if not matching now & matching before } else if (!eval && eval_old) { vm.deleteRowSelection(vm.getDeltaUpdatedRow(), (String) json.get("keyspace"), selecTable, baseTablePrimaryKey, json); // if not matching now & not before, ignore } } } // 2. for the delta table updated, get the depending preaggregation/agg // tables // preagg tables hold all column values, hence they have to be updated int position = deltaTableName.indexOf("delta_" + (String) json.get("table")); if (position != -1) { String temp = "mapping.unit("; temp += Integer.toString(position); temp += ")"; int nrPreagg = VmXmlHandler.getInstance().getDeltaPreaggMapping() .getInt(temp + ".nrPreagg"); for (int i = 0; i < nrPreagg; i++) { String s = temp + ".Preagg(" + Integer.toString(i) + ")"; String AggKey = VmXmlHandler.getInstance() .getDeltaPreaggMapping().getString(s + ".AggKey"); String AggKeyType = VmXmlHandler.getInstance() .getDeltaPreaggMapping().getString(s + ".AggKeyType"); String preaggTable = VmXmlHandler.getInstance() .getDeltaPreaggMapping().getString(s + ".name"); String AggCol = VmXmlHandler.getInstance() .getDeltaPreaggMapping().getString(s + ".AggCol"); String AggColType = VmXmlHandler.getInstance() .getDeltaPreaggMapping().getString(s + ".AggColType"); // 2.a after getting the preagg table name & neccessary // parameters, // check if aggKey in delta (_old & _new ) is null // if null then dont update, else update boolean isNull = checkIfAggIsNull(AggKey, deltaUpdatedRow); if (!isNull) { // WHERE clause condition evaluation String condName = VmXmlHandler.getInstance() .getDeltaPreaggMapping() .getString(s + ".Cond.name"); if (!condName.equals("none")) { String nrAnd = VmXmlHandler.getInstance() .getDeltaPreaggMapping() .getString(s + ".Cond.nrAnd"); boolean eval = true; String operation = ""; String value = ""; String type = ""; String colName = ""; for (int j = 0; j < Integer.parseInt(nrAnd); j++) { String s11 = s + ".Cond.And("; s11 += Integer.toString(j); s11 += ")"; operation = VmXmlHandler.getInstance() .getDeltaPreaggMapping() .getString(s11 + ".operation"); value = VmXmlHandler.getInstance() .getDeltaPreaggMapping() .getString(s11 + ".value"); type = VmXmlHandler.getInstance() .getDeltaPreaggMapping() .getString(s11 + ".type"); colName = VmXmlHandler.getInstance() .getDeltaPreaggMapping() .getString(s11 + ".selectionCol"); eval &= evaluateCondition(deltaUpdatedRow, operation, value, type, colName + "_new"); } System.out.println((String) json.get("table") + " condition is " + eval); // condition fulfilled if (eval) { // by passing the whole delta Row, we have agg key // value // even if it is not in json vm.updatePreaggregation(deltaUpdatedRow, AggKey, AggKeyType, json, preaggTable, baseTablePrimaryKey, AggCol, AggColType, false, false); } else { // cascade delete String pkVAlue = ""; switch (baseTablePrimaryKeyType) { case "int": pkVAlue = Integer.toString(deltaUpdatedRow .getInt(baseTablePrimaryKey)); break; case "float": pkVAlue = Float.toString(deltaUpdatedRow .getFloat(baseTablePrimaryKey)); break; case "varint": pkVAlue = deltaUpdatedRow.getVarint( baseTablePrimaryKey).toString(); break; case "varchar": pkVAlue = deltaUpdatedRow .getString(baseTablePrimaryKey); break; case "text": pkVAlue = deltaUpdatedRow .getString(baseTablePrimaryKey); break; } boolean eval_old = evaluateCondition( deltaUpdatedRow, operation, value, type, colName + "_old"); if (eval_old) { // 1. retrieve the row to be deleted from delta // table StringBuilder selectQuery = new StringBuilder( "SELECT *"); selectQuery.append(" FROM ") .append(json.get("keyspace")) .append(".") .append("delta_" + json.get("table")) .append(" WHERE ") .append(baseTablePrimaryKey) .append(" = ").append(pkVAlue) .append(";"); System.out.println(selectQuery); ResultSet selectionResult; try { Session session = currentCluster.connect(); selectionResult = session .execute(selectQuery.toString()); } catch (Exception e) { e.printStackTrace(); return; } // 2. set DeltaDeletedRow variable for streaming vm.setDeltaDeletedRow(selectionResult.one()); cascadeDelete(json, false); } // continue continue; } } else { // by passing the whole delta Row, we have agg key value // even if it is not in json vm.updatePreaggregation(deltaUpdatedRow, AggKey, AggKeyType, json, preaggTable, baseTablePrimaryKey, AggCol, AggColType, false, false); } } // 2.1 update preaggregations with having clause // check if preagg has some having clauses or not position = preaggTableNames.indexOf(preaggTable); if (position1 != -1) { String temp4 = "mapping.unit("; temp4 += Integer.toString(position1); temp4 += ")"; int nrConditions = VmXmlHandler.getInstance() .getHavingPreAggMapping().getInt(temp4 + ".nrCond"); for (int m = 0; m < nrConditions; m++) { String s1 = temp4 + ".Cond(" + Integer.toString(m) + ")"; String havingTable = VmXmlHandler.getInstance() .getHavingPreAggMapping() .getString(s1 + ".name"); String nrAnd = VmXmlHandler.getInstance() .getHavingPreAggMapping() .getString(s1 + ".nrAnd"); boolean eval1 = true; boolean eval2 = true; for (int n = 0; n < Integer.parseInt(nrAnd); n++) { String s11 = s1 + ".And("; s11 += Integer.toString(n); s11 += ")"; String aggFct = VmXmlHandler.getInstance() .getHavingPreAggMapping() .getString(s11 + ".aggFct"); String operation = VmXmlHandler.getInstance() .getHavingPreAggMapping() .getString(s11 + ".operation"); String value = VmXmlHandler.getInstance() .getHavingPreAggMapping() .getString(s11 + ".value"); String type = VmXmlHandler.getInstance() .getHavingPreAggMapping() .getString(s11 + ".type"); String selColName = VmXmlHandler.getInstance() .getHavingPreAggMapping() .getString(s11 + ".selectionCol"); Row PreagRow = vm.getUpdatedPreaggRow(); Row PreagRowAK = vm.getUpdatedPreaggRowChangeAK(); float min1 = PreagRow.getFloat("min"); float max1 = PreagRow.getFloat("max"); float average1 = PreagRow.getFloat("average"); float sum1 = PreagRow.getFloat("sum"); int count1 = PreagRow.getInt("count"); float min2 = 0; float max2 = 0; float average2 = 0; float sum2 = 0; int count2 = 0; if (PreagRowAK != null) { min2 = PreagRowAK.getFloat("min"); max2 = PreagRowAK.getFloat("max"); average2 = PreagRowAK.getFloat("average"); sum2 = PreagRowAK.getFloat("sum"); count2 = PreagRowAK.getInt("count"); } if (aggFct.equals("sum")) { int compareValue = new Float(sum1) .compareTo(new Float(value)); if ((operation.equals(">") && (compareValue > 0))) { eval1 &= true; } else if ((operation.equals("<") && (compareValue < 0))) { eval1 &= true; } else if ((operation.equals("=") && (compareValue == 0))) { eval1 &= true; } else { eval1 &= false; } if (PreagRowAK != null) { compareValue = new Float(sum2) .compareTo(new Float(value)); if ((operation.equals(">") && (compareValue > 0))) { eval2 &= true; } else if ((operation.equals("<") && (compareValue < 0))) { eval2 &= true; } else if ((operation.equals("=") && (compareValue == 0))) { eval2 &= true; } else { eval2 &= false; } } } else if (aggFct.equals("average")) { int compareValue = Float.compare(average1, Float.valueOf(value)); if ((operation.equals(">") && (compareValue > 0))) { eval1 &= true; } else if ((operation.equals("<") && (compareValue < 0))) { eval1 &= true; } else if ((operation.equals("=") && (compareValue == 0))) { eval1 &= true; } else { eval1 &= false; } if (PreagRowAK != null) { compareValue = Float.compare(average2, Float.valueOf(value)); if ((operation.equals(">") && (compareValue > 0))) { eval1 &= true; } else if ((operation.equals("<") && (compareValue < 0))) { eval1 &= true; } else if ((operation.equals("=") && (compareValue == 0))) { eval1 &= true; } else { eval1 &= false; } } } else if (aggFct.equals("count")) { int compareValue = new Integer(count1) .compareTo(new Integer(value)); if ((operation.equals(">") && (compareValue > 0))) { eval1 &= true; } else if ((operation.equals("<") && (compareValue < 0))) { eval1 &= true; } else if ((operation.equals("=") && (compareValue == 0))) { eval1 &= true; } else { eval1 &= false; } if (PreagRowAK != null) { compareValue = new Integer(count2) .compareTo(new Integer(value)); if ((operation.equals(">") && (compareValue > 0))) { eval2 &= true; } else if ((operation.equals("<") && (compareValue < 0))) { eval2 &= true; } else if ((operation.equals("=") && (compareValue == 0))) { eval2 &= true; } else { eval2 &= false; } } } else if (aggFct.equals("min")) { int compareValue = Float.compare(min1, Float.valueOf(value)); if ((operation.equals(">") && (compareValue > 0))) { eval1 &= true; } else if ((operation.equals("<") && (compareValue < 0))) { eval1 &= true; } else if ((operation.equals("=") && (compareValue == 0))) { eval1 &= true; } else { eval1 &= false; } if (PreagRowAK != null) { compareValue = Float.compare(min2, Float.valueOf(value)); if ((operation.equals(">") && (compareValue > 0))) { eval1 &= true; } else if ((operation.equals("<") && (compareValue < 0))) { eval1 &= true; } else if ((operation.equals("=") && (compareValue == 0))) { eval1 &= true; } else { eval1 &= false; } } } else if (aggFct.equals("max")) { int compareValue = Float.compare(max1, Float.valueOf(value)); if ((operation.equals(">") && (compareValue > 0))) { eval1 &= true; } else if ((operation.equals("<") && (compareValue < 0))) { eval1 &= true; } else if ((operation.equals("=") && (compareValue == 0))) { eval1 &= true; } else { eval1 &= false; } if (PreagRowAK != null) { compareValue = Float.compare(max2, Float.valueOf(value)); if ((operation.equals(">") && (compareValue > 0))) { eval2 &= true; } else if ((operation.equals("<") && (compareValue < 0))) { eval2 &= true; } else if ((operation.equals("=") && (compareValue == 0))) { eval2 &= true; } else { eval2 &= false; } } } // if matching now & not matching before // if condition matching now & matched before if (eval1) { vm.updateHaving(deltaUpdatedRow, (String) json.get("keyspace"), havingTable, PreagRow); if (PreagRowAK != null && eval2) { vm.updateHaving(deltaUpdatedRow, (String) json.get("keyspace"), havingTable, PreagRowAK); } // if not matching now } else if (!eval1) { vm.deleteRowHaving(deltaUpdatedRow, (String) json.get("keyspace"), havingTable, PreagRow); if (PreagRowAK != null && !eval2) { vm.deleteRowHaving(deltaUpdatedRow, (String) json.get("keyspace"), havingTable, PreagRowAK); } // if not matching now & not before, ignore } Row deletedRow = vm.getUpdatedPreaggRowDeleted(); if (deletedRow != null) { vm.deleteRowHaving(deltaUpdatedRow, (String) json.get("keyspace"), havingTable, deletedRow); } } } } else { System.out .println("No Having table for this joinpreaggregation Table " + preaggTable + " available"); } } } // End of updating preagg with having clause else { System.out.println("No Preaggregation table for this delta table " + " delta_" + (String) json.get("table") + " available"); } // 3. for the delta table updated, get update depending reverse join // tables int cursor = 0; for (int j = 0; j < rjoins; j++) { // basetables int nrOfTables = Integer.parseInt(rj_nrDelta.get(j)); String joinTable = rj_joinTables.get(j); // include only indices from 1 to nrOfTables // get basetables from name of rj table List<String> baseTables = Arrays.asList( rj_joinTables.get(j).split("_")).subList(1, nrOfTables + 1); String tableName = (String) json.get("table"); String keyspace = (String) json.get("keyspace"); int column = baseTables.indexOf(tableName) + 1; String joinKeyName = rj_joinKeys.get(cursor + column - 1); String joinKeyType = rj_joinKeyTypes.get(j); if (column == 0) { System.out.println("No ReverseJoin for this delta update"); continue; } // Check on where clause for join // WHERE clause condition evaluation position = VmXmlHandler.getInstance().getDeltaReverseJoinMapping() .getList("mapping.unit.Join.name").indexOf(joinTable); if (position != -1) { String temp = "mapping.unit("; temp += Integer.toString(position); temp += ").Join"; String condName = VmXmlHandler.getInstance() .getDeltaReverseJoinMapping() .getString(temp + ".Cond.name"); List<String> baseTableNames = new ArrayList<>(); String otherTable = ""; if (!condName.equals("none")) { baseTableNames = VmXmlHandler.getInstance() .getDeltaReverseJoinMapping() .getList(temp + ".Cond.table.name"); otherTable = VmXmlHandler.getInstance() .getDeltaReverseJoinMapping() .getString(temp + ".Cond.otherTable"); if (!baseTableNames.contains((String) json.get("table")) && !otherTable.equals((String) json.get("table"))) { continue; } } // to override the next if condition,to update the reverse join if (otherTable.equals((String) json.get("table"))) { condName = "none"; } if (!condName.equals("none")) { String nrAnd = VmXmlHandler.getInstance() .getDeltaReverseJoinMapping() .getString(temp + ".Cond.nrAnd"); boolean eval = true; String operation = ""; String value = ""; String type = ""; String colName = ""; for (int jj = 0; jj < Integer.parseInt(nrAnd); jj++) { String s11 = temp + ".Cond.And("; s11 += Integer.toString(jj); s11 += ")"; operation = VmXmlHandler.getInstance() .getDeltaReverseJoinMapping() .getString(s11 + ".operation"); value = VmXmlHandler.getInstance() .getDeltaReverseJoinMapping() .getString(s11 + ".value"); type = VmXmlHandler.getInstance() .getDeltaReverseJoinMapping() .getString(s11 + ".type"); colName = VmXmlHandler.getInstance() .getDeltaReverseJoinMapping() .getString(s11 + ".selectionCol"); eval &= evaluateCondition(deltaUpdatedRow, operation, value, type, colName + "_new"); } System.out.println((String) json.get("table") + " condition is " + eval); // condition fulfilled if (eval) { // by passing the whole delta Row, we have agg key // value // even if it is not in json vm.updateReverseJoin(json, cursor, nrOfTables, joinTable, baseTables, joinKeyName, tableName, keyspace, joinKeyType, column); } else { String pkVAlue = ""; switch (baseTablePrimaryKeyType) { case "int": pkVAlue = Integer.toString(deltaUpdatedRow .getInt(baseTablePrimaryKey)); break; case "float": pkVAlue = Float.toString(deltaUpdatedRow .getFloat(baseTablePrimaryKey)); break; case "varint": pkVAlue = deltaUpdatedRow.getVarint( baseTablePrimaryKey).toString(); break; case "varchar": pkVAlue = deltaUpdatedRow .getString(baseTablePrimaryKey); break; case "text": pkVAlue = deltaUpdatedRow .getString(baseTablePrimaryKey); break; } boolean eval_old = evaluateCondition(deltaUpdatedRow, operation, value, type, colName + "_old"); if (eval_old) { // 1. retrieve the row to be deleted from delta // table StringBuilder selectQuery = new StringBuilder( "SELECT *"); selectQuery.append(" FROM ") .append(json.get("keyspace")).append(".") .append("delta_" + json.get("table")) .append(" WHERE ") .append(baseTablePrimaryKey).append(" = ") .append(pkVAlue).append(";"); System.out.println(selectQuery); ResultSet selectionResult; try { Session session = currentCluster.connect(); selectionResult = session.execute(selectQuery .toString()); } catch (Exception e) { e.printStackTrace(); return; } // 2. set DeltaDeletedRow variable for streaming vm.setDeltaDeletedRow(selectionResult.one()); cascadeDelete(json, false); } // continue continue; } } else { // by passing the whole delta Row, we have agg key value // even if it is not in json vm.updateReverseJoin(json, cursor, nrOfTables, joinTable, baseTables, joinKeyName, tableName, keyspace, joinKeyType, column); } } // HERE UPDATE JOIN TABLES // 4. update Join tables String updatedReverseJoin = vm.getReverseJoinName(); position = reverseTablesNames_Join.indexOf(updatedReverseJoin); if (position != -1) { String temp = "mapping.unit("; temp += Integer.toString(position); temp += ")"; int nrJoin = VmXmlHandler.getInstance().getRjJoinMapping() .getInt(temp + ".nrJoin"); for (int i = 0; i < nrJoin; i++) { String s = temp + ".join(" + Integer.toString(i) + ")"; String innerJoinTableName = VmXmlHandler.getInstance() .getRjJoinMapping().getString(s + ".innerJoin"); String leftJoinTableName = VmXmlHandler.getInstance() .getRjJoinMapping().getString(s + ".leftJoin"); String rightJoinTableName = VmXmlHandler.getInstance() .getRjJoinMapping().getString(s + ".rightJoin"); String leftJoinTable = VmXmlHandler.getInstance() .getRjJoinMapping().getString(s + ".LeftTable"); String rightJoinTable = VmXmlHandler.getInstance() .getRjJoinMapping().getString(s + ".RightTable"); tableName = (String) json.get("table"); Boolean updateLeft = false; Boolean updateRight = false; if (tableName.equals(leftJoinTable)) { updateLeft = true; } else { updateRight = true; } vm.updateJoinController(deltaUpdatedRow, innerJoinTableName, leftJoinTableName, rightJoinTableName, json, updateLeft, updateRight, joinKeyType, joinKeyName, baseTablePrimaryKey); } } else { System.out.println("No join table for this reverse join table " + updatedReverseJoin + " available"); } // UPDATE join agg int positionAgg = reverseTablesNames_AggJoin.indexOf(joinTable); if (positionAgg != -1) { String temp = "mapping.unit("; temp += Integer.toString(positionAgg); temp += ")"; Boolean updateLeft = false; Boolean updateRight = false; String leftJoinTable = VmXmlHandler.getInstance() .getRJAggJoinMapping().getString(temp + ".LeftTable"); String rightJoinTable = VmXmlHandler.getInstance() .getRJAggJoinMapping().getString(temp + ".RightTable"); tableName = (String) json.get("table"); if (tableName.equals(leftJoinTable)) { updateLeft = true; } else { updateRight = true; } int nrLeftAggColumns = VmXmlHandler.getInstance() .getRJAggJoinMapping() .getInt(temp + ".leftAggColumns.nr"); for (int e = 0; e < nrLeftAggColumns; e++) { String aggColName = VmXmlHandler .getInstance() .getRJAggJoinMapping() .getString( temp + ".leftAggColumns.c(" + e + ").name"); String aggColType = VmXmlHandler .getInstance() .getRJAggJoinMapping() .getString( temp + ".leftAggColumns.c(" + e + ").type"); String innerJoinAggTable = VmXmlHandler .getInstance() .getRJAggJoinMapping() .getString( temp + ".leftAggColumns.c(" + e + ").inner.name"); String leftJoinAggTable = VmXmlHandler .getInstance() .getRJAggJoinMapping() .getString( temp + ".leftAggColumns.c(" + e + ").left.name"); int index = VmXmlHandler .getInstance() .getRJAggJoinMapping() .getInt(temp + ".leftAggColumns.c(" + e + ").index"); if (updateLeft) { vm.updateJoinAgg_UpdateLeft_AggColLeftSide(stream, innerJoinAggTable, leftJoinAggTable, json, joinKeyType, joinKeyName, aggColName, aggColType); } else { vm.updateJoinAgg_UpdateRight_AggColLeftSide(stream, innerJoinAggTable, leftJoinAggTable, json, joinKeyType, joinKeyName, aggColName, aggColType, index); } if(!leftJoinAggTable.equals("false")){ evaluateLeftorRightJoinAggHaving(temp,"leftAggColumns", e, json,"left"); } if(!innerJoinAggTable.equals("false")){ evaluateInnerJoinAggHaving(temp, "leftAggColumns", e, json); } stream.resetJoinAggRows(); } int nrRightAggColumns = VmXmlHandler.getInstance() .getRJAggJoinMapping() .getInt(temp + ".rightAggColumns.nr"); for (int e = 0; e < nrRightAggColumns; e++) { String aggColName = VmXmlHandler .getInstance() .getRJAggJoinMapping() .getString( temp + ".rightAggColumns.c(" + e + ").name"); String aggColType = VmXmlHandler .getInstance() .getRJAggJoinMapping() .getString( temp + ".rightAggColumns.c(" + e + ").type"); String innerJoinAggTable = VmXmlHandler .getInstance() .getRJAggJoinMapping() .getString( temp + ".rightAggColumns.c(" + e + ").inner.name"); String rightJoinAggTable = VmXmlHandler .getInstance() .getRJAggJoinMapping() .getString( temp + ".rightAggColumns.c(" + e + ").right.name"); int index = VmXmlHandler .getInstance() .getRJAggJoinMapping() .getInt(temp + ".rightAggColumns.c(" + e + ").index"); if (updateLeft) { vm.updateJoinAgg_UpdateLeft_AggColRightSide(stream, innerJoinAggTable, rightJoinAggTable, json, joinKeyType, joinKeyName, aggColName, aggColType, index); } else { vm.updateJoinAgg_UpdateRight_AggColRightSide(stream, innerJoinAggTable, rightJoinAggTable, json, joinKeyType, joinKeyName, aggColName, aggColType); } if(!rightJoinAggTable.equals("false")){ evaluateLeftorRightJoinAggHaving(temp,"rightAggColumns", e, json,"right"); } if(!innerJoinAggTable.equals("false")){ evaluateInnerJoinAggHaving(temp, "rightAggColumns", e, json); } stream.resetJoinAggRows(); } } // Update Group By Join Agg clauses int positionAggGroupBy = reverseTablesNames_AggJoinGroupBy .indexOf(joinTable); if (positionAggGroupBy != -1) { String temp = "mapping.unit("; temp += Integer.toString(positionAggGroupBy); temp += ")"; Boolean updateLeft = false; Boolean updateRight = false; String leftJoinTable = VmXmlHandler.getInstance() .getRJAggJoinGroupByMapping() .getString(temp + ".LeftTable"); String rightJoinTable = VmXmlHandler.getInstance() .getRJAggJoinGroupByMapping() .getString(temp + ".RightTable"); tableName = (String) json.get("table"); if (tableName.equals(leftJoinTable)) { updateLeft = true; } else { updateRight = true; } int nrLeftAggColumns = VmXmlHandler.getInstance() .getRJAggJoinGroupByMapping() .getInt(temp + ".leftAggColumns.nr"); for (int e = 0; e < nrLeftAggColumns; e++) { String aggColName = VmXmlHandler .getInstance() .getRJAggJoinGroupByMapping() .getString( temp + ".leftAggColumns.c(" + e + ").name"); String aggColType = VmXmlHandler .getInstance() .getRJAggJoinGroupByMapping() .getString( temp + ".leftAggColumns.c(" + e + ").type"); int nrAgg = VmXmlHandler .getInstance() .getRJAggJoinGroupByMapping() .getInt(temp + ".leftAggColumns.c(" + e + ").nrAgg"); for (int i = 0; i < nrAgg; i++) { String innerJoinAggTable = VmXmlHandler .getInstance() .getRJAggJoinGroupByMapping() .getString( temp + ".leftAggColumns.c(" + e + ").Agg(" + i + ").inner.name"); String leftJoinAggTable = VmXmlHandler .getInstance() .getRJAggJoinGroupByMapping() .getString( temp + ".leftAggColumns.c(" + e + ").Agg(" + i + ").left.name"); String Key = VmXmlHandler .getInstance() .getRJAggJoinGroupByMapping() .getString( temp + ".leftAggColumns.c(" + e + ").Agg(" + i + ").Key"); String KeyType = VmXmlHandler .getInstance() .getRJAggJoinGroupByMapping() .getString( temp + ".leftAggColumns.c(" + e + ").Agg(" + i + ").KeyType"); int index = VmXmlHandler .getInstance() .getRJAggJoinGroupByMapping() .getInt(temp + ".leftAggColumns.c(" + e + ").index"); int AggKeyIndex = VmXmlHandler .getInstance() .getRJAggJoinGroupByMapping() .getInt(temp + ".leftAggColumns.c(" + e + ").Agg(" + i + ").aggKeyIndex"); if (updateLeft) { vm.updateJoinAgg_UpdateLeft_AggColLeftSide_GroupBy(stream, innerJoinAggTable, leftJoinAggTable, json, KeyType, Key, aggColName, aggColType, joinKeyName, joinKeyType); } else { vm.updateJoinAgg_UpdateRight_AggColLeftSide_GroupBy(stream, innerJoinAggTable, leftJoinAggTable, json, joinKeyType, joinKeyName, aggColName, aggColType, index, Key, KeyType, AggKeyIndex); } //evalute Left Having if(!leftJoinAggTable.equals("false")){ evaluateLeftorRightJoinAggGroupByHaving(i,e,temp,json,"left"); } //evalute Inner Having if(!innerJoinAggTable.equals("false")){ evaluateInnerJoinAggGroupByHaving(i,e,temp,json,"leftAggColumns"); } stream.resetJoinAggGroupByUpRows(); } } int nrRightAggColumns = VmXmlHandler.getInstance() .getRJAggJoinGroupByMapping() .getInt(temp + ".rightAggColumns.nr"); for (int e = 0; e < nrRightAggColumns; e++) { String aggColName = VmXmlHandler .getInstance() .getRJAggJoinGroupByMapping() .getString( temp + ".rightAggColumns.c(" + e + ").name"); String aggColType = VmXmlHandler .getInstance() .getRJAggJoinGroupByMapping() .getString( temp + ".rightAggColumns.c(" + e + ").type"); int nrAgg = VmXmlHandler .getInstance() .getRJAggJoinGroupByMapping() .getInt(temp + ".rightAggColumns.c(" + e + ").nrAgg"); for (int i = 0; i < nrAgg; i++) { String Key = VmXmlHandler .getInstance() .getRJAggJoinGroupByMapping() .getString( temp + ".rightAggColumns.c(" + e + ").Agg(" + i + ").Key"); String KeyType = VmXmlHandler .getInstance() .getRJAggJoinGroupByMapping() .getString( temp + ".rightAggColumns.c(" + e + ").Agg(" + i + ").KeyType"); int index = VmXmlHandler .getInstance() .getRJAggJoinGroupByMapping() .getInt(temp + ".rightAggColumns.c(" + e + ").index"); String innerJoinAggTable = VmXmlHandler .getInstance() .getRJAggJoinGroupByMapping() .getString( temp + ".rightAggColumns.c(" + e + ").Agg(" + i + ").inner"); String rightJoinAggTable = VmXmlHandler .getInstance() .getRJAggJoinGroupByMapping() .getString( temp + ".rightAggColumns.c(" + e + ").Agg(" + i + ").right"); int AggKeyIndex = VmXmlHandler .getInstance() .getRJAggJoinGroupByMapping() .getInt(temp + ".rightAggColumns.c(" + e + ").Agg(" + i + ").aggKeyIndex"); if (updateLeft) { vm.updateJoinAgg_UpdateLeft_AggColRightSide_GroupBy(stream, innerJoinAggTable, rightJoinAggTable, json, joinKeyType, joinKeyName, aggColName, aggColType, index, Key, KeyType, AggKeyIndex); } else { vm.updateJoinAgg_UpdateRight_AggColRightSide_GroupBy(stream, innerJoinAggTable, rightJoinAggTable, json, KeyType, Key, aggColName, aggColType, joinKeyName, joinKeyType); } //evalute Left Having if(!rightJoinAggTable.equals("false")){ evaluateLeftorRightJoinAggGroupByHaving(i,e,temp,json,"right"); } //evalute Inner Having if(!innerJoinAggTable.equals("false")){ evaluateInnerJoinAggGroupByHaving(i,e,temp,json,"rightAggColumns"); } stream.resetJoinAggGroupByUpRows(); } } } // END OF UPDATE JoinPreag cursor += nrOfTables; } } private void evaluateLeftorRightJoinAggHaving(String temp, String aggColPosition, int e, JSONObject json, String leftOrRight) { Integer nrHaving = VmXmlHandler.getInstance() .getRJAggJoinMapping().getInt(temp + "." +aggColPosition+".c(" + e + ")."+leftOrRight+".nrHaving"); if(nrHaving!=0){ List<String> innerHaving = VmXmlHandler.getInstance() .getRJAggJoinMapping().getList(temp + "." +aggColPosition+".c(" + e + ")."+leftOrRight+".Having.name"); List<String> aggFct = VmXmlHandler.getInstance() .getRJAggJoinMapping().getList(temp + "." +aggColPosition+".c(" + e + ")."+leftOrRight+".Having.And.aggFct"); List<String> innerHavingType = VmXmlHandler.getInstance() .getRJAggJoinMapping().getList(temp + "." +aggColPosition+".c(" + e + ")."+leftOrRight+".Having.And.type"); List<String> operation = VmXmlHandler.getInstance() .getRJAggJoinMapping().getList(temp + "." +aggColPosition+".c(" + e + ")."+leftOrRight+".Having.And.operation"); List<String> value = VmXmlHandler.getInstance() .getRJAggJoinMapping().getList(temp + "." +aggColPosition+".c(" + e + ")."+leftOrRight+".Having.And.value"); for(int j=0;j<nrHaving;j++){ if(stream.getLeftOrRightJoinAggDeleteRow()!=null){ boolean result = Utils.evalueJoinAggConditions(stream.getLeftOrRightJoinAggDeleteRow(), aggFct.get(j), operation.get(j), value.get(j)); if(result){ String pkName = stream.getLeftOrRightJoinAggDeleteRow().getColumnDefinitions().getName(0); String pkType = stream.getLeftOrRightJoinAggDeleteRow().getColumnDefinitions().getType(0).toString(); String pkValue = Utils.getColumnValueFromDeltaStream(stream.getLeftOrRightJoinAggDeleteRow(), pkName, pkType, ""); Utils.deleteEntireRowWithPK((String)json.get("keyspace"), innerHaving.get(j), pkName,pkValue); } } if(stream.getLeftOrRightJoinAggUpdatedOldRow()!=null){ boolean result = Utils.evalueJoinAggConditions(stream.getLeftOrRightJoinAggUpdatedOldRow(), aggFct.get(j), operation.get(j), value.get(j)); if(result){ JoinAggregationHelper.insertStatement(json, innerHaving.get(j), stream.getLeftOrRightJoinAggUpdatedOldRow()); } } if(stream.getLeftOrRightJoinAggNewRow()!=null){ boolean result = Utils.evalueJoinAggConditions(stream.getLeftOrRightJoinAggNewRow(), aggFct.get(j), operation.get(j), value.get(j)); if(result){ JoinAggregationHelper.insertStatement(json, innerHaving.get(j), stream.getLeftOrRightJoinAggNewRow()); } } } } } private void evaluateInnerJoinAggHaving(String temp,String aggColPosition,int e,JSONObject json){ Integer nrHaving = VmXmlHandler.getInstance() .getRJAggJoinMapping().getInt(temp + "." +aggColPosition+".c(" + e + ").inner.nrHaving"); if(nrHaving!=0){ List<String> innerHaving = VmXmlHandler.getInstance() .getRJAggJoinMapping().getList(temp + "." +aggColPosition+".c(" + e + ").inner.Having.name"); List<String> aggFct = VmXmlHandler.getInstance() .getRJAggJoinMapping().getList(temp + "." +aggColPosition+".c(" + e + ").inner.Having.And.aggFct"); List<String> innerHavingType = VmXmlHandler.getInstance() .getRJAggJoinMapping().getList(temp + "." +aggColPosition+".c(" + e + ").inner.Having.And.type"); List<String> operation = VmXmlHandler.getInstance() .getRJAggJoinMapping().getList(temp + "." +aggColPosition+".c(" + e + ").inner.Having.And.operation"); List<String> value = VmXmlHandler.getInstance() .getRJAggJoinMapping().getList(temp + "." +aggColPosition+".c(" + e + ").inner.Having.And.value"); for(int j=0;j<nrHaving;j++){ if(stream.getInnerJoinAggDeleteRow()!=null){ boolean result = Utils.evalueJoinAggConditions(stream.getInnerJoinAggDeleteRow(), aggFct.get(j), operation.get(j), value.get(j)); if(result){ String pkName = stream.getInnerJoinAggDeleteRow().getColumnDefinitions().getName(0); String pkType = stream.getInnerJoinAggDeleteRow().getColumnDefinitions().getType(0).toString(); String pkValue = Utils.getColumnValueFromDeltaStream(stream.getInnerJoinAggDeleteRow(), pkName, pkType, ""); Utils.deleteEntireRowWithPK((String)json.get("keyspace"), innerHaving.get(j), pkName,pkValue); } } if(stream.getInnerJoinAggUpdatedOldRow()!=null){ boolean result = Utils.evalueJoinAggConditions(stream.getInnerJoinAggUpdatedOldRow(), aggFct.get(j), operation.get(j), value.get(j)); if(result){ JoinAggregationHelper.insertStatement(json, innerHaving.get(j), stream.getInnerJoinAggUpdatedOldRow()); } } if(stream.getInnerJoinAggNewRow()!=null){ boolean result = Utils.evalueJoinAggConditions(stream.getInnerJoinAggNewRow(), aggFct.get(j), operation.get(j), value.get(j)); if(result){ JoinAggregationHelper.insertStatement(json, innerHaving.get(j), stream.getInnerJoinAggNewRow()); } } } } } private void evaluateInnerJoinAggGroupByHaving(int i, int e, String temp,JSONObject json,String aggColPosition) { Integer nrHaving = VmXmlHandler.getInstance() .getRJAggJoinGroupByMapping().getInt(temp + "." +aggColPosition+".c(" + e + ").Agg(" + i + ").inner.nrHaving"); if(nrHaving!=0){ List<String> innerHaving = VmXmlHandler.getInstance() .getRJAggJoinGroupByMapping().getList(temp + "." +aggColPosition+".c(" + e + ").Agg(" + i + ").inner.Having.name"); List<String> aggFct = VmXmlHandler.getInstance() .getRJAggJoinGroupByMapping().getList(temp + "." +aggColPosition+".c(" + e + ").Agg(" + i + ").inner.Having.And.aggFct"); List<String> innerHavingType = VmXmlHandler.getInstance() .getRJAggJoinGroupByMapping().getList(temp + "." +aggColPosition+".c(" + e + ").Agg(" + i + ").inner.Having.And.type"); List<String> operation = VmXmlHandler.getInstance() .getRJAggJoinGroupByMapping().getList(temp + "." +aggColPosition+".c(" + e + ").Agg(" + i + ").inner.Having.And.operation"); List<String> value = VmXmlHandler.getInstance() .getRJAggJoinGroupByMapping().getList(temp + "." +aggColPosition+".c(" + e + ").Agg(" + i + ").inner.Having.And.value"); for(int j=0;j<nrHaving;j++){ if(stream.getInnerJoinAggGroupByDeleteOldRow()!=null){ boolean result = Utils.evalueJoinAggConditions(stream.getInnerJoinAggGroupByDeleteOldRow(), aggFct.get(j), operation.get(j), value.get(j)); if(result){ String pkName = stream.getInnerJoinAggGroupByDeleteOldRow().getColumnDefinitions().getName(0); String pkType = stream.getInnerJoinAggGroupByDeleteOldRow().getColumnDefinitions().getType(0).toString(); String pkValue = Utils.getColumnValueFromDeltaStream(stream.getInnerJoinAggGroupByDeleteOldRow(), pkName, pkType, ""); Utils.deleteEntireRowWithPK((String)json.get("keyspace"), innerHaving.get(j), pkName,pkValue); } } if(stream.getInnerJoinAggGroupByUpdatedOldRow()!=null){ boolean result = Utils.evalueJoinAggConditions(stream.getInnerJoinAggGroupByUpdatedOldRow(), aggFct.get(j), operation.get(j), value.get(j)); if(result){ JoinAggGroupByHelper.insertStatement(json, innerHaving.get(j), stream.getInnerJoinAggGroupByUpdatedOldRow()); } } if(stream.getInnerJoinAggGroupByNewRow()!=null){ boolean result = Utils.evalueJoinAggConditions(stream.getInnerJoinAggGroupByNewRow(), aggFct.get(j), operation.get(j), value.get(j)); if(result){ JoinAggGroupByHelper.insertStatement(json, innerHaving.get(j), stream.getInnerJoinAggGroupByNewRow()); } } } } } private void evaluateLeftorRightJoinAggGroupByHaving(int i, int e, String temp,JSONObject json,String position) { Integer nrHaving = VmXmlHandler.getInstance() .getRJAggJoinGroupByMapping().getInt(temp + ".leftAggColumns.c(" + e + ").Agg(" + i + ")."+position+".nrHaving"); if(nrHaving!=0){ List<String> leftHaving = VmXmlHandler.getInstance() .getRJAggJoinGroupByMapping().getList(temp + ".leftAggColumns.c(" + e + ").Agg(" + i + ")."+position+".Having.name"); List<String> aggFct = VmXmlHandler.getInstance() .getRJAggJoinGroupByMapping().getList(temp + ".leftAggColumns.c(" + e + ").Agg(" + i + ")."+position+".Having.And.aggFct"); List<String> leftHavingType = VmXmlHandler.getInstance() .getRJAggJoinGroupByMapping().getList(temp + ".leftAggColumns.c(" + e + ").Agg(" + i + ")."+position+".Having.And.type"); List<String> operation = VmXmlHandler.getInstance() .getRJAggJoinGroupByMapping().getList(temp + ".leftAggColumns.c(" + e + ").Agg(" + i + ")."+position+".Having.And.operation"); List<String> value = VmXmlHandler.getInstance() .getRJAggJoinGroupByMapping().getList(temp + ".leftAggColumns.c(" + e + ").Agg(" + i + ")."+position+".Having.And.value"); for(int j=0;j<nrHaving;j++){ if(stream.getLeftOrRightJoinAggGroupByDeleteRow()!=null){ boolean result = Utils.evalueJoinAggConditions(stream.getLeftOrRightJoinAggGroupByDeleteRow(), aggFct.get(j), operation.get(j), value.get(j)); if(result){ String pkName = stream.getLeftOrRightJoinAggGroupByDeleteRow().getColumnDefinitions().getName(0); String pkType = stream.getLeftOrRightJoinAggGroupByDeleteRow().getColumnDefinitions().getType(0).toString(); String pkValue = Utils.getColumnValueFromDeltaStream(stream.getLeftOrRightJoinAggGroupByDeleteRow(), pkName, pkType, ""); Utils.deleteEntireRowWithPK((String)json.get("keyspace"), leftHaving.get(j), pkName,pkValue); } } if(stream.getLeftOrRightJoinAggGroupByUpdatedOldRow()!=null){ boolean result = Utils.evalueJoinAggConditions(stream.getLeftOrRightJoinAggGroupByUpdatedOldRow(), aggFct.get(j), operation.get(j), value.get(j)); if(result){ JoinAggGroupByHelper.insertStatement(json, leftHaving.get(j), stream.getLeftOrRightJoinAggGroupByUpdatedOldRow()); } } if(stream.getLeftOrRightJoinAggGroupByNewRow()!=null){ boolean result = Utils.evalueJoinAggConditions(stream.getLeftOrRightJoinAggGroupByNewRow(), aggFct.get(j), operation.get(j), value.get(j)); if(result){ JoinAggGroupByHelper.insertStatement(json, leftHaving.get(j), stream.getLeftOrRightJoinAggGroupByNewRow()); } } } } } private boolean checkIfAggIsNull(String aggKey, Row deltaUpdatedRow) { if (deltaUpdatedRow != null) { ColumnDefinitions colDef = deltaUpdatedRow.getColumnDefinitions(); int indexNew = colDef.getIndexOf(aggKey + "_new"); int indexOld = colDef.getIndexOf(aggKey + "_old"); if (deltaUpdatedRow.isNull(indexNew) && deltaUpdatedRow.isNull(indexOld)) { return true; } } return false; } public void cascadeDelete(JSONObject json, boolean deleteOperation) { // boolean deleteOperation is set to false if this method is called from // the update method // i.e WHERE clause condition evaluates to fasle // get position of basetable from xml list // retrieve pk of basetable and delta from XML mapping file int indexBaseTableName = baseTableName.indexOf((String) json .get("table")); String baseTablePrimaryKey = pkName.get(indexBaseTableName); Row deltaDeletedRow = null; // 1. delete from Delta Table // 1.a If successful, retrieve entire delta Row from Delta to pass on as // streams if (deleteOperation) { if (vm.deleteRowDelta(json)) { deltaDeletedRow = vm.getDeltaDeletedRow(); } } else deltaDeletedRow = vm.getDeltaDeletedRow(); // 2. for the delta table updated, get the depending preaggregation/agg // tables // preagg tables hold all column values, hence they have to be updated int position = deltaTableName.indexOf("delta_" + (String) json.get("table")); if (position != -1) { String temp = "mapping.unit("; temp += Integer.toString(position); temp += ")"; int nrPreagg = VmXmlHandler.getInstance().getDeltaPreaggMapping() .getInt(temp + ".nrPreagg"); for (int i = 0; i < nrPreagg; i++) { String s = temp + ".Preagg(" + Integer.toString(i) + ")"; String AggKey = VmXmlHandler.getInstance() .getDeltaPreaggMapping().getString(s + ".AggKey"); String AggKeyType = VmXmlHandler.getInstance() .getDeltaPreaggMapping().getString(s + ".AggKeyType"); String preaggTable = VmXmlHandler.getInstance() .getDeltaPreaggMapping().getString(s + ".name"); String AggCol = VmXmlHandler.getInstance() .getDeltaPreaggMapping().getString(s + ".AggCol"); String AggColType = VmXmlHandler.getInstance() .getDeltaPreaggMapping().getString(s + ".AggColType"); // by passing the whole delta Row, we have agg key value even if // it is not in json vm.deleteRowPreaggAgg(deltaDeletedRow, baseTablePrimaryKey, json, preaggTable, AggKey, AggKeyType, AggCol, AggColType); // update the corresponding preagg wih having clause position = preaggTableNames.indexOf(preaggTable); if (position != -1) { String temp4 = "mapping.unit("; temp4 += Integer.toString(position); temp4 += ")"; int nrConditions = VmXmlHandler.getInstance() .getHavingPreAggMapping().getInt(temp4 + ".nrCond"); for (int r = 0; r < nrConditions; r++) { String s1 = temp4 + ".Cond(" + Integer.toString(r) + ")"; String havingTable = VmXmlHandler.getInstance() .getHavingPreAggMapping() .getString(s1 + ".name"); String nrAnd = VmXmlHandler.getInstance() .getHavingPreAggMapping() .getString(s1 + ".nrAnd"); boolean eval1 = true; for (int j = 0; j < Integer.parseInt(nrAnd); j++) { String s11 = s1 + ".And("; s11 += Integer.toString(j); s11 += ")"; String aggFct = VmXmlHandler.getInstance() .getHavingPreAggMapping() .getString(s11 + ".aggFct"); String operation = VmXmlHandler.getInstance() .getHavingPreAggMapping() .getString(s11 + ".operation"); String value = VmXmlHandler.getInstance() .getHavingPreAggMapping() .getString(s11 + ".value"); String type = VmXmlHandler.getInstance() .getHavingPreAggMapping() .getString(s11 + ".type"); String selColName = VmXmlHandler.getInstance() .getHavingPreAggMapping() .getString(s11 + ".selectionCol"); Row DeletedPreagRow = vm.getDeletePreaggRow(); Row DeletedPreagRowMapSize1 = vm .getDeletePreaggRowDeleted(); float min1 = 0; float max1 = 0; float average1 = 0; float sum1 = 0; int count1 = 0; if (DeletedPreagRow != null) { min1 = DeletedPreagRow.getFloat("min"); max1 = DeletedPreagRow.getFloat("max"); average1 = DeletedPreagRow.getFloat("average"); sum1 = DeletedPreagRow.getFloat("sum"); count1 = DeletedPreagRow.getInt("count"); } if (aggFct.equals("sum")) { if (DeletedPreagRow != null) { int compareValue = Float.compare(sum1, Float.valueOf(value)); if ((operation.equals(">") && (compareValue > 0))) { eval1 &= true; } else if ((operation.equals("<") && (compareValue < 0))) { eval1 &= true; } else if ((operation.equals("=") && (compareValue == 0))) { eval1 &= true; } else { eval1 &= false; } } } else if (aggFct.equals("average")) { if (DeletedPreagRow != null) { int compareValue = Float.compare(average1, Float.valueOf(value)); if ((operation.equals(">") && (compareValue > 0))) { eval1 &= true; } else if ((operation.equals("<") && (compareValue < 0))) { eval1 &= true; } else if ((operation.equals("=") && (compareValue == 0))) { eval1 &= true; } else { eval1 &= false; } } } else if (aggFct.equals("count")) { if (DeletedPreagRow != null) { int compareValue = new Integer(count1) .compareTo(new Integer(value)); if ((operation.equals(">") && (compareValue > 0))) { eval1 &= true; } else if ((operation.equals("<") && (compareValue < 0))) { eval1 &= true; } else if ((operation.equals("=") && (compareValue == 0))) { eval1 &= true; } else { eval1 &= false; } } } else if (aggFct.equals("min")) { if (DeletedPreagRow != null) { int compareValue = Float.compare(min1, Float.valueOf(value)); if ((operation.equals(">") && (compareValue > 0))) { eval1 &= true; } else if ((operation.equals("<") && (compareValue < 0))) { eval1 &= true; } else if ((operation.equals("=") && (compareValue == 0))) { eval1 &= true; } else { eval1 &= false; } } } else if (aggFct.equals("max")) { if (DeletedPreagRow != null) { int compareValue = Float.compare(max1, Float.valueOf(value)); if ((operation.equals(">") && (compareValue > 0))) { eval1 &= true; } else if ((operation.equals("<") && (compareValue < 0))) { eval1 &= true; } else if ((operation.equals("=") && (compareValue == 0))) { eval1 &= true; } else { eval1 &= false; } } } if (DeletedPreagRow != null) { if (eval1) { vm.updateHaving(deltaDeletedRow, (String) json.get("keyspace"), havingTable, DeletedPreagRow); } else { vm.deleteRowHaving(deltaDeletedRow, (String) json.get("keyspace"), havingTable, DeletedPreagRow); } } else if (DeletedPreagRowMapSize1 != null) { vm.deleteRowHaving(deltaDeletedRow, (String) json.get("keyspace"), havingTable, DeletedPreagRowMapSize1); } } } } } } else { System.out.println("No Preaggregation table for this delta table " + " delta_" + (String) json.get("table") + " available"); } // 3. for the delta table updated, get the depending selection tables // tables // check if condition is true based on selection true // if true, delete row from selection table int position1 = deltaTableName.indexOf("delta_" + (String) json.get("table")); if (deleteOperation && position1 != -1) { String temp4 = "mapping.unit("; temp4 += Integer.toString(position1); temp4 += ")"; int nrConditions = VmXmlHandler.getInstance() .getDeltaSelectionMapping().getInt(temp4 + ".nrCond"); for (int i = 0; i < nrConditions; i++) { String s = temp4 + ".Cond(" + Integer.toString(i) + ")"; String selecTable = VmXmlHandler.getInstance() .getDeltaSelectionMapping().getString(s + ".name"); String nrAnd = VmXmlHandler.getInstance() .getDeltaSelectionMapping().getString(s + ".nrAnd"); boolean eval = false; for (int j = 0; j < Integer.parseInt(nrAnd); j++) { String s11 = s + ".And("; s11 += Integer.toString(j); s11 += ")"; String operation = VmXmlHandler.getInstance() .getDeltaSelectionMapping() .getString(s11 + ".operation"); String value = VmXmlHandler.getInstance() .getDeltaSelectionMapping() .getString(s11 + ".value"); String type = VmXmlHandler.getInstance() .getDeltaSelectionMapping() .getString(s11 + ".type"); String selColName = VmXmlHandler.getInstance() .getDeltaSelectionMapping() .getString(s11 + ".selectionCol"); switch (type) { case "text": if (operation.equals("=")) { if (vm.getDeltaDeletedRow() .getString(selColName + "_new") .equals(value)) { eval = true; } else { eval = false; } } else if (operation.equals("!=")) { if (!vm.getDeltaDeletedRow() .getString(selColName + "_new") .equals(value)) { eval = true; } else { eval = false; } } break; case "varchar": if (operation.equals("=")) { if (vm.getDeltaDeletedRow() .getString(selColName + "_new") .equals(value)) { eval = true; } else { eval = false; } } else if (operation.equals("!=")) { if (!vm.getDeltaDeletedRow() .getString(selColName + "_new") .equals(value)) { eval = true; } else { eval = false; } } break; case "int": String s1 = Integer.toString(vm.getDeltaDeletedRow() .getInt(selColName + "_new")); Integer valueInt = new Integer(s1); int compareValue = valueInt .compareTo(new Integer(value)); if ((operation.equals(">") && (compareValue < 0))) { eval = false; } else if ((operation.equals("<") && (compareValue > 0))) { eval = false; } else if ((operation.equals("=") && (compareValue != 0))) { eval = false; } else { eval = true; } break; case "varint": s1 = vm.getDeltaDeletedRow() .getVarint(selColName + "_new").toString(); valueInt = new Integer(new BigInteger(s1).intValue()); compareValue = valueInt.compareTo(new Integer(value)); if ((operation.equals(">") && (compareValue < 0))) { eval = false; } else if ((operation.equals("<") && (compareValue > 0))) { eval = false; } else if ((operation.equals("=") && (compareValue != 0))) { eval = false; } else { eval = true; } break; case "float": break; } } if (eval) vm.deleteRowSelection(vm.getDeltaDeletedRow(), (String) json.get("keyspace"), selecTable, baseTablePrimaryKey, json); } } // 4. reverse joins if (deleteOperation) { // check for rj mappings after updating delta int cursor = 0; // for each join for (int j = 0; j < rjoins; j++) { // basetables int nrOfTables = Integer.parseInt(rj_nrDelta.get(j)); String joinTable = rj_joinTables.get(j); // include only indices from 1 to nrOfTables // get basetables from name of rj table List<String> baseTables = Arrays.asList( rj_joinTables.get(j).split("_")).subList(1, nrOfTables + 1); String tableName = (String) json.get("table"); String keyspace = (String) json.get("keyspace"); int column = baseTables.indexOf(tableName) + 1; String joinKeyName = rj_joinKeys.get(cursor + column - 1); String aggKeyType = rj_joinKeyTypes.get(j); vm.deleteReverseJoin(json, cursor, nrOfTables, joinTable, baseTables, joinKeyName, tableName, keyspace, aggKeyType, column); // HERE DELETE FROM JOIN TABLES String updatedReverseJoin = vm.getReverseJoinName(); position = reverseTablesNames_Join.indexOf(updatedReverseJoin); if (position != -1) { String temp = "mapping.unit("; temp += Integer.toString(position); temp += ")"; int nrJoin = VmXmlHandler.getInstance().getRjJoinMapping() .getInt(temp + ".nrJoin"); for (int i = 0; i < nrJoin; i++) { String s = temp + ".join(" + Integer.toString(i) + ")"; String innerJoinTableName = VmXmlHandler.getInstance() .getRjJoinMapping().getString(s + ".innerJoin"); String leftJoinTableName = VmXmlHandler.getInstance() .getRjJoinMapping().getString(s + ".leftJoin"); String rightJoinTableName = VmXmlHandler.getInstance() .getRjJoinMapping().getString(s + ".rightJoin"); String leftJoinTable = VmXmlHandler.getInstance() .getRjJoinMapping().getString(s + ".LeftTable"); String rightJoinTable = VmXmlHandler.getInstance() .getRjJoinMapping() .getString(s + ".RightTable"); tableName = (String) json.get("table"); Boolean updateLeft = false; Boolean updateRight = false; if (tableName.equals(leftJoinTable)) { updateLeft = true; } else { updateRight = true; } vm.deleteJoinController(deltaDeletedRow, innerJoinTableName, leftJoinTableName, rightJoinTableName, json, updateLeft, updateRight); } } else { System.out .println("No join table for this reverse join table " + updatedReverseJoin + " available"); } // END OF DELETE FROM JOIN TABLES // UPDATE join aggregation int positionAgg = reverseTablesNames_AggJoin.indexOf(joinTable); String joinKeyType = rj_joinKeyTypes.get(j); if (positionAgg != -1) { String temp = "mapping.unit("; temp += Integer.toString(positionAgg); temp += ")"; Boolean updateLeft = false; Boolean updateRight = false; String leftJoinTable = VmXmlHandler.getInstance() .getRJAggJoinMapping() .getString(temp + ".LeftTable"); String rightJoinTable = VmXmlHandler.getInstance() .getRJAggJoinMapping() .getString(temp + ".RightTable"); tableName = (String) json.get("table"); if (tableName.equals(leftJoinTable)) { updateLeft = true; } else { updateRight = true; } int nrLeftAggColumns = VmXmlHandler.getInstance() .getRJAggJoinMapping() .getInt(temp + ".leftAggColumns.nr"); for (int e = 0; e < nrLeftAggColumns; e++) { String aggColName = VmXmlHandler .getInstance() .getRJAggJoinMapping() .getString( temp + ".leftAggColumns.c(" + e + ").name"); String aggColType = VmXmlHandler .getInstance() .getRJAggJoinMapping() .getString( temp + ".leftAggColumns.c(" + e + ").type"); String innerJoinAggTable = VmXmlHandler .getInstance() .getRJAggJoinMapping() .getString( temp + ".leftAggColumns.c(" + e + ").inner"); String leftJoinAggTable = VmXmlHandler .getInstance() .getRJAggJoinMapping() .getString( temp + ".leftAggColumns.c(" + e + ").left"); int index = VmXmlHandler .getInstance() .getRJAggJoinMapping() .getInt(temp + ".leftAggColumns.c(" + e + ").index"); if (updateLeft) { vm.deleteJoinAgg_DeleteLeft_AggColLeftSide(stream, innerJoinAggTable, leftJoinAggTable, json, joinKeyType, joinKeyName, aggColName, aggColType); } else { vm.deleteJoinAgg_DeleteRight_AggColLeftSide(stream, innerJoinAggTable, json, joinKeyType, joinKeyName, aggColName, aggColType); } if(!leftJoinAggTable.equals("false")){ evaluateLeftorRightJoinAggHaving(temp,"leftAggColumns", e, json,"left"); } if(!innerJoinAggTable.equals("false")){ evaluateInnerJoinAggHaving(temp, "leftAggColumns", e, json); } stream.resetJoinAggRows(); } int nrRightAggColumns = VmXmlHandler.getInstance() .getRJAggJoinMapping() .getInt(temp + ".rightAggColumns.nr"); for (int e = 0; e < nrRightAggColumns; e++) { String aggColName = VmXmlHandler .getInstance() .getRJAggJoinMapping() .getString( temp + ".rightAggColumns.c(" + e + ").name"); String aggColType = VmXmlHandler .getInstance() .getRJAggJoinMapping() .getString( temp + ".rightAggColumns.c(" + e + ").type"); String innerJoinAggTable = VmXmlHandler .getInstance() .getRJAggJoinMapping() .getString( temp + ".rightAggColumns.c(" + e + ").inner"); String rightJoinAggTable = VmXmlHandler .getInstance() .getRJAggJoinMapping() .getString( temp + ".rightAggColumns.c(" + e + ").right"); int index = VmXmlHandler .getInstance() .getRJAggJoinMapping() .getInt(temp + ".rightAggColumns.c(" + e + ").index"); if (updateLeft) { vm.deleteJoinAgg_DeleteLeft_AggColRightSide(stream, innerJoinAggTable, json, joinKeyType, joinKeyName, aggColName, aggColType); } else { vm.deleteJoinAgg_DeleteRight_AggColRightSide(stream, innerJoinAggTable, rightJoinAggTable, json, joinKeyType, joinKeyName, aggColName, aggColType); } if(!rightJoinAggTable.equals("false")){ evaluateLeftorRightJoinAggHaving(temp,"rightAggColumns", e, json,"right"); } if(!innerJoinAggTable.equals("false")){ evaluateInnerJoinAggHaving(temp, "rightAggColumns", e, json); } stream.resetJoinAggRows(); } } int positionAggGroupBy = reverseTablesNames_AggJoinGroupBy .indexOf(joinTable); if (positionAggGroupBy != -1) { String temp = "mapping.unit("; temp += Integer.toString(positionAggGroupBy); temp += ")"; Boolean updateLeft = false; Boolean updateRight = false; String leftJoinTable = VmXmlHandler.getInstance() .getRJAggJoinGroupByMapping() .getString(temp + ".LeftTable"); String rightJoinTable = VmXmlHandler.getInstance() .getRJAggJoinGroupByMapping() .getString(temp + ".RightTable"); tableName = (String) json.get("table"); if (tableName.equals(leftJoinTable)) { updateLeft = true; } else { updateRight = true; } int nrLeftAggColumns = VmXmlHandler.getInstance() .getRJAggJoinGroupByMapping() .getInt(temp + ".leftAggColumns.nr"); for (int e = 0; e < nrLeftAggColumns; e++) { String aggColName = VmXmlHandler .getInstance() .getRJAggJoinGroupByMapping() .getString( temp + ".leftAggColumns.c(" + e + ").name"); String aggColType = VmXmlHandler .getInstance() .getRJAggJoinGroupByMapping() .getString( temp + ".leftAggColumns.c(" + e + ").type"); int nrAgg = VmXmlHandler .getInstance() .getRJAggJoinGroupByMapping() .getInt(temp + ".leftAggColumns.c(" + e + ").nrAgg"); for (int i = 0; i < nrAgg; i++) { String innerJoinAggTable = VmXmlHandler .getInstance() .getRJAggJoinGroupByMapping() .getString( temp + ".leftAggColumns.c(" + e + ").Agg(" + i + ").inner"); String leftJoinAggTable = VmXmlHandler .getInstance() .getRJAggJoinGroupByMapping() .getString( temp + ".leftAggColumns.c(" + e + ").Agg(" + i + ").left"); String aggKey = VmXmlHandler .getInstance() .getRJAggJoinGroupByMapping() .getString( temp + ".leftAggColumns.c(" + e + ").Agg(" + i + ").Key"); aggKeyType = VmXmlHandler .getInstance() .getRJAggJoinGroupByMapping() .getString( temp + ".leftAggColumns.c(" + e + ").Agg(" + i + ").KeyType"); int index = VmXmlHandler .getInstance() .getRJAggJoinGroupByMapping() .getInt(temp + ".leftAggColumns.c(" + e + ").index"); int AggKeyIndex = VmXmlHandler .getInstance() .getRJAggJoinGroupByMapping() .getInt(temp + ".leftAggColumns.c(" + e + ").Agg(" + i + ").aggKeyIndex"); if (updateLeft) { vm.deleteJoinAgg_DeleteLeft_AggColLeftSide_GroupBy(stream, innerJoinAggTable, leftJoinAggTable, json, aggKeyType, aggKey, aggColName, aggColType); } else { vm.deleteJoinAgg_DeleteRight_AggColLeftSide_GroupBy(stream, innerJoinAggTable, leftJoinAggTable, json, aggKeyType, aggKey, aggColName, aggColType, AggKeyIndex, index); } //evalute Left Having if(!leftJoinAggTable.equals("false")){ evaluateLeftorRightJoinAggGroupByHaving(i,e,temp,json,"left"); } //evalute Inner Having if(!innerJoinAggTable.equals("false")){ evaluateInnerJoinAggGroupByHaving(i,e,temp,json,"leftAggColumns"); } stream.resetJoinAggGroupByUpRows(); } } int nrRightAggColumns = VmXmlHandler.getInstance() .getRJAggJoinGroupByMapping() .getInt(temp + ".rightAggColumns.nr"); for (int e = 0; e < nrRightAggColumns; e++) { String aggColName = VmXmlHandler .getInstance() .getRJAggJoinGroupByMapping() .getString( temp + ".rightAggColumns.c(" + e + ").name"); String aggColType = VmXmlHandler .getInstance() .getRJAggJoinGroupByMapping() .getString( temp + ".rightAggColumns.c(" + e + ").type"); int nrAgg = VmXmlHandler .getInstance() .getRJAggJoinGroupByMapping() .getInt(temp + ".rightAggColumns.c(" + e + ").nrAgg"); for (int i = 0; i < nrAgg; i++) { String aggKey = VmXmlHandler .getInstance() .getRJAggJoinGroupByMapping() .getString( temp + ".rightAggColumns.c(" + e + ").Agg(" + i + ").Key"); aggKeyType = VmXmlHandler .getInstance() .getRJAggJoinGroupByMapping() .getString( temp + ".rightAggColumns.c(" + e + ").Agg(" + i + ").KeyType"); int index = VmXmlHandler .getInstance() .getRJAggJoinGroupByMapping() .getInt(temp + ".rightAggColumns.c(" + e + ").index"); String innerJoinAggTable = VmXmlHandler .getInstance() .getRJAggJoinGroupByMapping() .getString( temp + ".rightAggColumns.c(" + e + ").Agg(" + i + ").inner"); String rightJoinAggTable = VmXmlHandler .getInstance() .getRJAggJoinGroupByMapping() .getString( temp + ".rightAggColumns.c(" + e + ").Agg(" + i + ").right"); int AggKeyIndex = VmXmlHandler .getInstance() .getRJAggJoinGroupByMapping() .getInt(temp + ".rightAggColumns.c(" + e + ").Agg(" + i + ").aggKeyIndex"); if (updateLeft) { vm.deleteJoinAgg_DeleteLeft_AggColRightSide_GroupBy(stream, innerJoinAggTable, rightJoinAggTable, json, aggKeyType, aggKey, aggColName, aggColType, AggKeyIndex, index); } else { vm.deleteJoinAgg_DeleteRight_AggColRightSide_GroupBy(stream, innerJoinAggTable, rightJoinAggTable, json, aggKeyType, aggKey, aggColName, aggColType); } //evalute Left Having if(!rightJoinAggTable.equals("false")){ evaluateLeftorRightJoinAggGroupByHaving(i,e,temp,json,"right"); } //evalute Inner Having if(!innerJoinAggTable.equals("false")){ evaluateInnerJoinAggGroupByHaving(i,e,temp,json,"rightAggColumns"); } stream.resetJoinAggGroupByUpRows(); } } } cursor += nrOfTables; } } } public boolean evaluateCondition(Row row, String operation, String value, String type, String colName) { boolean eval = true; if (row.isNull(colName)) { return false; } switch (type) { case "text": if (operation.equals("=")) { if (row.getString(colName).equals(value)) { eval &= true; } else { eval &= false; } } else if (operation.equals("!=")) { if (!row.getString(colName).equals(value)) { eval = true; } else { eval = false; } } break; case "varchar": if (operation.equals("=")) { if (row.getString(colName).equals(value)) { eval &= true; } else { eval &= false; } } else if (operation.equals("!=")) { if (!row.getString(colName).equals(value)) { eval &= true; } else { eval &= false; } } break; case "int": // for _new col String s1 = Integer.toString(row.getInt(colName)); Integer valueInt = new Integer(s1); int compareValue = valueInt.compareTo(new Integer(value)); if ((operation.equals(">") && (compareValue > 0))) { eval &= true; } else if ((operation.equals("<") && (compareValue < 0))) { eval &= true; } else if ((operation.equals("=") && (compareValue == 0))) { eval &= true; } else { eval &= false; } break; case "varint": // for _new col s1 = row.getVarint(colName).toString(); valueInt = new Integer(new BigInteger(s1).intValue()); compareValue = valueInt.compareTo(new Integer(value)); if ((operation.equals(">") && (compareValue > 0))) { eval &= true; } else if ((operation.equals("<") && (compareValue < 0))) { eval &= true; } else if ((operation.equals("=") && (compareValue == 0))) { eval &= true; } else { eval &= false; } break; case "float": compareValue = Float.compare(row.getFloat(colName), Float.valueOf(value)); if ((operation.equals(">") && (compareValue > 0))) { eval &= true; } else if ((operation.equals("<") && (compareValue < 0))) { eval &= true; } else if ((operation.equals("=") && (compareValue == 0))) { eval &= true; } else { eval &= false; } break; } return eval; } }
package axiom.objectmodel.dom; import java.io.IOException; import java.io.Reader; import java.util.regex.*; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.Token; import org.apache.lucene.analysis.TokenStream; public class UrlAnalyzer extends Analyzer { public TokenStream tokenStream(String fieldName, final Reader reader) { return new TokenStream() { private final String tokenString = "^([^:]*://|www|com|org|net)"; private final Pattern stripTokens = Pattern.compile(tokenString); private final Pattern endTokens = Pattern.compile("(\\.|/|-|_|\\?)$"); private boolean done = false; public Token next() throws IOException { if(!done){ final char[] buffer = new char[1]; StringBuffer sb = new StringBuffer(); int length = 0; Matcher matcher = endTokens.matcher(sb); boolean found = matcher.find(); while (!found && (length = reader.read(buffer)) != -1) { sb.append(buffer, 0, length); Matcher startMatcher = stripTokens.matcher(sb); if(startMatcher.matches()){ // strip prefix String tmp = sb.toString(); sb = new StringBuffer(tmp.replaceFirst(tokenString, "")); } matcher = endTokens.matcher(sb); found = matcher.find(); if(found){ final String text = sb.toString().substring(0, matcher.end()-1).toLowerCase(); int len = text.length(); if(len > 0){ // matched a token return new Token(text, 0, len); } else { // only contains a stop token, continue reading sb = new StringBuffer(); found = false; } } } // at end of string done = true; final String value = sb.toString().toLowerCase(); return new Token(value, 0, value.length()); } return null; } }; } }
package net.sf.jabref.groups; import java.util.Map; import java.util.regex.*; import javax.swing.undo.AbstractUndoableEdit; import net.sf.jabref.*; import net.sf.jabref.undo.*; import net.sf.jabref.util.QuotedStringTokenizer; /** * @author jzieren */ public class KeywordGroup extends AbstractGroup implements SearchRule { public static final String ID = "KeywordGroup:"; private final String m_searchField; private final String m_searchExpression; private final boolean m_caseSensitive; private final boolean m_regExp; private Pattern m_pattern = null; /** * Creates a KeywordGroup with the specified properties. */ public KeywordGroup(String name, String searchField, String searchExpression, boolean caseSensitive, boolean regExp, int context) throws IllegalArgumentException, PatternSyntaxException { super(name, context); m_searchField = searchField; m_searchExpression = searchExpression; m_caseSensitive = caseSensitive; m_regExp = regExp; if (m_regExp) compilePattern(); } protected void compilePattern() throws IllegalArgumentException, PatternSyntaxException { m_pattern = m_caseSensitive ? Pattern.compile(m_searchExpression) : Pattern.compile(m_searchExpression, Pattern.CASE_INSENSITIVE); } /** * Parses s and recreates the KeywordGroup from it. * * @param s * The String representation obtained from * KeywordGroup.toString() */ public static AbstractGroup fromString(String s, BibtexDatabase db, int version) throws Exception { if (!s.startsWith(ID)) throw new Exception( "Internal error: KeywordGroup cannot be created from \"" + s + "\". " + "Please report this on www.sf.net/projects/jabref"); QuotedStringTokenizer tok = new QuotedStringTokenizer(s.substring(ID .length()), SEPARATOR, QUOTE_CHAR); switch (version) { case 0: { String name = tok.nextToken(); String field = tok.nextToken(); String expression = tok.nextToken(); // assume caseSensitive=false and regExp=true for old groups return new KeywordGroup(Util.unquote(name, QUOTE_CHAR), Util .unquote(field, QUOTE_CHAR), Util.unquote(expression, QUOTE_CHAR), false, true, AbstractGroup.INDEPENDENT); } case 1: case 2: { String name = tok.nextToken(); String field = tok.nextToken(); String expression = tok.nextToken(); boolean caseSensitive = Integer.parseInt(tok.nextToken()) == 1; boolean regExp = Integer.parseInt(tok.nextToken()) == 1; return new KeywordGroup(Util.unquote(name, QUOTE_CHAR), Util .unquote(field, QUOTE_CHAR), Util.unquote(expression, QUOTE_CHAR), caseSensitive, regExp, AbstractGroup.INDEPENDENT); } case 3: { String name = tok.nextToken(); int context = Integer.parseInt(tok.nextToken()); String field = tok.nextToken(); String expression = tok.nextToken(); boolean caseSensitive = Integer.parseInt(tok.nextToken()) == 1; boolean regExp = Integer.parseInt(tok.nextToken()) == 1; return new KeywordGroup(Util.unquote(name, QUOTE_CHAR), Util .unquote(field, QUOTE_CHAR), Util.unquote(expression, QUOTE_CHAR), caseSensitive, regExp, context); } default: throw new UnsupportedVersionException("KeywordGroup", version); } } /** * @see net.sf.jabref.groups.AbstractGroup#getSearchRule() */ public SearchRule getSearchRule() { return this; } /** * Returns a String representation of this object that can be used to * reconstruct it. */ public String toString() { return ID + Util.quote(m_name, SEPARATOR, QUOTE_CHAR) + SEPARATOR + m_context + SEPARATOR + Util.quote(m_searchField, SEPARATOR, QUOTE_CHAR) + SEPARATOR + Util.quote(m_searchExpression, SEPARATOR, QUOTE_CHAR) + SEPARATOR + (m_caseSensitive ? "1" : "0") + SEPARATOR + (m_regExp ? "1" : "0") + SEPARATOR; } public boolean supportsAdd() { return !m_regExp; } public boolean supportsRemove() { return !m_regExp; } public AbstractUndoableEdit add(BibtexEntry[] entries) { if (!supportsAdd()) return null; if ((entries != null) && (entries.length > 0)) { NamedCompound ce = new NamedCompound(Globals .lang("add entries to group")); boolean modified = false; for (int i = 0; i < entries.length; i++) { if (applyRule(null, entries[i]) == 0) { String oldContent = (String) entries[i] .getField(m_searchField), pre = Globals.prefs.get("groupKeywordSeparator"); String newContent = (oldContent == null ? "" : oldContent + pre) + m_searchExpression; entries[i].setField(m_searchField, newContent); // Store undo information. ce.addEdit(new UndoableFieldChange(entries[i], m_searchField, oldContent, newContent)); modified = true; } } if (modified) ce.end(); return modified ? ce : null; } return null; } public AbstractUndoableEdit remove(BibtexEntry[] entries) { if (!supportsRemove()) return null; if ((entries != null) && (entries.length > 0)) { NamedCompound ce = new NamedCompound(Globals .lang("remove from group")); boolean modified = false; for (int i = 0; i < entries.length; ++i) { if (applyRule(null, entries[i]) > 0) { String oldContent = (String) entries[i] .getField(m_searchField); removeMatches(entries[i]); // Store undo information. ce.addEdit(new UndoableFieldChange(entries[i], m_searchField, oldContent, entries[i] .getField(m_searchField))); modified = true; } } if (modified) ce.end(); return modified ? ce : null; } return null; } public boolean equals(Object o) { if (!(o instanceof KeywordGroup)) return false; KeywordGroup other = (KeywordGroup) o; return m_name.equals(other.m_name) && m_searchField.equals(other.m_searchField) && m_searchExpression.equals(other.m_searchExpression) && m_caseSensitive == other.m_caseSensitive && m_regExp == other.m_regExp; } /* * (non-Javadoc) * * @see net.sf.jabref.groups.AbstractGroup#contains(java.util.Map, * net.sf.jabref.BibtexEntry) */ public boolean contains(Map searchOptions, BibtexEntry entry) { return contains(entry); } public boolean contains(BibtexEntry entry) { String content = (String) entry.getField(m_searchField); if (content == null) return false; if (m_regExp) return m_pattern.matcher(content).find(); if (m_caseSensitive) return content.indexOf(m_searchExpression) >= 0; content = content.toLowerCase(); return content.indexOf(m_searchExpression.toLowerCase()) >= 0; } /** * Removes matches of searchString in the entry's field. This is only * possible if the search expression is not a regExp. */ private void removeMatches(BibtexEntry entry) { String content = (String) entry.getField(m_searchField); if (content == null) return; // nothing to modify StringBuffer sbOrig = new StringBuffer(content); StringBuffer sbLower = new StringBuffer(content.toLowerCase()); StringBuffer haystack = m_caseSensitive ? sbOrig : sbLower; String needle = m_caseSensitive ? m_searchExpression : m_searchExpression.toLowerCase(); int i, j, k; final String separator = Globals.prefs.get("groupKeywordSeparator"); while ((i = haystack.indexOf(needle)) >= 0) { sbOrig.replace(i, i + needle.length(), ""); sbLower.replace(i, i + needle.length(), ""); // reduce spaces at i to 1 j = i; k = i; while (j - 1 >= 0 && separator.indexOf(haystack.charAt(j - 1)) >= 0) --j; while (k < haystack.length() && separator.indexOf(haystack.charAt(k)) >= 0) ++k; sbOrig.replace(j, k, j >= 0 && k < sbOrig.length() ? separator : ""); sbLower.replace(j, k, j >= 0 && k < sbOrig.length() ? separator : ""); } String result = sbOrig.toString().trim(); entry.setField(m_searchField, (result.length() > 0 ? result : null)); } public int applyRule(Map searchOptions, BibtexEntry entry) { return contains(searchOptions, entry) ? 1 : 0; } public AbstractGroup deepCopy() { try { return new KeywordGroup(m_name, m_searchField, m_searchExpression, m_caseSensitive, m_regExp, m_context); } catch (Throwable t) { // this should never happen, because the constructor obviously // succeeded in creating _this_ instance! System.err.println("Internal error: Exception " + t + " in KeywordGroup.deepCopy(). " + "Please report this on www.sf.net/projects/jabref"); return null; } } public boolean isCaseSensitive() { return m_caseSensitive; } public boolean isRegExp() { return m_regExp; } public String getSearchExpression() { return m_searchExpression; } public String getSearchField() { return m_searchField; } public boolean isDynamic() { return true; } public String getDescription() { return getDescriptionForPreview(m_searchField, m_searchExpression, m_caseSensitive, m_regExp); } public static String getDescriptionForPreview(String field, String expr, boolean caseSensitive, boolean regExp) { StringBuffer sb = new StringBuffer(); sb.append(regExp ? Globals.lang( "This group contains entries whose <b>%0</b> field contains the regular expression <b>%1</b>", field, expr) : Globals.lang( "This group contains entries whose <b>%0</b> field contains the keyword <b>%1</b>", field, expr)); sb.append(" (" + (caseSensitive ? Globals.lang("case sensitive") : Globals.lang("case insensitive")) + "). "); sb.append(regExp ? Globals.lang( "Entries cannot be manually assigned to or removed from this group.") : Globals.lang( "Additionally, entries whose <b>%0</b> field does not contain " + "<b>%1</b> can be assigned manually to this group by selecting them " + "then using either drag and drop or the context menu. " + "This process adds the term <b>%1</b> to " + "each entry's <b>%0</b> field. " + "Entries can be removed manually from this group by selecting them " + "then using the context menu. " + "This process removes the term <b>%1</b> from " + "each entry's <b>%0</b> field.", field, expr)); return sb.toString(); } public String getShortDescription() { StringBuffer sb = new StringBuffer(); sb.append("<b>"); if (Globals.prefs.getBoolean("groupShowDynamic")) sb.append("<i>" + getName() + "</i>"); else sb.append(getName()); sb.append("</b> - dynamic group (<b>" + m_searchField + "</b> contains <b>" + m_searchExpression + "</b>)"); switch (getHierarchicalContext()) { case AbstractGroup.INCLUDING: sb.append(", includes subgroups"); break; case AbstractGroup.REFINING: sb.append(", refines supergroup"); break; default: break; } return sb.toString(); } }
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.*; /** * 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 Set<String> columnLabels = new HashSet<String>(); 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(final BEAN bean) { this.metrics.add(bean); } /** Returns the list of headers. */ public List<BEAN> getMetrics() { return Collections.unmodifiableList(this.metrics); } public Set<String> getMetricsColumnLabels() { return Collections.unmodifiableSet(this.columnLabels); } /** 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(final 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(final Histogram<HKEY> histogram) { this.histograms.add(histogram); } //** Returns an unmodifiable version of the histogram list */ public List<Histogram<HKEY>> getAllHistograms() { return Collections.unmodifiableList(histograms); } /** 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(final Class<? extends Header> type) { List<Header> tmp = new ArrayList<Header>(); for (final 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(final 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(final Writer w) { try { final FormatUtil formatter = new FormatUtil(); final 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(final BufferedWriter out) throws IOException { for (final 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(final BufferedWriter out, final 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 final 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 (final BEAN bean : this.metrics) { for (int i=0; i<fieldCount; ++i) { try { final 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(final BufferedWriter out, final FormatUtil formatter) throws IOException { final List<Histogram<HKEY>> nonEmptyHistograms = new ArrayList<Histogram<HKEY>>(); for (final Histogram<HKEY> histo : this.histograms) { if (!histo.isEmpty()) nonEmptyHistograms.add(histo); } if (nonEmptyHistograms.isEmpty()) { return; } // Build a combined key set. Assume comparator is the same for all Histograms final java.util.Set<HKEY> keys = new TreeSet<HKEY>(nonEmptyHistograms.get(0).comparator()); for (final Histogram<HKEY> histo : nonEmptyHistograms) { if (histo != null) keys.addAll(histo.keySet()); } // Add a header for the histogram key type out.append(HISTO_HEADER + nonEmptyHistograms.get(0).keySet().iterator().next().getClass().getName()); out.newLine(); // Output a header row out.append(StringUtil.assertCharactersNotInString(nonEmptyHistograms.get(0).getBinLabel(), '\t', '\n')); for (final Histogram<HKEY> histo : nonEmptyHistograms) { out.append(SEPARATOR); out.append(StringUtil.assertCharactersNotInString(histo.getValueLabel(), '\t', '\n')); } out.newLine(); for (final HKEY key : keys) { out.append(key.toString()); for (final Histogram<HKEY> histo : nonEmptyHistograms) { final 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(final Reader r) { final BufferedReader in = new BufferedReader(r); final 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."); } final String className = line.substring(MAJOR_HEADER_PREFIX.length()).trim(); try { header = (Header) loadClass(className, true).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); } } //read space between starting headers and metrics while (line != null && !line.startsWith(MAJOR_HEADER_PREFIX)) { line = in.readLine(); } if(line != null) { line = line.trim(); // Then read the metrics if there are any if (line.startsWith(METRIC_HEADER)) { // Get the metric class from the header final String className = line.split(SEPARATOR)[1]; Class<?> type = null; try { type = loadClass(className, true); } catch (ClassNotFoundException cnfe) { throw new PicardException("Could not locate class with name " + className, cnfe); } // Read the next line with the column headers final String[] fieldNames = in.readLine().split(SEPARATOR); Collections.addAll(columnLabels, fieldNames); final 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) { if ("".equals(line.trim())) { break; } else { String[] values = line.split(SEPARATOR, -1); 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 final String keyClassName = line.split(SEPARATOR)[1].trim(); Class<?> keyClass = null; try { keyClass = loadClass(keyClassName, true); } catch (ClassNotFoundException cnfe) { throw new PicardException("Could not load class with name " + keyClassName); } // Read the next line with the bin and value labels final 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)) { final String[] fields = line.trim().split(SEPARATOR); final HKEY key = (HKEY) formatter.parseObject(fields[0], keyClass); for (int i=1; i<fields.length; ++i) { final 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(final String className, final boolean tryOtherPackages) throws ClassNotFoundException { // List of alternative packages to check in case classes moved around final String[] packages = new String[] { "edu.mit.broad.picard.genotype.concordance", "edu.mit.broad.picard.genotype.fingerprint", "edu.mit.broad.picard.ic", "edu.mit.broad.picard.illumina", "edu.mit.broad.picard.jumping", "edu.mit.broad.picard.quality", "edu.mit.broad.picard.samplevalidation", "net.sf.picard.analysis", "net.sf.picard.analysis.directed", "net.sf.picard.sam", "net.sf.picard.metrics" }; try { return Class.forName(className); } catch (ClassNotFoundException cnfe) { if (tryOtherPackages) { for (final String p : packages) { try { return loadClass(p + className.substring(className.lastIndexOf(".")), false); } catch (ClassNotFoundException cnf2) {/* do nothing */} // If it ws an inner class, try and see if it's a stand-alone class now if (className.indexOf("$") > -1) { try { return loadClass(p + "." + className.substring(className.lastIndexOf("$") + 1), false); } catch (ClassNotFoundException cnf2) {/* do nothing */} } } } throw cnfe; } } /** Checks that the headers, metrics and histogram are all equal. */ @Override public boolean equals(final Object o) { if (o == null) { return false; } if (getClass() != o.getClass()) { return false; } final MetricsFile that = (MetricsFile) o; if (!areHeadersEqual(that)) { return false; } if (!areMetricsEqual(that)) { return false; } if (!areHistogramsEqual(that)) { return false; } return true; } public boolean areHeadersEqual(final MetricsFile that) { return this.headers.equals(that.headers); } public boolean areMetricsEqual(final MetricsFile that) { return this.metrics.equals(that.metrics); } public boolean areHistogramsEqual(final MetricsFile that) { return this.histograms.equals(that.histograms); } @Override public int hashCode() { int result = headers.hashCode(); result = 31 * result + metrics.hashCode(); return result; } /** * Convenience method to read all the Metric beans from a metrics file. * @param file to be read. * @return list of beans from the file. */ public static List<? extends MetricBase> readBeans(final File file) { try { final MetricsFile<MetricBase, Comparable<?>> metricsFile = new MetricsFile<MetricBase, Comparable<?>>(); metricsFile.read(new FileReader(file)); return metricsFile.getMetrics(); } catch (FileNotFoundException e) { throw new PicardException(e.getMessage(), e); } } }
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> * The enums can have functionality by using anonymous inner classes * [Effective Java, Bloch01]: * <pre> * public abstract class OperationEnum extends Enum { * public static final OperationEnum PLUS = new OperationEnum("Plus") { * public double eval(double a, double b) { * return (a + b); * } * }; * public static final OperationEnum MINUS = new OperationEnum("Minus") { * public double eval(double a, double b) { * return (a - b); * } * }; * * private OperationEnum(String color) { * super(color); * } * * public abstract double eval(double a, double b); * * public static OperationEnum getEnum(String name) { * return (OperationEnum) getEnum(OperationEnum.class, name); * } * * public static Map getEnumMap() { * return getEnumMap(OperationEnum.class); * } * * public static List getEnumList() { * return getEnumList(OperationEnum.class); * } * * public static Iterator iterator() { * return iterator(OperationEnum.class); * } * } * </pre> * <p> * <em>NOTE:</em> This class originated in the Jakarta Avalon project. * </p> * * @author Stephen Colebourne * @author Chris Webb * @since 1.0 * @version $Id: Enum.java,v 1.7 2003/02/04 16:56:08 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; String className = Enum.getEnumClassName(getClass()); Entry entry = (Entry) cEnumClasses.get(className); if (entry == null) { entry = new Entry(); cEnumClasses.put(className, 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() { Entry entry = (Entry) cEnumClasses.get(Enum.getEnumClassName(getClass())); if (entry == null) { return null; } return (Enum) entry.map.get(getName()); } protected static Enum getEnum(Class enumClass, String name) { Entry entry = getEntry(enumClass); if (entry == null) { return null; } return (Enum) entry.map.get(name); } protected static Map getEnumMap(Class enumClass) { Entry entry = getEntry(enumClass); if (entry == null) { return EMPTY_MAP; } return Collections.unmodifiableMap(entry.map); } protected static List getEnumList(Class enumClass) { Entry entry = getEntry(enumClass); if (entry == null) { return Collections.EMPTY_LIST; } return Collections.unmodifiableList(entry.list); } protected static Iterator iterator(Class enumClass) { return Enum.getEnumList(enumClass).iterator(); } /** * Gets an entry from the map of Enums. * * @param enumClass the class of the Enum to get * @return the enum entry */ private static Entry getEntry(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()); return entry; } /** * Convert a class to a class name accounting for inner classes. * * @param cls the class to get the name for * @return the class name */ protected static String getEnumClassName(Class cls) { String className = cls.getName(); int index = className.lastIndexOf('$'); if (index > -1) { // is it an anonymous inner class? String inner = className.substring(index + 1); if (inner.length() > 0 && inner.charAt(0) >= '0' && inner.charAt(0) < '9') { // Strip off anonymous inner class reference. className = className.substring(0, index); } } return className; } /** * 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 = Enum.getEnumClassName(getClass()); int pos = shortName.lastIndexOf('.'); if (pos != -1) { shortName = shortName.substring(pos + 1); } shortName = shortName.replace('$', '.'); return shortName + "[" + getName() + "]"; } }
//modification, are permitted provided that the following conditions are //met: //documentation and/or other materials provided with the distribution. //Neither the name of the Drew Davidson nor the names of its contributors //may be used to endorse or promote products derived from this software //"AS IS" AND 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 THE //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 org.apache.commons.ognl; import org.apache.commons.ognl.enhance.ExpressionCompiler; import org.apache.commons.ognl.enhance.OrderedReturn; import org.apache.commons.ognl.enhance.UnsupportedCompilationException; import java.lang.reflect.Method; /** * @author Luke Blanshard (blanshlu@netscape.net) * @author Drew Davidson (drew@ognl.org) */ public class ASTMethod extends SimpleNode implements OrderedReturn, NodeType { private String _methodName; private String _lastExpression; private String _coreExpression; private Class _getterClass; public ASTMethod(int id) { super(id); } public ASTMethod(OgnlParser p, int id) { super(p, id); } /** Called from parser action. */ public void setMethodName(String methodName) { _methodName = methodName; } /** * Returns the method name that this node will call. */ public String getMethodName() { return _methodName; } protected Object getValueBody(OgnlContext context, Object source) throws OgnlException { Object[] args = OgnlRuntime.getObjectArrayPool().create(jjtGetNumChildren()); try { Object result, root = context.getRoot(); for(int i = 0, icount = args.length; i < icount; ++i) { args[i] = _children[i].getValue(context, root); } result = OgnlRuntime.callMethod(context, source, _methodName, args); if (result == null) { NullHandler nh = OgnlRuntime.getNullHandler(OgnlRuntime.getTargetClass(source)); result = nh.nullMethodResult(context, source, _methodName, args); } return result; } finally { OgnlRuntime.getObjectArrayPool().recycle(args); } } public String getLastExpression() { return _lastExpression; } public String getCoreExpression() { return _coreExpression; } public Class getGetterClass() { return _getterClass; } public Class getSetterClass() { return _getterClass; } public String toString() { String result = _methodName; result = result + "("; if ((_children != null) && (_children.length > 0)) { for(int i = 0; i < _children.length; i++) { if (i > 0) { result = result + ", "; } result = result + _children[i]; } } result = result + ")"; return result; } public String toGetSourceString(OgnlContext context, Object target) { /* System.out.println("methodName is " + _methodName + " for target " + target + " target class: " + (target != null ? target.getClass() : null) + " current type: " + context.getCurrentType());*/ if (target == null) throw new UnsupportedCompilationException("Target object is null."); String post = ""; String result = null; Method m = null; try { m = OgnlRuntime.getMethod(context, context.getCurrentType() != null ? context.getCurrentType() : target.getClass(), _methodName, _children, false); if (m == null) m = OgnlRuntime.getReadMethod(target.getClass(), _methodName, _children != null ? _children.length : -1); if (m == null) { m = OgnlRuntime.getWriteMethod(target.getClass(), _methodName, _children != null ? _children.length : -1); if (m != null) { context.setCurrentType(m.getReturnType()); context.setCurrentAccessor(OgnlRuntime.getCompiler().getSuperOrInterfaceClass(m, m.getDeclaringClass())); _coreExpression = toSetSourceString(context, target); if (_coreExpression == null || _coreExpression.length() < 1) throw new UnsupportedCompilationException("can't find suitable getter method"); _coreExpression += ";"; _lastExpression = "null"; return _coreExpression; } return ""; } else { _getterClass = m.getReturnType(); } // TODO: This is a hacky workaround until javassist supports varargs method invocations boolean varArgs = OgnlRuntime.isJdk15() && m.isVarArgs(); if (varArgs) { throw new UnsupportedCompilationException("Javassist does not currently support varargs method calls"); } result = "." + m.getName() + "("; if ((_children != null) && (_children.length > 0)) { Class[] parms = m.getParameterTypes(); String prevCast = (String)context.remove(ExpressionCompiler.PRE_CAST); /* System.out.println("before children methodName is " + _methodName + " for target " + target + " target class: " + (target != null ? target.getClass() : null) + " current type: " + context.getCurrentType() + " and previous type: " + context.getPreviousType());*/ for(int i = 0; i < _children.length; i++) { if (i > 0) { result = result + ", "; } Class prevType = context.getCurrentType(); context.setCurrentObject(context.getRoot()); context.setCurrentType(context.getRoot() != null ? context.getRoot().getClass() : null); context.setCurrentAccessor(null); context.setPreviousType(null); Object value = _children[i].getValue(context, context.getRoot()); String parmString = _children[i].toGetSourceString(context, context.getRoot()); if (parmString == null || parmString.trim().length() < 1) parmString = "null"; // to undo type setting of constants when used as method parameters if (ASTConst.class.isInstance(_children[i])) { context.setCurrentType(prevType); } parmString = ExpressionCompiler.getRootExpression(_children[i], context.getRoot(), context) + parmString; String cast = ""; if (ExpressionCompiler.shouldCast(_children[i])) { cast = (String)context.remove(ExpressionCompiler.PRE_CAST); } if (cast == null) cast = ""; if (!ASTConst.class.isInstance(_children[i])) parmString = cast + parmString; Class valueClass = value != null ? value.getClass() : null; if (NodeType.class.isAssignableFrom(_children[i].getClass())) valueClass = ((NodeType)_children[i]).getGetterClass(); if ((!varArgs || varArgs && (i + 1) < parms.length) && valueClass != parms[i]) { if (parms[i].isArray()) { parmString = OgnlRuntime.getCompiler().createLocalReference(context, "(" + ExpressionCompiler.getCastString(parms[i]) + ")org.apache.commons.ognl.OgnlOps#toArray(" + parmString + ", " + parms[i].getComponentType().getName() + ".class, true)", parms[i] ); } else if (parms[i].isPrimitive()) { Class wrapClass = OgnlRuntime.getPrimitiveWrapperClass(parms[i]); parmString = OgnlRuntime.getCompiler().createLocalReference(context, "((" + wrapClass.getName() + ")org.apache.commons.ognl.OgnlOps#convertValue(" + parmString + "," + wrapClass.getName() + ".class, true))." + OgnlRuntime.getNumericValueGetter(wrapClass), parms[i] ); } else if (parms[i] != Object.class) { parmString = OgnlRuntime.getCompiler().createLocalReference(context, "(" + parms[i].getName() + ")org.apache.commons.ognl.OgnlOps#convertValue(" + parmString + "," + parms[i].getName() + ".class)", parms[i] ); } else if ((NodeType.class.isInstance(_children[i]) && ((NodeType)_children[i]).getGetterClass() != null && Number.class.isAssignableFrom(((NodeType)_children[i]).getGetterClass())) || (valueClass != null && valueClass.isPrimitive())) { parmString = " ($w) " + parmString; } else if (valueClass != null && valueClass.isPrimitive()) { parmString = "($w) " + parmString; } } result += parmString; } if (prevCast != null) { context.put(ExpressionCompiler.PRE_CAST, prevCast); } } } catch (Throwable t) { throw OgnlOps.castToRuntime(t); } try { Object contextObj = getValueBody(context, target); context.setCurrentObject(contextObj); } catch (Throwable t) { throw OgnlOps.castToRuntime(t); } result += ")" + post; if (m.getReturnType() == void.class) { _coreExpression = result + ";"; _lastExpression = "null"; } context.setCurrentType(m.getReturnType()); context.setCurrentAccessor(OgnlRuntime.getCompiler().getSuperOrInterfaceClass(m, m.getDeclaringClass())); return result; } public String toSetSourceString(OgnlContext context, Object target) { /*System.out.println("current type: " + context.getCurrentType() + " target:" + target + " " + context.getCurrentObject() + " last child? " + lastChild(context));*/ Method m = OgnlRuntime.getWriteMethod(context.getCurrentType() != null ? context.getCurrentType() : target.getClass(), _methodName, _children != null ? _children.length : -1); if (m == null) { throw new UnsupportedCompilationException("Unable to determine setter method generation for " + _methodName); } String post = ""; String result = "." + m.getName() + "("; if (m.getReturnType() != void.class && m.getReturnType().isPrimitive() && (_parent == null || !ASTTest.class.isInstance(_parent))) { Class wrapper = OgnlRuntime.getPrimitiveWrapperClass(m.getReturnType()); ExpressionCompiler.addCastString(context, "new " + wrapper.getName() + "("); post = ")"; _getterClass = wrapper; } boolean varArgs = OgnlRuntime.isJdk15() && m.isVarArgs(); if (varArgs) { throw new UnsupportedCompilationException("Javassist does not currently support varargs method calls"); } try { /* if (lastChild(context) && m.getParameterTypes().length > 0 && _children.length <= 0) throw new UnsupportedCompilationException("Unable to determine setter method generation for " + m); */ if ((_children != null) && (_children.length > 0)) { Class[] parms = m.getParameterTypes(); String prevCast = (String)context.remove(ExpressionCompiler.PRE_CAST); for(int i = 0; i < _children.length; i++) { if (i > 0) { result += ", "; } Class prevType = context.getCurrentType(); context.setCurrentObject(context.getRoot()); context.setCurrentType(context.getRoot() != null ? context.getRoot().getClass() : null); context.setCurrentAccessor(null); context.setPreviousType(null); Object value = _children[i].getValue(context, context.getRoot()); String parmString = _children[i].toSetSourceString(context, context.getRoot()); if (context.getCurrentType() == Void.TYPE || context.getCurrentType() == void.class) throw new UnsupportedCompilationException("Method argument can't be a void type."); if (parmString == null || parmString.trim().length() < 1) { if (ASTProperty.class.isInstance(_children[i]) || ASTMethod.class.isInstance(_children[i]) || ASTStaticMethod.class.isInstance(_children[i]) || ASTChain.class.isInstance(_children[i])) throw new UnsupportedCompilationException("ASTMethod setter child returned null from a sub property expression."); parmString = "null"; } // to undo type setting of constants when used as method parameters if (ASTConst.class.isInstance(_children[i])) { context.setCurrentType(prevType); } parmString = ExpressionCompiler.getRootExpression(_children[i], context.getRoot(), context) + parmString; String cast = ""; if (ExpressionCompiler.shouldCast(_children[i])) { cast = (String)context.remove(ExpressionCompiler.PRE_CAST); } if (cast == null) cast = ""; parmString = cast + parmString; Class valueClass = value != null ? value.getClass() : null; if (NodeType.class.isAssignableFrom(_children[i].getClass())) valueClass = ((NodeType)_children[i]).getGetterClass(); if (valueClass != parms[i]) { if (parms[i].isArray()) { parmString = OgnlRuntime.getCompiler().createLocalReference(context, "(" + ExpressionCompiler.getCastString(parms[i]) + ")org.apache.commons.ognl.OgnlOps#toArray(" + parmString + ", " + parms[i].getComponentType().getName() + ".class)", parms[i] ); } else if (parms[i].isPrimitive()) { Class wrapClass = OgnlRuntime.getPrimitiveWrapperClass(parms[i]); parmString = OgnlRuntime.getCompiler().createLocalReference(context, "((" + wrapClass.getName() + ")org.apache.commons.ognl.OgnlOps#convertValue(" + parmString + "," + wrapClass.getName() + ".class, true))." + OgnlRuntime.getNumericValueGetter(wrapClass), parms[i] ); } else if (parms[i] != Object.class) { parmString = OgnlRuntime.getCompiler().createLocalReference(context, "(" + parms[i].getName() + ")org.apache.commons.ognl.OgnlOps#convertValue(" + parmString + "," + parms[i].getName() + ".class)", parms[i] ); } else if ((NodeType.class.isInstance(_children[i]) && ((NodeType)_children[i]).getGetterClass() != null && Number.class.isAssignableFrom(((NodeType)_children[i]).getGetterClass())) || (valueClass != null && valueClass.isPrimitive())) { parmString = " ($w) " + parmString; } else if (valueClass != null && valueClass.isPrimitive()) { parmString = "($w) " + parmString; } } result += parmString; } if (prevCast != null) { context.put(ExpressionCompiler.PRE_CAST, prevCast); } } } catch (Throwable t) { throw OgnlOps.castToRuntime(t); } try { Object contextObj = getValueBody(context, target); context.setCurrentObject(contextObj); } catch (Throwable t) { // ignore } context.setCurrentType(m.getReturnType()); context.setCurrentAccessor(OgnlRuntime.getCompiler().getSuperOrInterfaceClass(m, m.getDeclaringClass())); return result + ")" + post; } }
package org.joda.time.chrono; import java.util.ArrayList; import java.util.HashMap; import java.util.Locale; import java.util.Map; import org.joda.time.Chronology; // Import for @link support import org.joda.time.DateTimeConstants; import org.joda.time.DateTimeField; import org.joda.time.DateTimeZone; import org.joda.time.DurationField; import org.joda.time.Instant; import org.joda.time.ReadableInstant; import org.joda.time.field.AbstractDateTimeField; import org.joda.time.field.DecoratedDurationField; import org.joda.time.format.DateTimePrinter; import org.joda.time.format.ISODateTimeFormat; /** * GJChronology provides access to the individual date time fields for the * Gregorian/Julian defined chronological calendar system. * <p> * The Gregorian calendar replaced the Julian calendar, and the point in time * when this chronology switches can be controlled using the second parameter * of the getInstance method. By default this cutover is set to the date the * Gregorian calendar was first instituted, October 15, 1582. * <p> * Before this date, this chronology uses the proleptic Julian calendar * (proleptic means extending indefinitely). The Julian calendar has leap years * every four years, whereas the Gregorian has special rules for 100 and 400 * years. A meaningful result will thus be obtained for all input values. * However before 8 CE, Julian leap years were irregular, and before 45 BCE * there was no Julian calendar. * <p> * This chronology differs from {@link java.util.GregorianCalendar * java.util.GregorianCalendar} in that years in BCE are returned * correctly. Thus year 1 BCE is returned as -1 instead of 1. The yearOfEra * field produces results compatible with GregorianCalendar. * <p> * The Julian calendar does not have a year zero, and so year -1 is followed by * year 1. If the Gregorian cutover date is specified at or before year -1 * (Julian), year zero is defined. In other words, the proleptic Gregorian * chronology used by this class has a year zero. * <p> * To create a pure proleptic Julian chronology, use {@link JulianChronology}, * and to create a pure proleptic Gregorian chronology, use * {@link GregorianChronology}. * <p> * GJChronology is thread-safe and immutable. * * @author Brian S O'Neill * @author Stephen Colebourne * @since 1.0 */ public final class GJChronology extends AssembledChronology { static final long serialVersionUID = -2545574827706931671L; /** * Convert a datetime from one chronology to another. */ private static long convertByYear(long instant, Chronology from, Chronology to) { return to.getDateTimeMillis (from.year().get(instant), from.monthOfYear().get(instant), from.dayOfMonth().get(instant), from.millisOfDay().get(instant)); } /** * Convert a datetime from one chronology to another. */ private static long convertByWeekyear(final long instant, Chronology from, Chronology to) { long newInstant; newInstant = to.weekyear().set(0, from.weekyear().get(instant)); newInstant = to.weekOfWeekyear().set(newInstant, from.weekOfWeekyear().get(instant)); newInstant = to.dayOfWeek().set(newInstant, from.dayOfWeek().get(instant)); newInstant = to.millisOfDay().set(newInstant, from.millisOfDay().get(instant)); return newInstant; } /** * The default GregorianJulian cutover point */ static final Instant DEFAULT_CUTOVER = new Instant(-12219292800000L); /** Cache of zone to chronology list */ private static final Map cCache = new HashMap(); /** * Factory method returns instances of the default GJ cutover * chronology. This uses a cutover date of October 15, 1582 (Gregorian) * 00:00:00 UTC. For this value, October 4, 1582 (Julian) is followed by * October 15, 1582 (Gregorian). * * <p>The first day of the week is designated to be * {@link DateTimeConstants#MONDAY Monday}, and the minimum days in the * first week of the year is 4. * * <p>The time zone of the returned instance is UTC. */ public static GJChronology getInstanceUTC() { return getInstance(DateTimeZone.UTC, DEFAULT_CUTOVER, 4); } /** * Factory method returns instances of the default GJ cutover * chronology. This uses a cutover date of October 15, 1582 (Gregorian) * 00:00:00 UTC. For this value, October 4, 1582 (Julian) is followed by * October 15, 1582 (Gregorian). * * <p>The first day of the week is designated to be * {@link DateTimeConstants#MONDAY Monday}, and the minimum days in the * first week of the year is 4. * * <p>The returned chronology is in the default time zone. */ public static GJChronology getInstance() { return getInstance(DateTimeZone.getDefault(), DEFAULT_CUTOVER, 4); } /** * Factory method returns instances of the GJ cutover chronology. This uses * a cutover date of October 15, 1582 (Gregorian) 00:00:00 UTC. For this * value, October 4, 1582 (Julian) is followed by October 15, 1582 * (Gregorian). * * <p>The first day of the week is designated to be * {@link DateTimeConstants#MONDAY Monday}, and the minimum days in the * first week of the year is 4. * * @param zone the time zone to use, null is default */ public static GJChronology getInstance(DateTimeZone zone) { return getInstance(zone, DEFAULT_CUTOVER, 4); } /** * Factory method returns instances of the GJ cutover chronology. Any * cutover date may be specified. * * <p>The first day of the week is designated to be * {@link DateTimeConstants#MONDAY Monday}, and the minimum days in the * first week of the year is 4. * * @param zone the time zone to use, null is default * @param gregorianCutover the cutover to use, null means default */ public static GJChronology getInstance(DateTimeZone zone, ReadableInstant gregorianCutover) { return getInstance(zone, gregorianCutover, 4); } /** * Factory method returns instances of the GJ cutover chronology. Any * cutover date may be specified. * * @param zone the time zone to use, null is default * @param gregorianCutover the cutover to use, null means default * @param minDaysInFirstWeek minimum number of days in first week of the year; default is 4 */ public static synchronized GJChronology getInstance(DateTimeZone zone, ReadableInstant gregorianCutover, int minDaysInFirstWeek) { if (zone == null) { zone = DateTimeZone.getDefault(); } Instant cutoverInstant; if (gregorianCutover == null) { cutoverInstant = DEFAULT_CUTOVER; } else { cutoverInstant = gregorianCutover.toInstant(); } GJChronology chrono; ArrayList chronos = (ArrayList)cCache.get(zone); if (chronos == null) { chronos = new ArrayList(2); cCache.put(zone, chronos); } else { for (int i=chronos.size(); --i>=0; ) { chrono = (GJChronology)chronos.get(i); if (minDaysInFirstWeek == chrono.getMinimumDaysInFirstWeek() && cutoverInstant.equals(chrono.getGregorianCutover())) { return chrono; } } } if (zone == DateTimeZone.UTC) { chrono = new GJChronology (JulianChronology.getInstance(zone, minDaysInFirstWeek), GregorianChronology.getInstance(zone, minDaysInFirstWeek), cutoverInstant); } else { chrono = getInstance(DateTimeZone.UTC, cutoverInstant, minDaysInFirstWeek); chrono = new GJChronology (ZonedChronology.getInstance(chrono, zone), chrono.iJulianChronology, chrono.iGregorianChronology, chrono.iCutoverInstant); } chronos.add(chrono); return chrono; } /** * Factory method returns instances of the GJ cutover chronology. Any * cutover date may be specified. * * @param zone the time zone to use, null is default * @param gregorianCutover the cutover to use * @param minDaysInFirstWeek minimum number of days in first week of the year; default is 4 */ public static synchronized GJChronology getInstance(DateTimeZone zone, long gregorianCutover, int minDaysInFirstWeek) { Instant cutoverInstant; if (gregorianCutover == DEFAULT_CUTOVER.getMillis()) { cutoverInstant = null; } else { cutoverInstant = new Instant(gregorianCutover); } return getInstance(zone, cutoverInstant, minDaysInFirstWeek); } private JulianChronology iJulianChronology; private GregorianChronology iGregorianChronology; private Instant iCutoverInstant; long iCutoverMillis; long iGapDuration; /** * @param julian chronology used before the cutover instant * @param gregorian chronology used at and after the cutover instant * @param cutoverInstant instant when the gregorian chronology began */ private GJChronology(JulianChronology julian, GregorianChronology gregorian, Instant cutoverInstant) { super(null, new Object[] {julian, gregorian, cutoverInstant}); } /** * Called when applying a time zone. */ private GJChronology(Chronology base, JulianChronology julian, GregorianChronology gregorian, Instant cutoverInstant) { super(base, new Object[] {julian, gregorian, cutoverInstant}); } /** * Serialization singleton */ private Object readResolve() { return getInstance(getDateTimeZone(), iCutoverInstant, getMinimumDaysInFirstWeek()); } public DateTimeZone getDateTimeZone() { Chronology base; if ((base = getBase()) != null) { return base.getDateTimeZone(); } return DateTimeZone.UTC; } // Conversion /** * Gets the Chronology in the UTC time zone. * * @return the chronology in UTC */ public Chronology withUTC() { return withDateTimeZone(DateTimeZone.UTC); } /** * Gets the Chronology in a specific time zone. * * @param zone the zone to get the chronology in, null is default * @return the chronology */ public Chronology withDateTimeZone(DateTimeZone zone) { if (zone == null) { zone = DateTimeZone.getDefault(); } if (zone == getDateTimeZone()) { return this; } return getInstance(zone, iCutoverInstant, getMinimumDaysInFirstWeek()); } public long getDateOnlyMillis(int year, int monthOfYear, int dayOfMonth) throws IllegalArgumentException { Chronology base; if ((base = getBase()) != null) { return base.getDateOnlyMillis(year, monthOfYear, dayOfMonth); } return getDateTimeMillis(year, monthOfYear, dayOfMonth, 0); } public long getTimeOnlyMillis(int hourOfDay, int minuteOfHour, int secondOfMinute, int millisOfSecond) throws IllegalArgumentException { Chronology base; if ((base = getBase()) != null) { return base.getTimeOnlyMillis(hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond); } // Time fields are same for Julian and Gregorian. return iGregorianChronology.getTimeOnlyMillis (hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond); } public long getDateTimeMillis(int year, int monthOfYear, int dayOfMonth, int millisOfDay) throws IllegalArgumentException { Chronology base; if ((base = getBase()) != null) { return base.getDateTimeMillis(year, monthOfYear, dayOfMonth, millisOfDay); } // Assume date is Gregorian. long instant = iGregorianChronology.getDateTimeMillis (year, monthOfYear, dayOfMonth, millisOfDay); if (instant < iCutoverMillis) { // Maybe it's Julian. instant = iJulianChronology.getDateTimeMillis (year, monthOfYear, dayOfMonth, millisOfDay); if (instant >= iCutoverMillis) { throw new IllegalArgumentException("Specified date does not exist"); } } return instant; } public long getDateTimeMillis(long instant, int hourOfDay, int minuteOfHour, int secondOfMinute, int millisOfSecond) throws IllegalArgumentException { Chronology base; if ((base = getBase()) != null) { return base.getDateTimeMillis (instant, hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond); } return getDateOnlyMillis(instant) + getTimeOnlyMillis(hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond); } public long getDateTimeMillis(int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour, int secondOfMinute, int millisOfSecond) throws IllegalArgumentException { Chronology base; if ((base = getBase()) != null) { return base.getDateTimeMillis (year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond); } return getDateTimeMillis(year, monthOfYear, dayOfMonth, 0) + getTimeOnlyMillis(hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond); } /** * Gets the cutover instant between Gregorian and Julian chronologies. * @return the cutover instant */ public Instant getGregorianCutover() { return iCutoverInstant; } public final int getMinimumDaysInFirstWeek() { return iGregorianChronology.getMinimumDaysInFirstWeek(); } // Output /** * Gets a debugging toString. * * @return a debugging string */ public String toString() { StringBuffer sb = new StringBuffer(60); sb.append("GJCutoverChronology"); sb.append('['); sb.append(getDateTimeZone().getID()); sb.append(", "); sb.append("cutover="); ISODateTimeFormat format = ISODateTimeFormat.getInstance(withUTC()); DateTimePrinter printer; if (withUTC().getTimeOnlyMillis(iCutoverMillis) == 0) { printer = format.date(); } else { printer = format.dateTime(); } printer.printTo(sb, iCutoverMillis); sb.append(", mdfw="); sb.append(getMinimumDaysInFirstWeek()); sb.append(']'); return sb.toString(); } protected void assemble(Fields fields) { Object[] params = (Object[])getParam(); JulianChronology julian = (JulianChronology)params[0]; GregorianChronology gregorian = (GregorianChronology)params[1]; Instant cutoverInstant = (Instant)params[2]; iCutoverMillis = cutoverInstant.getMillis(); iJulianChronology = julian; iGregorianChronology = gregorian; iCutoverInstant = cutoverInstant; if (getBase() != null) { return; } if (julian.getMinimumDaysInFirstWeek() != gregorian.getMinimumDaysInFirstWeek()) { throw new IllegalArgumentException(); } // Compute difference between the chronologies at the cutover instant iGapDuration = iCutoverMillis - julianToGregorianByYear(iCutoverMillis); // Begin field definitions. // First just copy all the Gregorian fields and then override those // that need special attention. fields.copyFieldsFrom(gregorian); // Assuming cutover is at midnight, all time of day fields can be // gregorian since they are unaffected by cutover. // Verify assumption. if (gregorian.millisOfDay().get(iCutoverMillis) == 0) { // Cutover is sometime in the day, so cutover fields are required // for time of day. fields.millisOfSecond = new CutoverField(julian.millisOfSecond(), fields.millisOfSecond); fields.millisOfDay = new CutoverField(julian.millisOfDay(), fields.millisOfDay); fields.secondOfMinute = new CutoverField(julian.secondOfMinute(), fields.secondOfMinute); fields.secondOfDay = new CutoverField(julian.secondOfDay(), fields.secondOfDay); fields.minuteOfHour = new CutoverField(julian.minuteOfHour(), fields.minuteOfHour); fields.minuteOfDay = new CutoverField(julian.minuteOfDay(), fields.minuteOfDay); fields.hourOfDay = new CutoverField(julian.hourOfDay(), fields.hourOfDay); fields.hourOfHalfday = new CutoverField(julian.hourOfHalfday(), fields.hourOfHalfday); fields.clockhourOfDay = new CutoverField(julian.clockhourOfDay(), fields.clockhourOfDay); fields.clockhourOfHalfday = new CutoverField(julian.clockhourOfHalfday(), fields.clockhourOfHalfday); fields.halfdayOfDay = new CutoverField(julian.halfdayOfDay(), fields.halfdayOfDay); } // These fields just require basic cutover support. { fields.era = new CutoverField(julian.era(), fields.era); fields.dayOfMonth = new CutoverField(julian.dayOfMonth(), fields.dayOfMonth); } // DayOfYear and weekOfWeekyear require special handling since cutover // year has fewer days and weeks. Extend the cutover to the start of // the next year or weekyear. This keeps the sequence unbroken during // the cutover year. { long cutover = gregorian.year().roundCeiling(iCutoverMillis); fields.dayOfYear = new CutoverField (julian.dayOfYear(), fields.dayOfYear, cutover); } { long cutover = gregorian.weekyear().roundCeiling(iCutoverMillis); fields.weekOfWeekyear = new CutoverField (julian.weekOfWeekyear(), fields.weekOfWeekyear, cutover, true); } // These fields are special because they have imprecise durations. The // family of addition methods need special attention. Override affected // duration fields as well. { fields.year = new ImpreciseCutoverField(julian.year(), fields.year); fields.years = fields.year.getDurationField(); fields.yearOfEra = new ImpreciseCutoverField (julian.yearOfEra(), fields.yearOfEra, fields.years); fields.yearOfCentury = new ImpreciseCutoverField (julian.yearOfCentury(), fields.yearOfCentury, fields.years); fields.centuryOfEra = new ImpreciseCutoverField (julian.centuryOfEra(), fields.centuryOfEra); fields.centuries = fields.centuryOfEra.getDurationField(); fields.monthOfYear = new ImpreciseCutoverField (julian.monthOfYear(), fields.monthOfYear); fields.months = fields.monthOfYear.getDurationField(); fields.weekyear = new ImpreciseCutoverField(julian.weekyear(), fields.weekyear, true); fields.weekyears = fields.weekyear.getDurationField(); } } long julianToGregorianByYear(long instant) { return convertByYear(instant, iJulianChronology, iGregorianChronology); } long gregorianToJulianByYear(long instant) { return convertByYear(instant, iGregorianChronology, iJulianChronology); } long julianToGregorianByWeekyear(long instant) { return convertByWeekyear(instant, iJulianChronology, iGregorianChronology); } long gregorianToJulianByWeekyear(long instant) { return convertByWeekyear(instant, iGregorianChronology, iJulianChronology); } /** * This basic cutover field adjusts calls to 'get' and 'set' methods, and * assumes that calls to add and addWrapped are unaffected by the cutover. */ private class CutoverField extends AbstractDateTimeField { static final long serialVersionUID = 3528501219481026402L; final DateTimeField iJulianField; final DateTimeField iGregorianField; final long iCutover; final boolean iConvertByWeekyear; protected DurationField iDurationField; /** * @param julianField field from the chronology used before the cutover instant * @param gregorianField field from the chronology used at and after the cutover */ CutoverField(DateTimeField julianField, DateTimeField gregorianField) { this(julianField, gregorianField, iCutoverMillis, false); } /** * @param julianField field from the chronology used before the cutover instant * @param gregorianField field from the chronology used at and after the cutover * @param convertByWeekyear */ CutoverField(DateTimeField julianField, DateTimeField gregorianField, boolean convertByWeekyear) { this(julianField, gregorianField, iCutoverMillis, convertByWeekyear); } CutoverField(DateTimeField julianField, DateTimeField gregorianField, long cutoverMillis) { this(julianField, gregorianField, cutoverMillis, false); } CutoverField(DateTimeField julianField, DateTimeField gregorianField, long cutoverMillis, boolean convertByWeekyear) { super(gregorianField.getName()); iJulianField = julianField; iGregorianField = gregorianField; iCutover = cutoverMillis; iConvertByWeekyear = convertByWeekyear; // Although average length of Julian and Gregorian years differ, // use the Gregorian duration field because it is more accurate. iDurationField = gregorianField.getDurationField(); } public boolean isLenient() { return false; } public int get(long instant) { if (instant >= iCutover) { return iGregorianField.get(instant); } else { return iJulianField.get(instant); } } public String getAsText(long instant, Locale locale) { if (instant >= iCutover) { return iGregorianField.getAsText(instant, locale); } else { return iJulianField.getAsText(instant, locale); } } public String getAsShortText(long instant, Locale locale) { if (instant >= iCutover) { return iGregorianField.getAsShortText(instant, locale); } else { return iJulianField.getAsShortText(instant, locale); } } public long add(long instant, int value) { return iGregorianField.add(instant, value); } public long add(long instant, long value) { return iGregorianField.add(instant, value); } public int getDifference(long minuendInstant, long subtrahendInstant) { return iGregorianField.getDifference(minuendInstant, subtrahendInstant); } public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { return iGregorianField.getDifferenceAsLong(minuendInstant, subtrahendInstant); } public long set(long instant, int value) { if (instant >= iCutover) { instant = iGregorianField.set(instant, value); if (instant < iCutover) { // Only adjust if gap fully crossed. if (instant + iGapDuration < iCutover) { instant = gregorianToJulian(instant); } // Verify that new value stuck. if (get(instant) != value) { throw new IllegalArgumentException ("Illegal value for " + iGregorianField.getName() + ": " + value); } } } else { instant = iJulianField.set(instant, value); if (instant >= iCutover) { // Only adjust if gap fully crossed. if (instant - iGapDuration >= iCutover) { instant = julianToGregorian(instant); } // Verify that new value stuck. if (get(instant) != value) { throw new IllegalArgumentException ("Illegal value for " + iJulianField.getName() + ": " + value); } } } return instant; } public long set(long instant, String text, Locale locale) { if (instant >= iCutover) { instant = iGregorianField.set(instant, text, locale); if (instant < iCutover) { // Only adjust if gap fully crossed. if (instant + iGapDuration < iCutover) { instant = gregorianToJulian(instant); } // Cannot verify that new value stuck because set may be lenient. } } else { instant = iJulianField.set(instant, text, locale); if (instant >= iCutover) { // Only adjust if gap fully crossed. if (instant - iGapDuration >= iCutover) { instant = julianToGregorian(instant); } // Cannot verify that new value stuck because set may be lenient. } } return instant; } public DurationField getDurationField() { return iDurationField; } public DurationField getRangeDurationField() { DurationField rangeField = iGregorianField.getRangeDurationField(); if (rangeField == null) { rangeField = iJulianField.getRangeDurationField(); } return rangeField; } public boolean isLeap(long instant) { if (instant >= iCutover) { return iGregorianField.isLeap(instant); } else { return iJulianField.isLeap(instant); } } public int getLeapAmount(long instant) { if (instant >= iCutover) { return iGregorianField.getLeapAmount(instant); } else { return iJulianField.getLeapAmount(instant); } } public DurationField getLeapDurationField() { return iGregorianField.getLeapDurationField(); } public int getMinimumValue() { // For all precise fields, the Julian and Gregorian limits are // identical. Choose Julian to tighten up the year limits. return iJulianField.getMinimumValue(); } public int getMinimumValue(long instant) { if (instant < iCutover) { return iJulianField.getMinimumValue(instant); } int min = iGregorianField.getMinimumValue(instant); // Because the cutover may reduce the length of this field, verify // the minimum by setting it. instant = iGregorianField.set(instant, min); if (instant < iCutover) { min = iGregorianField.get(iCutover); } return min; } public int getMaximumValue() { // For all precise fields, the Julian and Gregorian limits are // identical. return iGregorianField.getMaximumValue(); } public int getMaximumValue(long instant) { if (instant >= iCutover) { return iGregorianField.getMaximumValue(instant); } int max = iJulianField.getMaximumValue(instant); // Because the cutover may reduce the length of this field, verify // the maximum by setting it. instant = iJulianField.set(instant, max); if (instant >= iCutover) { max = iJulianField.get(iJulianField.add(iCutover, -1)); } return max; } public long roundFloor(long instant) { if (instant >= iCutover) { instant = iGregorianField.roundFloor(instant); if (instant < iCutover) { // Only adjust if gap fully crossed. if (instant + iGapDuration < iCutover) { instant = gregorianToJulian(instant); } } } else { instant = iJulianField.roundFloor(instant); } return instant; } public long roundCeiling(long instant) { if (instant >= iCutover) { instant = iGregorianField.roundCeiling(instant); } else { instant = iJulianField.roundCeiling(instant); if (instant >= iCutover) { // Only adjust if gap fully crossed. if (instant - iGapDuration >= iCutover) { instant = julianToGregorian(instant); } } } return instant; } public int getMaximumTextLength(Locale locale) { return Math.max(iJulianField.getMaximumTextLength(locale), iGregorianField.getMaximumTextLength(locale)); } public int getMaximumShortTextLength(Locale locale) { return Math.max(iJulianField.getMaximumShortTextLength(locale), iGregorianField.getMaximumShortTextLength(locale)); } protected long julianToGregorian(long instant) { if (iConvertByWeekyear) { return julianToGregorianByWeekyear(instant); } else { return julianToGregorianByYear(instant); } } protected long gregorianToJulian(long instant) { if (iConvertByWeekyear) { return gregorianToJulianByWeekyear(instant); } else { return gregorianToJulianByYear(instant); } } } /** * Cutover field for variable length fields. These fields internally call * set whenever add is called. As a result, the same correction applied to * set must be applied to add and addWrapped. Knowing when to use this * field requires specific knowledge of how the GJ fields are implemented. */ private final class ImpreciseCutoverField extends CutoverField { static final long serialVersionUID = 3410248757173576441L; /** * Creates a duration field that links back to this. */ ImpreciseCutoverField(DateTimeField julianField, DateTimeField gregorianField) { this(julianField, gregorianField, null, false); } /** * Creates a duration field that links back to this. */ ImpreciseCutoverField(DateTimeField julianField, DateTimeField gregorianField, boolean convertByWeekyear) { this(julianField, gregorianField, null, convertByWeekyear); } /** * Uses a shared duration field rather than creating a new one. * * @param durationField shared duration field */ ImpreciseCutoverField(DateTimeField julianField, DateTimeField gregorianField, DurationField durationField) { this(julianField, gregorianField, durationField, false); } /** * Uses a shared duration field rather than creating a new one. * * @param durationField shared duration field */ ImpreciseCutoverField(DateTimeField julianField, DateTimeField gregorianField, DurationField durationField, boolean convertByWeekyear) { super(julianField, gregorianField, convertByWeekyear); if (durationField == null) { durationField = new LinkedDurationField(iDurationField, this); } iDurationField = durationField; } public long add(long instant, int value) { if (instant >= iCutover) { instant = iGregorianField.add(instant, value); if (instant < iCutover) { // Only adjust if gap fully crossed. if (instant + iGapDuration < iCutover) { instant = gregorianToJulian(instant); } } } else { instant = iJulianField.add(instant, value); if (instant >= iCutover) { // Only adjust if gap fully crossed. if (instant - iGapDuration >= iCutover) { instant = julianToGregorian(instant); } } } return instant; } public long add(long instant, long value) { if (instant >= iCutover) { instant = iGregorianField.add(instant, value); if (instant < iCutover) { // Only adjust if gap fully crossed. if (instant + iGapDuration < iCutover) { instant = gregorianToJulian(instant); } } } else { instant = iJulianField.add(instant, value); if (instant >= iCutover) { // Only adjust if gap fully crossed. if (instant - iGapDuration >= iCutover) { instant = julianToGregorian(instant); } } } return instant; } public int getDifference(long minuendInstant, long subtrahendInstant) { if (minuendInstant >= iCutover) { if (subtrahendInstant >= iCutover) { return iGregorianField.getDifference(minuendInstant, subtrahendInstant); } // Remember, the add is being reversed. Since subtrahend is // Julian, convert minuend to Julian to match. minuendInstant = gregorianToJulian(minuendInstant); return iJulianField.getDifference(minuendInstant, subtrahendInstant); } else { if (subtrahendInstant < iCutover) { return iJulianField.getDifference(minuendInstant, subtrahendInstant); } // Remember, the add is being reversed. Since subtrahend is // Gregorian, convert minuend to Gregorian to match. minuendInstant = julianToGregorian(minuendInstant); return iGregorianField.getDifference(minuendInstant, subtrahendInstant); } } public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { if (minuendInstant >= iCutover) { if (subtrahendInstant >= iCutover) { return iGregorianField.getDifferenceAsLong(minuendInstant, subtrahendInstant); } // Remember, the add is being reversed. Since subtrahend is // Julian, convert minuend to Julian to match. minuendInstant = gregorianToJulian(minuendInstant); return iJulianField.getDifferenceAsLong(minuendInstant, subtrahendInstant); } else { if (subtrahendInstant < iCutover) { return iJulianField.getDifferenceAsLong(minuendInstant, subtrahendInstant); } // Remember, the add is being reversed. Since subtrahend is // Gregorian, convert minuend to Gregorian to match. minuendInstant = julianToGregorian(minuendInstant); return iGregorianField.getDifferenceAsLong(minuendInstant, subtrahendInstant); } } // Since the imprecise fields have durations longer than the gap // duration, keep these methods simple. The inherited implementations // produce incorrect results. // Degenerate case: If this field is a month, and the cutover is set // far into the future, then the gap duration may be so large as to // reduce the number of months in a year. If the missing month(s) are // at the beginning or end of the year, then the minimum and maximum // values are not 1 and 12. I don't expect this case to ever occur. public int getMinimumValue(long instant) { if (instant >= iCutover) { return iGregorianField.getMinimumValue(instant); } else { return iJulianField.getMinimumValue(instant); } } public int getMaximumValue(long instant) { if (instant >= iCutover) { return iGregorianField.getMaximumValue(instant); } else { return iJulianField.getMaximumValue(instant); } } } /** * Links the duration back to a ImpreciseCutoverField. */ private static class LinkedDurationField extends DecoratedDurationField { static final long serialVersionUID = 4097975388007713084L; private final ImpreciseCutoverField iField; LinkedDurationField(DurationField durationField, ImpreciseCutoverField dateTimeField) { super(durationField, durationField.getName()); iField = dateTimeField; } public long add(long instant, int value) { return iField.add(instant, value); } public long add(long instant, long value) { return iField.add(instant, value); } public int getDifference(long minuendInstant, long subtrahendInstant) { return iField.getDifference(minuendInstant, subtrahendInstant); } public long getDifferenceAsLong(long minuendInstant, long subtrahendInstant) { return iField.getDifferenceAsLong(minuendInstant, subtrahendInstant); } } }
package ameba.mvc; import ameba.mvc.template.internal.Viewables; import com.google.common.collect.Maps; import org.apache.commons.lang3.StringUtils; import org.glassfish.jersey.server.mvc.Viewable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Singleton; import javax.ws.rs.WebApplicationException; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; import java.util.HashMap; @Provider @Singleton public class ErrorPageGenerator implements ExceptionMapper<Throwable> { protected static final HashMap<Integer, String> errorTemplateMap = Maps.newHashMap(); public static final String DEFAULT_ERROR_PAGE_DIR = "/__views/ameba/error/"; public static final String DEFAULT_404_ERROR_PAGE = DEFAULT_ERROR_PAGE_DIR + "404.html"; public static final String DEFAULT_5XX_PRODUCT_ERROR_PAGE = DEFAULT_ERROR_PAGE_DIR + "500.html"; public static final String DEFAULT_501_ERROR_PAGE = DEFAULT_ERROR_PAGE_DIR + "501.html"; public static final String DEFAULT_403_ERROR_PAGE = DEFAULT_ERROR_PAGE_DIR + "403.html"; public static final String DEFAULT_400_ERROR_PAGE = DEFAULT_ERROR_PAGE_DIR + "400.html"; public static final String DEFAULT_405_ERROR_PAGE = DEFAULT_ERROR_PAGE_DIR + "405.html"; private static final Logger logger = LoggerFactory.getLogger(ErrorPageGenerator.class); private static String defaultErrorTemplate; @Context protected javax.inject.Provider<ContainerRequestContext> requestProvider; static void pushErrorMap(int status, String tpl) { errorTemplateMap.put(status, tpl); } static void pushAllErrorMap(HashMap<Integer, String> map) { errorTemplateMap.putAll(map); } public static HashMap<Integer, String> getErrorTemplateMap() { return errorTemplateMap; } public static String getDefaultErrorTemplate() { return defaultErrorTemplate; } static void setDefaultErrorTemplate(String template) { defaultErrorTemplate = template; } @Override public Response toResponse(Throwable exception) { ContainerRequestContext request = requestProvider.get(); int status = 500; if (exception instanceof WebApplicationException) { status = ((WebApplicationException) exception).getResponse().getStatus(); } String tplName = errorTemplateMap.get(status); if (StringUtils.isBlank(tplName)) { if (StringUtils.isBlank(defaultErrorTemplate)) { if (status < 500) { switch (status) { case 401: case 403: tplName = DEFAULT_403_ERROR_PAGE; break; case 404: tplName = DEFAULT_404_ERROR_PAGE; break; case 405: tplName = DEFAULT_405_ERROR_PAGE; break; default: tplName = DEFAULT_400_ERROR_PAGE; } } else { switch (status) { case 501: tplName = DEFAULT_501_ERROR_PAGE; break; default: tplName = DEFAULT_5XX_PRODUCT_ERROR_PAGE; } } } else { tplName = defaultErrorTemplate; } } Object viewable = createViewable(tplName, request, status, exception); if (status == 500) logger.error("", exception); return Response.status(status).entity(viewable).build(); } private Viewable createViewable(String tplName, ContainerRequestContext request, int status, Throwable exception) { Error error = new Error( request, status, exception); return Viewables.newDefaultViewable(tplName, error); } public static class Error { private int status; private ContainerRequestContext request; private Throwable exception; public Error() { } public Error(ContainerRequestContext request, int status, Throwable exception) { this.status = status; this.exception = exception; this.request = request; } public int getStatus() { return status; } public ContainerRequestContext getRequest() { return request; } public Throwable getException() { return exception; } } }
package br.uff.ic.utility.graph; import br.uff.ic.utility.GraphAttribute; import br.uff.ic.provviewer.EdgeType; import br.uff.ic.provviewer.Variables; import br.uff.ic.utility.Utils; import java.awt.Color; import java.awt.Paint; import java.util.HashMap; import java.util.Map; /** * Edge Class * * @author Kohwalter */ public class Edge extends GraphObject { private String id; private Object source; private Object target; //private String influence; // Influence type (i.e. Damage) private String value; // Influence Value (i.e. 5.0) private final String type; // Edge type (prov edges) //used to hide this edge when collapsing a group of edges private boolean hide; //used to say this edge is a temporary one private boolean collapsed; /** * Constructor * * @param id * @param influence * @param type * @param value * @param label * @param attributes * @param target * @param source */ public Edge(String id, String influence, String type, String value, String label, Map<String, GraphAttribute> attributes, Object target, Object source) { this.id = id; this.source = source; this.target = target; this.type = type; if (influence.equalsIgnoreCase("") || (influence == null) || influence.equalsIgnoreCase("Neutral")) { setLabel("Neutral"); this.value = "0"; } else { setLabel(influence); this.value = value; } setLabel(label); hide = false; collapsed = false; this.attributes.putAll(attributes); } /** * Constructor without extra attributes * * @param id * @param type * @param value * @param label * @param target * @param source */ public Edge(String id, String type, String label, String value, Object target, Object source) { this.id = id; this.source = source; this.target = target; this.type = type; if (label.equalsIgnoreCase("") || label == null || "-".equals(label) || label.equalsIgnoreCase("Neutral")) { setLabel("Neutral"); this.value = "0"; } else { this.value = value; } setLabel(label); hide = false; collapsed = false; this.attributes = new HashMap<>(); } /** * Constructor without influence value, label, type (type=influence) and no * extra attribute * * @param id Edge's ID * @deprecated Used only on outdated TSVReader * @param target Vertex target * @param source Vertex source * @param influence Influence value and name (i.e. "+9 damage") */ public Edge(String id, Object target, Object source, String influence) { this.id = id; this.source = source; this.target = target; if (influence.equalsIgnoreCase("")) { setLabel("Neutral"); } else { setLabel(influence); } this.value = "0"; this.type = getLabel(); hide = false; collapsed = false; this.attributes = new HashMap<>(); } /** * Return Edge id * * @return */ public String getID() { return id; } public void setID(String t) { id = t; } /** * Method to get the edge source * * @return vertex source */ public Object getSource() { return source; } public void setSource(Object t) { source = t; } /** * Method to get the edge target * * @return vertex target */ public Object getTarget() { return target; } public void setTarget(Object t) { target = t; } /** * Method for returning the edge value * * @return (float) edge influence value */ public float getValue() { if (Utils.tryParseFloat(this.value)) { return Float.parseFloat(this.value); } else if (Utils.tryParseFloat(this.value.split(" ")[0])) { return Float.parseFloat(this.value.split(" ")[0]); } else { return 0; } } public void setValue(String t) { this.value = t; } /** * Method for returning the edge type * * @return */ public String getType() { return this.type; } /** * Method to get the edge influence + value * * @return (String) influence */ public String getEdgeTooltip() { String atts = ""; if (!this.attributes.values().isEmpty()) { atts = "<br>" + this.printAttributes(); } String v = this.value; String l = getLabel(); String t = "(" + this.type + ")"; if ("0".equals(this.value)) { v = ""; } if ("".equals(getLabel())) { l = ""; t = this.type; } if (getLabel().contentEquals(this.type)) { l = ""; t = this.type; } return v + " " + l + " " + t + " " + atts; // return v + " " + getLabel() + " (" + this.type + ")" + atts; } /** * Method to check if the edge is hidden (due to collapses) * * @return (boolean) if the edge is hidden or not */ public boolean isHidden() { return hide; } /** * Method to check if the edge is a collapsed edge (new edge that contains * the information of the collapsed ones) * * @return (boolean) if the edge is collapsed or not */ public boolean isCollapased() { return collapsed; } /** * Method to set the hide parameter * * @param t (boolean) Hide = t */ public void setHide(boolean t) { hide = t; } /** * Method to set the collapsed parameter * * @param t (boolean) collapsed = t */ public void setCollapse(boolean t) { collapsed = t; } /** * Method to check if the edge is of the neutral type (Empty influence or * value equals zero * * @return (boolean) is neutral or not */ public boolean isNeutral() { return (getLabel().equalsIgnoreCase("")) || (getLabel().isEmpty()) || (getLabel().equalsIgnoreCase("Neutral")); } /** * Method to override JUNG's default toString method * * @return edge details */ @Override public String toString() { String font = "<html><font size=\"3\", font color=\"blue\">"; if (getLabel().isEmpty()) { return font + this.type; } else if (getLabel().equals(this.type)) { return font + this.type; } else { return font + this.type + " (" + getLabel() + ")"; } } /** * Method to get the edge color (red, black, or green), defined by value * * @param variables * @return */ public Paint getColor(Variables variables) { float v = getValue(); // if(this.label.equalsIgnoreCase("Neutral")) // if(((Vertex)this.source).getDate() < 85) // return new Color(255, 0, 0); // if(((Vertex)this.source).getDate() < 150) // return new Color(0, 255, 0); // if(((Vertex)this.source).getDate() < 300) // return new Color(0, 0, 255); // Return blue if neutral edge (value = 0) if (v == 0) { return new Color(0, 0, 0); } else { int j = 0; for (int i = 0; i < variables.config.edgetype.size(); i++) { if (this.getLabel().contains(variables.config.edgetype.get(i).type)) { j = i; } } // TODO add inverted color scheme for increase in value to be red and decrease to be green if (variables.config.edgetype.get(j).isInverted) { if (v > 0) { return compareValueRed(v, 0, variables.config.edgetype.get(j).max, variables.config.edgetype.get(j).isInverted); } else { return compareValueGreen(v, variables.config.edgetype.get(j).min, 0, variables.config.edgetype.get(j).isInverted); } } else { // else if (v > 0) { return compareValueGreen(v, 0, variables.config.edgetype.get(j).max, variables.config.edgetype.get(j).isInverted); } else { return compareValueRed(v, variables.config.edgetype.get(j).min, 0, variables.config.edgetype.get(j).isInverted); } } } } public Paint compareValueGreen(float value, double min, double max, boolean isInverted) { if(!isInverted) { int proportion = (int) Math.round(510 * Math.abs(value - min) / (float) Math.abs(max - min)); proportion = Math.max(proportion, 0); return new Color(0, Math.min(255, proportion), 0); } else { int proportion = (int) Math.round(510 * Math.abs(value - min) / (float) Math.abs(max - min)); proportion = Math.min(proportion, 510); return new Color(0, Math.min(255, 510 - proportion), 0); } } public Paint compareValueRed(float value, double min, double max, boolean isInverted) { if(!isInverted) { int proportion = (int) Math.round(510 * Math.abs(value - min) / (float) Math.abs(max - min)); proportion = Math.min(proportion, 510); return new Color(Math.min(255, 510 - proportion), 0, 0); } else { int proportion = (int) Math.round(510 * Math.abs(value - min) / (float) Math.abs(max - min)); proportion = Math.max(proportion, 0); return new Color(Math.min(255, proportion), 0, 0); } } /** * Method used during the collapse of edges. This method defines if the * collapsed edge influence value will be the sum of the edges values or the * average * * @param variables * @return (boolean) Return true if influence from collapsed edges are * added. Return false if average */ public boolean addInfluence(Variables variables) { for (EdgeType edgetype : variables.config.edgetype) { if (this.getEdgeTooltip().contains(edgetype.type)) { if (edgetype.collapse.equalsIgnoreCase("AVERAGE")) { return false; } } } return true; } }
package ca.phcri; import ij.IJ; import ij.ImagePlus; import ij.WindowManager; import ij.gui.DialogListener; import ij.gui.GenericDialog; import ij.gui.Overlay; import ij.gui.Roi; import ij.gui.ShapeRoi; import ij.measure.Calibration; import ij.plugin.PlugIn; import ij.text.TextPanel; import ij.text.TextWindow; import java.awt.AWTEvent; import java.awt.Color; import java.awt.Component; import java.awt.Frame; import java.awt.Shape; import java.awt.geom.GeneralPath; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Random; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class CombinedGridsPlugin implements PlugIn, DialogListener { private final static String[] colors = { "Red", "Green", "Blue", "Magenta", "Cyan", "Yellow", "Orange", "Black", "White" }; private static String color = "Blue"; private final static int COMBINED = 0, DOUBLE_LATTICE = 1, LINES = 2, HLINES = 3, CROSSES = 4, POINTS = 5; private final static String[] types = { "Combined Point", "Double Lattice", "Lines", "Horizontal Lines", "Crosses", "Points" }; private static String type = types[COMBINED]; private static double areaPerPoint; private final static int ONE_TO_FOUR = 0, ONE_TO_NINE = 1, ONE_TO_SIXTEEN = 2, ONE_TO_TWENTYFIVE = 3, ONE_TO_THIRTYSIX = 4; private final static String[] ratioChoices = { "1:4", "1:9", "1:16", "1:25", "1:36" }; private static String gridRatio = ratioChoices[ONE_TO_FOUR]; private final static String[] radiobuttons = { "Random Offset", "Fixed Position", "Manual Input" }; private final static int RANDOM = 0, FIXED = 1, MANUAL = 2; private static String radiochoice = radiobuttons[RANDOM]; private static Component[] components; // this is to select components in the dialog box private final static int[] ratioField = { 4, 5 }; private final static int[] combinedGridFields = { 14, 15, 16, 17 }; private final static int[] parameterFieldsOff = { 10, 11, 12, 13, 14, 15, 16, 17 }; private final static int[] xstartField = { 10, 11 }; private final static int[] ystartField = { 12, 13 }; private static boolean showGridSwitch = true; private Random random = new Random(System.currentTimeMillis()); private ImagePlus imp; private double tileWidth, tileHeight; private int xstart, ystart; private int xstartCoarse, ystartCoarse, coarseGridX, coarseGridY; private int linesV, linesH; private double pixelWidth = 1.0, pixelHeight = 1.0; private String units; private String err = ""; public void run(String arg) { if (IJ.versionLessThan("1.47")) return; imp = IJ.getImage(); showDialog(); } void showGrid(Shape shape) { Overlay layer = imp.getOverlay(); if (shape == null) { if (layer != null) layer.remove(layer.getIndex("grid")); } else { Roi roi = new ShapeRoi(shape); roi.setStrokeColor(getColor()); roi.setName("grid"); if (layer != null) { if (layer.getIndex("grid") != -1) layer.remove(layer.getIndex("grid")); layer.add(roi); } else layer = new Overlay(roi); } imp.setOverlay(layer); } // methods to form grids void drawPoints() { int one = 1; int two = 2; GeneralPath path = new GeneralPath(); for (int h = 0; h < linesV; h++) { for (int v = 0; v < linesH; v++) { float x = (float) (xstart + h * tileWidth); float y = (float) (ystart + v * tileHeight); path.moveTo(x - two, y - one); path.lineTo(x - two, y + one); path.moveTo(x + two, y - one); path.lineTo(x + two, y + one); path.moveTo(x - one, y - two); path.lineTo(x + one, y - two); path.moveTo(x - one, y + two); path.lineTo(x + one, y + two); } } showGrid(path); } void drawCrosses() { GeneralPath path = new GeneralPath(); float arm = 5; for (int h = 0; h < linesV; h++) { for (int v = 0; v < linesH; v++) { float x = (float) (xstart + h * tileWidth); float y = (float) (ystart + v * tileHeight); path.moveTo(x - arm, y); path.lineTo(x + arm, y); path.moveTo(x, y - arm); path.lineTo(x, y + arm); } } showGrid(path); } void drawCombined() { GeneralPath path = new GeneralPath(); float arm = 5; float pointSizeCoarse = 10; float armCoarse = pointSizeCoarse / 2; for (int h = 0; h < linesV; h++) { for (int v = 0; v < linesH; v++) { float x = (float) (xstart + h * tileWidth); float y = (float) (ystart + v * tileHeight); path.moveTo(x - arm, y); path.lineTo(x + arm, y); path.moveTo(x, y - arm); path.lineTo(x, y + arm); if ((h % coarseGridX == 0) && (v % coarseGridY == 0)) { float centerX = (float) (xstart + xstartCoarse * tileWidth + h * tileWidth); float centerY = (float) (ystart + ystartCoarse * tileHeight + v * tileHeight); // drawing a coarse point by lines path.moveTo(centerX - pointSizeCoarse, centerY - armCoarse); path.lineTo(centerX - pointSizeCoarse, centerY + armCoarse); path.moveTo(centerX + pointSizeCoarse, centerY - 0); path.lineTo(centerX + pointSizeCoarse, centerY + armCoarse); path.moveTo(centerX - armCoarse, centerY - pointSizeCoarse); path.lineTo(centerX + 0, centerY - pointSizeCoarse); path.moveTo(centerX - armCoarse, centerY + pointSizeCoarse); path.lineTo(centerX + armCoarse, centerY + pointSizeCoarse); } } } showGrid(path); } void drawDoubleLattice() { GeneralPath path = new GeneralPath(); int width = imp.getWidth(); int height = imp.getHeight(); float rad = 14; float radkappa = (float) (rad * 0.5522847498); // ref for (int i = 0; i < linesV; i++) { float xoff = (float) (xstart + i * tileWidth); path.moveTo(xoff, 0f); path.lineTo(xoff, height); } for (int i = 0; i < linesH; i++) { float yoff = (float) (ystart + i * tileHeight); path.moveTo(0f, yoff); path.lineTo(width, yoff); } for (int h = 0; h < linesV; h++) { for (int v = 0; v < linesH; v++) { if ((h % coarseGridX == 0) && (v % coarseGridY == 0)) { float centerX = (float) (xstart + xstartCoarse * tileWidth + h * tileWidth); float centerY = (float) (ystart + ystartCoarse * tileHeight + v * tileHeight); // drawing curve for coarse grid path.moveTo(centerX, centerY - rad); path.curveTo(centerX - radkappa, centerY - rad, centerX - rad, centerY - radkappa, centerX - rad, centerY); path.curveTo(centerX - rad, centerY + radkappa, centerX - radkappa, centerY + rad, centerX, centerY + rad); path.curveTo(centerX + radkappa, centerY + rad, centerX + rad, centerY + radkappa, centerX + rad, centerY); } } } showGrid(path); } void drawLines() { GeneralPath path = new GeneralPath(); int width = imp.getWidth(); int height = imp.getHeight(); for (int i = 0; i < linesV; i++) { float xoff = (float) (xstart + i * tileWidth); path.moveTo(xoff, 0f); path.lineTo(xoff, height); } for (int i = 0; i < linesH; i++) { float yoff = (float) (ystart + i * tileHeight); path.moveTo(0f, yoff); path.lineTo(width, yoff); } showGrid(path); } void drawHorizontalLines() { GeneralPath path = new GeneralPath(); int width = imp.getWidth(); // int height = imp.getHeight(); for (int i = 0; i < linesH; i++) { float yoff = (float) (ystart + i * tileHeight); path.moveTo(0f, yoff); path.lineTo(width, yoff); } showGrid(path); } // end of methods for drawing grids void showDialog() { int width = imp.getWidth(); int height = imp.getHeight(); Calibration cal = imp.getCalibration(); int places; if (cal.scaled()) { pixelWidth = cal.pixelWidth; pixelHeight = cal.pixelHeight; units = cal.getUnits(); places = 2; } else { pixelWidth = 1.0; pixelHeight = 1.0; units = "pixels"; places = 0; } if (areaPerPoint == 0.0) // default to 9x9 grid areaPerPoint = (width * cal.pixelWidth * height * cal.pixelHeight) / 81.0; // get values in a dialog box GenericDialog gd = new GenericDialog("Grid..."); gd.addChoice("Grid Type:", types, type); gd.addNumericField("Area per Point:", areaPerPoint, places, 6, units + "^2"); gd.addChoice("Ratio:", ratioChoices, gridRatio); gd.addChoice("Color:", colors, color); gd.addRadioButtonGroup("Grid Location", radiobuttons, 3, 1, radiobuttons[RANDOM]); gd.addNumericField("xstart:", 0, 0); gd.addNumericField("ystart:", 0, 0); gd.addNumericField("xstartCoarse:", 0, 0); gd.addNumericField("ystartCoarse:", 0, 0); gd.addCheckbox("Show a Grid Switch if none exists", showGridSwitch); // to switch enable/disable parameter input boxes components = gd.getComponents(); for (int i : parameterFieldsOff) components[i].setEnabled(false); if (!(types[COMBINED].equals(type) || types[DOUBLE_LATTICE].equals(type))) for (int i : ratioField) components[i].setEnabled(false); gd.addDialogListener(this); gd.showDialog(); if (gd.wasCanceled()) showGrid(null); if (gd.wasOKed()) { if ("".equals(err)) { showParameterList(); if (showGridSwitch && !gridSwitchExist()){ Grid_Switch gs = new Grid_Switch(); gs.gridSwitch(); } } else { IJ.error("Grid", err); showGrid(null); } } } // event control for dialog box public boolean dialogItemChanged(GenericDialog gd, AWTEvent e) { int width = imp.getWidth(); int height = imp.getHeight(); type = gd.getNextChoice(); areaPerPoint = gd.getNextNumber(); gridRatio = gd.getNextChoice(); color = gd.getNextChoice(); radiochoice = gd.getNextRadioButton(); xstart = (int) gd.getNextNumber(); ystart = (int) gd.getNextNumber(); xstartCoarse = (int) gd.getNextNumber(); ystartCoarse = (int) gd.getNextNumber(); showGridSwitch = gd.getNextBoolean(); err = ""; IJ.showStatus(err); // if areaPerPoint is not too small, this shows error double minArea = (width * height) / 50000.0; if (type.equals(types[CROSSES]) && minArea < 144.0) minArea = 144.0; // to avoid overlap of grid points. // ((5 + 1) * 2) ^2 = 12^2 = 144 else if (type.equals(types[COMBINED]) && minArea < 484.0) minArea = 484.0; // As pointSizeCoarse = 10, //(10 + 1) * 2)^2 = 22^2 = 484 else if (type.equals(types[DOUBLE_LATTICE]) && minArea < 900.0) minArea = 900.0; // As rad = 14, ((14 + 1) * 2) ^2 = 900 else if (minArea < 16) minArea = 16.0; if (Double.isNaN(areaPerPoint) || areaPerPoint / (pixelWidth * pixelHeight) < minArea) { err = "\"Area per Point\" too small. \n"; areaPerPoint = 0; } // choose gridRatio for Combined Points and Double Lattice if (type.equals(types[COMBINED]) || type.equals(types[DOUBLE_LATTICE])) { for (int i : ratioField) components[i].setEnabled(true); } else { for (int i : ratioField) components[i].setEnabled(false); } if (gridRatio.equals(ratioChoices[ONE_TO_FOUR])) { coarseGridX = 2; coarseGridY = 2; } else if (gridRatio.equals(ratioChoices[ONE_TO_NINE])) { coarseGridX = 3; coarseGridY = 3; } else if (gridRatio.equals(ratioChoices[ONE_TO_SIXTEEN])) { coarseGridX = 4; coarseGridY = 4; } else if (gridRatio.equals(ratioChoices[ONE_TO_TWENTYFIVE])) { coarseGridX = 5; coarseGridY = 5; } else if (gridRatio.equals(ratioChoices[ONE_TO_THIRTYSIX])) { coarseGridX = 6; coarseGridY = 6; } // calculation for tileWidth and tileLength double tileSize = Math.sqrt(areaPerPoint); tileWidth = tileSize / pixelWidth; tileHeight = tileSize / pixelHeight; // choose first point(s) depending on the way to place grid if (radiochoice.equals(radiobuttons[RANDOM])) { for (int i : parameterFieldsOff) components[i].setEnabled(false); xstart = (int) (random.nextDouble() * tileWidth); ystart = (int) (random.nextDouble() * tileHeight); // 0 <= random.nextDouble() < 1 xstartCoarse = random.nextInt(coarseGridX); ystartCoarse = random.nextInt(coarseGridY); } else if (radiochoice.equals(radiobuttons[FIXED])) { for (int i : parameterFieldsOff) components[i].setEnabled(false); xstart = (int) (tileWidth / 2.0 + 0.5); ystart = (int) (tileHeight / 2.0 + 0.5); xstartCoarse = 0; ystartCoarse = 0; } else if (radiochoice.equals(radiobuttons[MANUAL])) { for (int i : ystartField) components[i].setEnabled(true); if (type.equals(types[HLINES])) { for (int i : xstartField) components[i].setEnabled(false); xstart = 0; // just to prevent an error } else { for (int i : xstartField) components[i].setEnabled(true); } // check if both xstart and ystart are within proper ranges if (areaPerPoint != 0 && (xstart >= tileWidth || ystart >= tileHeight)) { if (xstart >= tileWidth) err += "\"xstart\" "; if (ystart >= tileHeight) err += "\"ystart\" "; err += "too large. \n"; } // input for the Combined grid if (type.equals(types[COMBINED]) || type.equals(types[DOUBLE_LATTICE])) { for (int i : combinedGridFields) components[i].setEnabled(true); // check if both xstartCoarse and ystartCoarse are within proper ranges if (xstartCoarse >= coarseGridX || ystartCoarse >= coarseGridY) { if (xstartCoarse >= coarseGridX) err += "\"xstartCoarse\" "; if (ystartCoarse >= coarseGridY) err += "\"ystartCoarse\" "; err += "too large."; } } else { for (int i : combinedGridFields) components[i].setEnabled(false); } } if (!"".equals(err)) { IJ.showStatus(err); return true; } // calculating number of vertical and horizontal lines in a selected image linesV = (int) ((width - xstart) / tileWidth) + 1; linesH = (int) ((height - ystart) / tileHeight) + 1; // execution part if (gd.invalidNumber()) return true; if (type.equals(types[LINES])) drawLines(); else if (type.equals(types[HLINES])) drawHorizontalLines(); else if (type.equals(types[CROSSES])) drawCrosses(); else if (type.equals(types[POINTS])) drawPoints(); else if (type.equals(types[COMBINED])) drawCombined(); else if (type.equals(types[DOUBLE_LATTICE])) drawDoubleLattice(); else showGrid(null); return true; } Color getColor() { Color c = Color.black; if (color.equals(colors[0])) c = Color.red; else if (color.equals(colors[1])) c = Color.green; else if (color.equals(colors[2])) c = Color.blue; else if (color.equals(colors[3])) c = Color.magenta; else if (color.equals(colors[4])) c = Color.cyan; else if (color.equals(colors[5])) c = Color.yellow; else if (color.equals(colors[6])) c = Color.orange; else if (color.equals(colors[7])) c = Color.black; else if (color.equals(colors[8])) c = Color.white; return c; } // output grid parameters void showParameterList() { Integer xStartOutput = new Integer(xstart); Integer xStartCoarseOutput = new Integer(xstartCoarse); Integer yStartCoarseOutput = new Integer(ystartCoarse); String singleQuart = "'"; if (type.equals(types[HLINES])) xStartOutput = null; if (!(type.equals(types[COMBINED]) || type.equals(types[DOUBLE_LATTICE]))) { xStartCoarseOutput = null; yStartCoarseOutput = null; singleQuart = ""; gridRatio = null; } DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = new Date(); String GridParameters = df.format(date) + "\t" + imp.getTitle() + "\t" + type + "\t" + areaPerPoint + "\t" + units + "^2" + "\t" + singleQuart + gridRatio + "\t" + color + "\t" + radiochoice + "\t" + xStartOutput + "\t" + ystart + "\t" + xStartCoarseOutput + "\t" + yStartCoarseOutput; // singleQuart before gridRatio is to prevent conversion to date in // Excel. TextWindow gridParameterWindow = (TextWindow) WindowManager.getWindow("Grid Parameters"); if (gridParameterWindow == null) { //make a new empty TextWindow titled "Grid Parameters" with headings gridParameterWindow = new TextWindow( "Grid Parameters", "Date \t Image \t Grid Type \t Area per Point \t Unit \t Ratio \t Color \t Location Setting \t xstart \t ystart \t xstartCoarse \t ystartCoarse", "", 1028, 250); //If "Grid Parameters.txt" exists in the plugin folder, read it into the "Grid Parameters" window try { BufferedReader br = new BufferedReader(new FileReader(IJ.getDirectory("plugins") + "Grid Parameters.txt")); int count = -1; while (true) { count++; String s = br.readLine(); if (s == null) break; if(count == 0) continue; gridParameterWindow.append(s); } } catch (IOException e) {} } gridParameterWindow.append(GridParameters); //auto save the parameters into "Grid Parameters.txt" TextPanel tp = gridParameterWindow.getTextPanel(); tp.saveAs(IJ.getDirectory("plugins") + "Grid Parameters.txt"); } boolean gridSwitchExist(){ Frame[] frames = Frame.getFrames(); for (Frame frame : frames){ if("Grid Switch".equals(frame.getTitle()) && frame.isVisible()) return true; } return false; } }
package ca.phon.csv2phon; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.logging.Level; import java.util.logging.Logger; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import au.com.bytecode.opencsv.CSVReader; import ca.phon.csv2phon.io.ColumnMapType; import ca.phon.csv2phon.io.FileType; import ca.phon.csv2phon.io.ImportDescriptionType; import ca.phon.csv2phon.io.ParticipantType; import ca.phon.extensions.UnvalidatedValue; import ca.phon.fontconverter.TranscriptConverter; import ca.phon.ipa.IPATranscript; import ca.phon.ipa.IPATranscriptBuilder; import ca.phon.ipa.alignment.PhoneAligner; import ca.phon.ipa.alignment.PhoneMap; import ca.phon.orthography.Orthography; import ca.phon.project.Project; import ca.phon.session.Group; import ca.phon.session.MediaSegment; import ca.phon.session.MediaSegmentFormatter; import ca.phon.session.MediaUnit; import ca.phon.session.Participant; import ca.phon.session.ParticipantRole; import ca.phon.session.Record; import ca.phon.session.Session; import ca.phon.session.SessionFactory; import ca.phon.session.SystemTierType; import ca.phon.session.Tier; import ca.phon.session.TierDescription; import ca.phon.session.TierViewItem; import ca.phon.syllabifier.Syllabifier; import ca.phon.syllabifier.SyllabifierLibrary; import ca.phon.util.Language; import ca.phon.util.OSInfo; /** * Reads in the XML description of a CSV import and performs the import. * * */ public class CSVImporter { private final static Logger LOGGER = Logger .getLogger(CSVImporter.class.getName()); /** The import description */ private ImportDescriptionType importDescription; /** The project we are importing into */ private Project project; /** Directory where files are located */ private String base; private String fileEncoding = "UTF-8"; private char textDelimChar = '"'; private char fieldDelimChar = ','; /** * Constructor. */ public CSVImporter(String baseDir, ImportDescriptionType importDesc, Project project) { super(); this.importDescription = importDesc; this.project = project; this.base = baseDir; } public void setFileEncoding(String charset) { this.fileEncoding = charset; } public String getFileEncoding() { return this.fileEncoding; } public char getTextDelimChar() { return textDelimChar; } public void setTextDelimChar(char textDelimChar) { this.textDelimChar = textDelimChar; } public char getFieldDelimChar() { return fieldDelimChar; } public void setFieldDelimChar(char fieldDelimChar) { this.fieldDelimChar = fieldDelimChar; } /** * Begin import of specified files. */ public void performImport() { // print some info messages LOGGER.info("Importing files from directory '" + base + '"'); for(FileType ft:importDescription.getFile()) { if(ft.isImport()) { try { LOGGER.info("Importing file '.../" + ft.getLocation() + "'"); importFile(ft); } catch (IOException e) { LOGGER.log(Level.SEVERE, e.getLocalizedMessage(), e); } } } LOGGER.info("Import finished."); } public void importFile(FileType fileInfo) throws IOException { // first try relative path from base // String base = importDescription.getBase(); String location = fileInfo.getLocation(); // check if location is an absolute path boolean absolute = false; if(OSInfo.isWindows()) { if(location.matches("[A-Z]:\\\\.*")) absolute = true; } else { if(location.startsWith("/")) absolute = true; } File csvFile = null; if(absolute) csvFile = new File(location); else csvFile = new File(base, location); if(!csvFile.exists()) { // throw an exception throw new FileNotFoundException("'" + csvFile.getAbsolutePath() + "' not found, check the 'base' attribute of the csvimport element."); } final InputStreamReader csvInputReader = new InputStreamReader(new FileInputStream(csvFile), fileEncoding); // read in csv file final CSVReader reader = new CSVReader(csvInputReader, fieldDelimChar, textDelimChar); // create a new transcript in the project // with the specified corpus and session name final String corpus = importDescription.getCorpus(); final String session = fileInfo.getSession(); if(!project.getCorpora().contains(corpus)) { LOGGER.info("Creating corpus '" + corpus + "'"); project.addCorpus(corpus, ""); } final SessionFactory factory = SessionFactory.newFactory(); final Session t = project.createSessionFromTemplate(corpus, session); if(t.getRecordCount() > 0) t.removeRecord(0); if(fileInfo.getDate() != null) { final DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("yyyy-MM-dd"); DateTime sessionDate = dateFormatter.parseDateTime(fileInfo.getDate()); t.setDate(sessionDate); } // add participants for(ParticipantType pt:importDescription.getParticipant()) { Participant newPart = CSVParticipantUtil.copyXmlParticipant(factory, pt, t.getDate()); t.addParticipant(newPart); } if(fileInfo.getMedia() != null) { t.setMediaLocation(fileInfo.getMedia()); } // set media file and date String[] colLine = reader.readNext(); // create deptier descriptions as necessary for(String columnName:colLine) { ColumnMapType colmap = getColumnMap(columnName); if(colmap != null) { String tierName = colmap.getPhontier(); if(tierName.equalsIgnoreCase("Don't import")) continue; if(!SystemTierType.isSystemTier(tierName) && !tierName.equalsIgnoreCase("Speaker:Name")) { final TierDescription tierDesc = factory.createTierDescription(tierName, colmap.isGrouped(), String.class); t.addUserTier(tierDesc); final TierViewItem tvi = factory.createTierViewItem(tierName); final List<TierViewItem> tierView = new ArrayList<>(t.getTierView()); tierView.add(tvi); t.setTierView(tierView); } } } int createdParticipant = 0; String[] currentRow = null; while((currentRow = reader.readNext()) != null) { // add a new record to the transcript Record utt = factory.createRecord(); t.addRecord(utt); for(int colIdx = 0; colIdx < colLine.length; colIdx++) { String csvcol = colLine[colIdx]; String rowval = currentRow[colIdx]; ColumnMapType colmap = getColumnMap(csvcol); if(colmap == null) { // print warning and continue LOGGER.warning("No column map for csv column '" + csvcol + "'"); continue; } // convert if necessary TranscriptConverter tc = null; if(colmap.getFilter() != null && colmap.getFilter().length() > 0) { tc = TranscriptConverter.getInstanceOf(colmap.getFilter()); if(tc == null) { LOGGER.warning("Could not find transcript converter '" + colmap.getFilter() + "'"); } } String phontier = colmap.getPhontier().trim(); if(phontier.equalsIgnoreCase("Don't Import")) { continue; } // do data pre-formatting if required if(colmap.getScript() != null) { // TODO: create a new javascript context and run the given script } // handle participant tier if(phontier.equals("Speaker:Name")) { // look for the participant in the transcript Participant speaker = null; for(Participant p:t.getParticipants()) { if(p.toString().equals(rowval)) { speaker = p; break; } } // if not found in the transcript, find the // participant info in the import description // add add the participant if(speaker == null) { speaker = factory.createParticipant(); speaker.setName(rowval); speaker.setRole(ParticipantRole.PARTICIPANT); String id = "PA" + (createdParticipant > 0 ? createdParticipant : "R"); ++createdParticipant; speaker.setId(id); t.addParticipant(speaker); } utt.setSpeaker(speaker); } else { if(colmap.isGrouped() == null) colmap.setGrouped(true); // convert rowval into a list of group values List<String> rowVals = new ArrayList<String>(); if(colmap.isGrouped() && rowval.startsWith("[") && rowval.endsWith("]")) { String[] splitRow = rowval.split("\\["); for(int i = 1; i < splitRow.length; i++) { String splitVal = splitRow[i]; splitVal = splitVal.replaceAll("\\]", ""); rowVals.add(splitVal); } } else { rowVals.add(rowval); } final SystemTierType systemTier = SystemTierType.tierFromString(phontier); if(systemTier != null) { if(systemTier == SystemTierType.Orthography) { final Tier<Orthography> orthoTier = utt.getOrthography(); for(String grpVal:rowVals) { try { final Orthography ortho = Orthography.parseOrthography(grpVal); orthoTier.addGroup(ortho); } catch (ParseException e) { final Orthography ortho = new Orthography(); final UnvalidatedValue uv = new UnvalidatedValue(grpVal, e); ortho.putExtension(UnvalidatedValue.class, uv); orthoTier.addGroup(ortho); } } } else if(systemTier == SystemTierType.IPATarget || systemTier == SystemTierType.IPAActual) { final Tier<IPATranscript> ipaTier = (systemTier == SystemTierType.IPATarget ? utt.getIPATarget() : utt.getIPAActual()); for(String grpVal:rowVals) { if(tc != null) { grpVal = tc.convert(grpVal); } grpVal = grpVal.trim(); final IPATranscript ipa = (new IPATranscriptBuilder()).append(grpVal).toIPATranscript(); ipaTier.addGroup(ipa); } } else if(systemTier == SystemTierType.Notes) { utt.getNotes().addGroup(rowval); } else if(systemTier == SystemTierType.Segment) { final MediaSegmentFormatter segmentFormatter = new MediaSegmentFormatter(); MediaSegment segment = factory.createMediaSegment(); segment.setStartValue(0.0f); segment.setEndValue(0.0f); segment.setUnitType(MediaUnit.Millisecond); try { segment = segmentFormatter.parse(rowval); } catch (ParseException e) { LOGGER.log(Level.SEVERE, e.getLocalizedMessage(), e); } utt.getSegment().addGroup(segment); } } else { Tier<String> tier = utt.getTier(phontier, String.class); if(tier == null) { tier = factory.createTier(phontier, String.class, colmap.isGrouped()); utt.putTier(tier); } if(tier.isGrouped()) { for(String grpVal:rowVals) { tier.addGroup(grpVal); } } else { tier.setGroup(0, rowval); } } } } // end for(colIdx) // do syllabification + alignment if necessary ColumnMapType targetMapping = getPhonColumnMap(SystemTierType.IPATarget.getName()); ColumnMapType actualMapping = getPhonColumnMap(SystemTierType.IPAActual.getName()); if(targetMapping != null && actualMapping != null) { final SyllabifierLibrary library = SyllabifierLibrary.getInstance(); String targetLangName = targetMapping.getSyllabifier(); if(targetLangName == null) { targetLangName = SyllabifierLibrary.getInstance().defaultSyllabifierLanguage().toString(); } final Language targetLang = Language.parseLanguage(targetLangName); String actualLangName = targetMapping.getSyllabifier(); if(actualLangName == null) { actualLangName = SyllabifierLibrary.getInstance().defaultSyllabifierLanguage().toString(); } final Language actualLang = Language.parseLanguage(actualLangName); final PhoneAligner aligner = new PhoneAligner(); Syllabifier targetSyllabifier = library.getSyllabifierForLanguage(targetLang); Syllabifier actualSyllabifier = library.getSyllabifierForLanguage(actualLang); for(int i = 0; i < utt.numberOfGroups(); i++) { final Group grp = utt.getGroup(i); final IPATranscript targetRep = grp.getIPATarget(); if(targetSyllabifier != null) { targetSyllabifier.syllabify(targetRep.toList()); } final IPATranscript actualRep = grp.getIPAActual(); if(actualSyllabifier != null) { actualSyllabifier.syllabify(actualRep.toList()); } PhoneMap pm = aligner.calculatePhoneMap(targetRep, actualRep); grp.setPhoneAlignment(pm); } } } // end while(currentRow) reader.close(); // save transcript final UUID writeLock = project.getSessionWriteLock(t); if(writeLock != null) { project.saveSession(t, writeLock); project.releaseSessionWriteLock(t, writeLock); } } /** * Returns the column mapping for the given csvcolumn. */ private ColumnMapType getColumnMap(String csvcol) { ColumnMapType retVal = null; for(ColumnMapType cmt:importDescription.getColumnmap()) { if(cmt.getCsvcolumn().equals(csvcol)) { retVal = cmt; break; } } return retVal; } /** * Returns the column mapping for the given phon column. */ private ColumnMapType getPhonColumnMap(String phoncol) { ColumnMapType retVal = null; for(ColumnMapType cmt:importDescription.getColumnmap()) { if(cmt.getPhontier().equals(phoncol)) { retVal = cmt; break; } } return retVal; } /** * Returns the participant with the given name */ private ParticipantType getParticipant(String partName) { ParticipantType retVal = null; for(ParticipantType part:importDescription.getParticipant()) { if(part.getName().equals(partName)) { retVal = part; break; } } return retVal; } }
package com.bloatit.framework; import java.math.BigDecimal; import java.util.Date; import java.util.Locale; import com.bloatit.common.PageIterable; import com.bloatit.framework.lists.CommentList; import com.bloatit.framework.lists.ContributionList; import com.bloatit.framework.lists.OfferList; import com.bloatit.model.data.DaoComment; import com.bloatit.model.data.DaoDemand; import com.bloatit.model.data.DaoDescription; import com.bloatit.model.data.DaoKudosable; import com.bloatit.model.data.util.SessionManager; public class Demand extends Kudosable { private final DaoDemand dao; public static Demand create(DaoDemand dao) { if (dao == null || !SessionManager.getSessionFactory().getCurrentSession().contains(dao)) { return null; } return new Demand(dao); } public Demand(Member member, Locale locale, String title, String description) { dao = DaoDemand.createAndPersist(member.getDao(), new DaoDescription(member.getDao(), locale, title, description)); } private Demand(DaoDemand dao) { super(); this.dao = dao; } public void addComment(String text) { dao.addComment(DaoComment.createAndPersist(getToken().getMember().getDao(), text)); } public void addContribution(BigDecimal amount) throws Throwable { dao.addContribution(getToken().getMember().getDao(), amount); } public Offer addOffer(Description description, Date dateExpir) { return new Offer(dao.addOffer(getToken().getMember().getDao(), description.getDao(), dateExpir)); } public void createSpecification(String content) { dao.createSpecification(getToken().getMember().getDao(), content); } public PageIterable<Comment> getComments() { return new CommentList(dao.getCommentsFromQuery()); } public PageIterable<Contribution> getContributions() { return new ContributionList(dao.getContributionsFromQuery()); } public DaoDemand getDao() { return dao; } public BigDecimal getContribution(){ return dao.getContribution(); } @Override protected DaoKudosable getDaoKudosable() { return dao; } public Description getDescription() { return new Description(dao.getDescription()); } public PageIterable<Offer> getOffers() { return new OfferList(dao.getOffersFromQuery()); } public int getPopularity() { return dao.getPopularity(); } public Specification getSpecification() { return new Specification(dao.getSpecification()); } public String getTitle() { return getDescription().getDefaultTranslation().getTitle(); } // TODO right management public void removeOffer(Offer offer) { dao.removeOffer(offer.getDao()); } }
package com.browserstack.local; import java.io.*; import java.util.ArrayList; import java.util.HashMap; import java.util.Arrays; import java.util.List; import java.util.Map; import org.json.*; /** * Creates and manages a secure tunnel connection to BrowserStack. */ public class Local { List<String> command; Map<String, String> startOptions; String binaryPath; String logFilePath; int pid = 0; private LocalProcess proc = null; private final Map<String, String> parameters; public Local() { parameters = new HashMap<String, String>(); parameters.put("v", "-vvv"); parameters.put("f", "-f"); parameters.put("force", "-force"); parameters.put("only", "-only"); parameters.put("forcelocal", "-forcelocal"); parameters.put("localIdentifier", "-localIdentifier"); parameters.put("onlyAutomate", "-onlyAutomate"); parameters.put("proxyHost", "-proxyHost"); parameters.put("proxyPort", "-proxyPort"); parameters.put("proxyUser", "-proxyUser"); parameters.put("proxyPass", "-proxyPass"); parameters.put("forceproxy", "-forceproxy"); parameters.put("hosts", "-hosts"); } /** * Starts Local instance with options * * @param options Options for the Local instance * @throws Exception */ public void start(Map<String, String> options) throws Exception { startOptions = options; if (options.get("binarypath") != null) { binaryPath = options.get("binarypath"); } else { LocalBinary lb = new LocalBinary(); binaryPath = lb.getBinaryPath(); } logFilePath = options.get("logfile") == null ? (System.getProperty("user.dir") + "/local.log") : options.get("logfile"); makeCommand(options, "start"); if (options.get("onlyCommand") != null) return; if (proc == null) { FileWriter fw = new FileWriter(logFilePath); fw.write(""); fw.close(); proc = runCommand(command); BufferedReader stdoutbr = new BufferedReader(new InputStreamReader(proc.getInputStream())); BufferedReader stderrbr = new BufferedReader(new InputStreamReader(proc.getErrorStream())); String stdout="", stderr="", line; while ((line = stdoutbr.readLine()) != null) { stdout += line; } while ((line = stderrbr.readLine()) != null) { stderr += line; } int r = proc.waitFor(); JSONObject obj = new JSONObject(stdout != "" ? stdout : stderr); if(!obj.getString("state").equals("connected")){ throw new LocalException(obj.getString("message")); } else { pid = obj.getInt("pid"); } } } /** * Stops the Local instance * * @throws InterruptedException */ public void stop() throws Exception { if (pid != 0) { makeCommand(startOptions, "stop"); proc = runCommand(command); proc.waitFor(); pid = 0; } } /** * Checks if Local instance is running * * @return true if Local instance is running, else false */ public boolean isRunning() throws Exception { if (pid == 0) return false; return isProcessRunning(pid); } /** * Creates a list of command-line arguments for the Local instance * * @param options Options supplied for the Local instance */ private void makeCommand(Map<String, String> options, String opCode) { command = new ArrayList<String>(); command.add(binaryPath); command.add("-d"); command.add(opCode); command.add("-logFile"); command.add(logFilePath); command.add(options.get("key")); for (Map.Entry<String, String> opt : options.entrySet()) { List<String> ignoreKeys = Arrays.asList("key", "logfile", "binarypath"); String parameter = opt.getKey().trim(); if (ignoreKeys.contains(parameter)) { continue; } if (parameters.get(parameter) != null) { command.add(parameters.get(parameter)); } else { command.add("-" + parameter); } if (opt.getValue() != null) { command.add(opt.getValue().trim()); } } } private boolean isProcessRunning(int pid) throws Exception { ArrayList<String> cmd = new ArrayList<String>(); if (System.getProperty("os.name").toLowerCase().contains("windows")) { //tasklist exit code is always 0. Parse output //findstr exit code 0 if found pid, 1 if it doesn't cmd.add("cmd"); cmd.add("/c"); cmd.add("\"tasklist /FI \"PID eq " + pid + "\" | findstr " + pid + "\""); } else { //ps exit code 0 if process exists, 1 if it doesn't cmd.add("ps"); cmd.add("-p"); cmd.add(String.valueOf(pid)); } proc = runCommand(cmd); int exitValue = proc.waitFor(); // 0 is the default exit code which means the process exists return exitValue == 0; } /** * Executes the supplied command on the shell. * * @param command Command to be executed on the shell. * @return {@link LocalProcess} for managing the launched process. * @throws IOException */ protected LocalProcess runCommand(List<String> command) throws IOException { ProcessBuilder processBuilder = new ProcessBuilder(command); final Process process = processBuilder.start(); return new LocalProcess() { public InputStream getInputStream() { return process.getInputStream(); } public InputStream getErrorStream() { return process.getErrorStream(); } public int waitFor() throws Exception { return process.waitFor(); } }; } public interface LocalProcess { InputStream getInputStream(); InputStream getErrorStream(); int waitFor() throws Exception; } }
package com.cognodyne.dw.cdi; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.Set; import java.util.regex.Pattern; import javax.enterprise.context.spi.CreationalContext; import javax.enterprise.inject.spi.Bean; import javax.enterprise.inject.spi.BeanManager; import javax.enterprise.inject.spi.CDI; import com.google.common.collect.Sets; public class CdiUtil { public static BeanManager getBeanManager() { return CDI.current().getBeanManager(); } public static boolean isAnnotationPresent(Bean<?> bean, Class<? extends Annotation> annotationClass) { return isAnnotationPresent(bean.getTypes(), annotationClass); } public static boolean isAnnotationPresent(Set<Type> types, Class<? extends Annotation> annotationClass) { for (Type type : types) { Class<?> typeClass = type.getClass(); if (type instanceof Class) { typeClass = (Class<?>) type; } else if (type instanceof ParameterizedType) { ParameterizedType ptype = (ParameterizedType) type; typeClass = (Class<?>) ptype.getRawType(); } if (typeClass.isAnnotationPresent(annotationClass)) { return true; } } return false; } public static <T extends Annotation> T getAnnotation(Bean<?> bean, Class<T> annotationClass) { return getAnnotation(bean.getTypes(), annotationClass); } public static <T extends Annotation> T getAnnotation(Set<Type> types, Class<T> annotationClass) { for (Type type : types) { Class<?> typeClass = type.getClass(); if (type instanceof Class) { typeClass = (Class<?>) type; } else if (type instanceof ParameterizedType) { ParameterizedType ptype = (ParameterizedType) type; typeClass = (Class<?>) ptype.getRawType(); } if (typeClass.isAnnotationPresent(annotationClass)) { return typeClass.getAnnotation(annotationClass); } } return null; } public static Set<Method> getMethods(Bean<?> bean, String methodNameRegEx, Set<Class<? extends Annotation>> annotationClasses) { Pattern pattern = Pattern.compile(methodNameRegEx); Set<Method> result = Sets.newHashSet(); for (Type type : bean.getTypes()) { Class<?> typeClass = type.getClass(); if (type instanceof Class) { typeClass = (Class<?>) type; } else if (type instanceof ParameterizedType) { ParameterizedType ptype = (ParameterizedType) type; typeClass = (Class<?>) ptype.getRawType(); } for (Method method : typeClass.getDeclaredMethods()) { if (pattern.matcher(method.getName()).matches()) { for (Class<? extends Annotation> anno : annotationClasses) { if (method.isAnnotationPresent(anno)) { result.add(method); } } } } } return result; } @SuppressWarnings("unchecked") public static <T> T getReference(Class<? extends T> cls, Annotation... qualifiers) { Set<Bean<?>> beans = getBeanManager().getBeans(cls, qualifiers); if (beans == null || beans.isEmpty()) { return null; } return getReference((Bean<T>) beans.iterator().next()); } public static <T> T getReference(Bean<T> bean) { return getReference(getBeanManager(), bean); } @SuppressWarnings("unchecked") public static <T> T getReference(BeanManager bm, Bean<T> bean) { CreationalContext<T> ctx = bm.createCreationalContext(bean); return (T) bm.getReference(bean, bean.getBeanClass(), ctx); } public static <T> T create(Bean<T> bean) { return create(getBeanManager(), bean); } public static <T> T create(BeanManager bm, Bean<T> bean) { CreationalContext<T> ctx = bm.createCreationalContext(bean); return bean.create(ctx); } public static <T> void destroy(Bean<T> bean) { destroy(getBeanManager(), bean); } public static <T> void destroy(BeanManager bm, Bean<T> bean) { bean.destroy(getReference(bm, bean), bm.createCreationalContext(bean)); } }
package com.expression.parser; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.expression.parser.exception.CalculatorException; import com.expression.parser.function.Complex; import com.expression.parser.function.ComplexFunction; import com.expression.parser.function.FunctionX; import com.expression.parser.function.FunctionXs; import com.expression.parser.util.ParserResult; import com.expression.parser.util.Point; /** * The Class Parser. */ public class Parser { /** * Eval * * This is a parser eval. The real parser of a function is within the Fuction * * FunctionX: functions with one var. Example 1+2*x --> it is more optimized * * FunctionXs: functions with several vars. Example: 1+2*x+3*y... * * ComplexFunction: Complex functions with several vars: one var or n vars. Example: 1+x+y +j * * @param function the function: 1+2*x+j... * @param values the values x=10, y=20 * * @return the parser result: complex or real value */ public static ParserResult eval(final String function, final Point... values) { final ParserResult result = new ParserResult(); FunctionX f_x = null; FunctionXs f_xs = null; ComplexFunction complexFunction = null; if ((function != null) && !function.isEmpty()) { if (Parser.pointIsComplex(values) || function.toLowerCase().contains("j")) { // Complex complexFunction = new ComplexFunction(function); final List<Complex> valuesList = pointToComplexValue(values); final List<String> varsList = pointToVar(values); try { result.setComplexValue(complexFunction.getValue(valuesList, varsList)); } catch (final CalculatorException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { try { if (values != null) { if (values.length == 1) { f_x = new FunctionX(function); if ((values[0].getStringValue() != null && !values[0].getStringValue().isEmpty())) { final ParserResult evaluatedValue = Parser.eval(values[0].getStringValue()); result.setValue(f_x.getF_xo(evaluatedValue.getValue())); } else { result.setValue(f_x.getF_xo(values[0].getValue())); } } else if (values.length > 1) { f_xs = new FunctionXs(function); final List<Double> valuesList = pointToValue(values); final List<String> varsList = pointToVar(values); result.setValue(f_xs.getValue(valuesList, varsList)); } } else { f_x = new FunctionX(function); result.setValue(f_x.getF_xo(0)); } } catch (final CalculatorException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return result; } /** * Eval. * * @param function the function * @param vars the vars * @param values the values * @return the double */ public static double eval(final String function, final String[] vars, final Double[] values) { double result = 0; FunctionX f_x = null; FunctionXs f_xs = null; if ((function != null) && !function.equals("")) { try { if ((((vars == null) || (vars.length < 1)) && (values == null)) || (values.length < 1)) { f_x = new FunctionX(function); result = f_x.getF_xo(0); } else if ((values != null) && (values.length == 1)) { f_x = new FunctionX(function); result = f_x.getF_xo(values[0]); } else if ((vars != null) && (vars.length > 1) && (values != null) && (values.length > 1)) { f_xs = new FunctionXs(function); final List<Double> valuesList = Arrays.asList(values); final List<String> varsList = Arrays.asList(vars); result = f_xs.getValue(valuesList, varsList); } } catch (final CalculatorException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return result; } /** * Eval. * * @param function the function * @return the parser result */ public static ParserResult eval(final String function) { ParserResult result = new ParserResult(); FunctionX f_x = null; if ((function != null) && !function.equals("")) { try { if ((function.toLowerCase().contains("j") || function.toLowerCase().contains("i")) && !function.toLowerCase().contains("x")) { result = eval(function, new Point("x", new Complex(1, 0))); } else if (!function.toLowerCase().contains("x")) { f_x = new FunctionX(function); result.setValue(f_x.getF_xo(0)); } else { throw new CalculatorException("function is not well defined"); } } catch (final CalculatorException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return result; } /** * PointToValue. * * @param values the values * @return the list */ private static List<Double> pointToValue(final Point... values) { final List<Double> result = new ArrayList<Double>(); for (int i = 0; i < values.length; i++) { if ((values[i].getStringValue() != null && !values[i].getStringValue().isEmpty())) { final ParserResult evaluatedValue = Parser.eval(values[i].getStringValue()); result.add(evaluatedValue.getValue()); } else { result.add(values[i].getValue()); } } return result; } /** * PointToComplexValue. * * @param values the values * @return the list */ private static List<Complex> pointToComplexValue(final Point... values) { final List<Complex> result = new ArrayList<Complex>(); for (int i = 0; i < values.length; i++) { if (values[i].isComplex() && (values[i].getStringValue() == null || values[i].getStringValue().isEmpty())) { result.add(values[i].getComplexValue()); } else if ((values[i].getStringValue() != null && !values[i].getStringValue().isEmpty())) { final ParserResult evaluatedValue = Parser.eval(values[i].getStringValue()); if (evaluatedValue.isComplex()) { result.add(evaluatedValue.getComplexValue()); } else { result.add(new Complex(evaluatedValue.getValue(), 0)); } } else { result.add(new Complex(values[i].getValue(), 0)); } } return result; } /** * pointIsComplex. * * @param values the values * @return true, if successful */ private static boolean pointIsComplex(final Point... values) { boolean result = false; for (int i = 0; i < values.length; i++) { if (values[i].isComplex() && (values[i].getStringValue() == null || values[i].getStringValue().isEmpty())) { result = true; break; } else { if (values[i].getStringValue() != null && !values[i].getStringValue().isEmpty()) { final ParserResult evaluatedValue = Parser.eval(values[i].getStringValue()); if (evaluatedValue.isComplex()) { result = true; break; } } } } return result; } /** * PointToVar. * * @param values the values * @return the list */ private static List<String> pointToVar(final Point... values) { final List<String> result = new ArrayList<String>(); for (int i = 0; i < values.length; i++) { result.add(values[i].getVar()); } return result; } }
package com.fishercoder.solutions; import com.fishercoder.common.classes.ListNode; public class _2 { public static class Solution1 { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode result = new ListNode(0); ListNode tmp = result; int sum = 0; while (l1 != null || l2 != null) { sum /= 10; if (l1 != null) { sum += l1.val; l1 = l1.next; } if (l2 != null) { sum += l2.val; l2 = l2.next; } tmp.next = new ListNode(sum % 10); tmp = tmp.next; } if (sum / 10 == 1) { tmp.next = new ListNode(1);//this means there's a carry, so we add additional 1, e.g. [5] + [5] = [0, 1] } return result.val == 0 ? result.next : result; } } }
package com.googlecode.objectify; import com.google.appengine.api.datastore.KeyFactory; import com.googlecode.objectify.annotation.Entity; import com.googlecode.objectify.impl.TypeUtils; import java.io.Serializable; /** * <p>A typesafe wrapper for the datastore Key object.</p> * * @author Jeff Schnitzer <jeff@infohazard.org> * @author Scott Hernandez */ public class Key<T> implements Serializable, Comparable<Key<?>> { private static final long serialVersionUID = 2L; /** Key.create(key) is easier to type than new Key<Blah>(key) */ public static <T> Key<T> create(com.google.appengine.api.datastore.Key raw) { if (raw == null) throw new NullPointerException("Cannot create a Key<?> from a null datastore Key"); return new Key<>(raw); } /** Key.create(Blah.class, id) is easier to type than new Key<Blah>(Blah.class, id) */ public static <T> Key<T> create(Class<? extends T> kindClass, long id) { return new Key<>(kindClass, id); } /** Key.create(Blah.class, name) is easier to type than new Key<Blah>(Blah.class, name) */ public static <T> Key<T> create(Class<? extends T> kindClass, String name) { return new Key<>(kindClass, name); } /** Key.create(parent, Blah.class, id) is easier to type than new Key<Blah>(parent, Blah.class, id) */ public static <T> Key<T> create(Key<?> parent, Class<? extends T> kindClass, long id) { return new Key<>(parent, kindClass, id); } /** Key.create(parent, Blah.class, name) is easier to type than new Key<Blah>(parent, Blah.class, name) */ public static <T> Key<T> create(Key<?> parent, Class<? extends T> kindClass, String name) { return new Key<>(parent, kindClass, name); } /** Key.create(webSafeString) is easier to type than new Key<Blah>(webSafeString) */ public static <T> Key<T> create(String webSafeString) { if (webSafeString == null) throw new NullPointerException("Cannot create a Key<?> from a null String"); return new Key<>(webSafeString); } /** This is an alias for Key.create(String) which exists for JAX-RS compliance. */ public static <T> Key<T> valueOf(String webSafeString) { return Key.create(webSafeString); } /** Create a key from a registered POJO entity. */ public static <T> Key<T> create(T pojo) { return ObjectifyService.factory().keys().keyOf(pojo); } protected com.google.appengine.api.datastore.Key raw; /** Cache the instance of the parent wrapper to avoid unnecessary garbage */ transient protected Key<?> parent; /** For GWT serialization */ private Key() {} /** Wrap a raw Key */ private Key(com.google.appengine.api.datastore.Key raw) { this.raw = raw; } /** Create a key with a long id */ private Key(Class<? extends T> kindClass, long id) { this(null, kindClass, id); } /** Create a key with a String name */ private Key(Class<? extends T> kindClass, String name) { this(null, kindClass, name); } /** Create a key with a parent and a long id */ private Key(Key<?> parent, Class<? extends T> kindClass, long id) { this.raw = KeyFactory.createKey(key(parent), getKind(kindClass), id); this.parent = parent; } /** Create a key with a parent and a String name */ private Key(Key<?> parent, Class<? extends T> kindClass, String name) { this.raw = KeyFactory.createKey(key(parent), getKind(kindClass), name); this.parent = parent; } /** * Reconstitute a Key from a web safe string. This can be generated with getString()/toWebSafeString() * or KeyFactory.stringToKey(). */ private Key(String webSafe) { this(KeyFactory.stringToKey(webSafe)); } /** * @return the raw datastore version of this key */ public com.google.appengine.api.datastore.Key getRaw() { return this.raw; } /** * @return the id associated with this key, or 0 if this key has a name. */ public long getId() { return this.raw.getId(); } /** * @return the name associated with this key, or null if this key has an id */ public String getName() { return this.raw.getName(); } /** * @return the low-level datastore kind associated with this Key */ public String getKind() { return this.raw.getKind(); } /** * @return the parent key, or null if there is no parent. Note that * the parent could potentially have any type. */ @SuppressWarnings("unchecked") public <V> Key<V> getParent() { if (this.parent == null && this.raw.getParent() != null) this.parent = new Key<V>(this.raw.getParent()); return (Key<V>)this.parent; } /** * Gets the root of a parent graph of keys. If a Key has no parent, it is the root. * * @return the topmost parent key, or this object itself if it is the root. * Note that the root key could potentially have any type. */ @SuppressWarnings("unchecked") public <V> Key<V> getRoot() { if (this.getParent() == null) return (Key<V>)this; else return this.getParent().getRoot(); } /** * <p>Compares based on comparison of the raw key</p> */ @Override public int compareTo(Key<?> other) { return this.raw.compareTo(other.raw); } @Override public boolean equals(Object obj) { if (obj == null) return false; if (!(obj instanceof Key<?>)) return false; return this.compareTo((Key<?>)obj) == 0; } /** A type-safe equivalence comparison */ public boolean equivalent(Key<T> other) { return equals(other); } /** A type-safe equivalence comparison */ public boolean equivalent(Ref<T> other) { return (other != null) && equals(other.key()); } @Override public int hashCode() { return this.raw.hashCode(); } /** Creates a human-readable version of this key */ @Override public String toString() { return "Key<?>(" + this.raw + ")"; } /** * Call KeyFactory.keyToString() on the underlying Key. You can reconstitute a Key<?> using the * constructor that takes a websafe string. This is a javabeans-style alias for toWebSafeString(). */ public String getString() { return toWebSafeString(); } /** * Call KeyFactory.keyToString() on the underlying Key. You can reconstitute a Key<?> using the * constructor that takes a websafe string. Note that toString() is only useful for debugging; * it cannot be used to create a key with Key.create(String). */ public String toWebSafeString() { return KeyFactory.keyToString(this.raw); } /** * Easy null-safe conversion of the raw key. */ public static <V> Key<V> key(com.google.appengine.api.datastore.Key raw) { if (raw == null) return null; else return new Key<>(raw); } /** * Easy null-safe conversion of the typed key. */ public static com.google.appengine.api.datastore.Key key(Key<?> typed) { if (typed == null) return null; else return typed.getRaw(); } public static String getKind(Class<?> clazz) { String kind = getKindRecursive(clazz); if (kind == null) throw new IllegalArgumentException("Class hierarchy for " + clazz + " has no @Entity annotation"); else return kind; } /** * <p>Recursively looks for the @Entity annotation.</p> * * @return null if kind cannot be found */ private static String getKindRecursive(Class<?> clazz) { if (clazz == Object.class) return null; String kind = getKindHere(clazz); if (kind != null) return kind; else return getKindRecursive(clazz.getSuperclass()); } /** * Get the kind from the class if the class has an @Entity annotation, otherwise return null. */ private static String getKindHere(Class<?> clazz) { // @Entity is inherited so we have to be explicit about the declared annotations Entity ourAnn = TypeUtils.getDeclaredAnnotation(clazz, Entity.class); if (ourAnn != null) if (ourAnn.name() != null && ourAnn.name().length() != 0) return ourAnn.name(); else return clazz.getSimpleName(); return null; } }
package com.jaamsim.input; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; 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 java.util.Locale; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.filechooser.FileNameExtensionFilter; import com.jaamsim.basicsim.Entity; import com.jaamsim.basicsim.ErrorException; import com.jaamsim.basicsim.Group; import com.jaamsim.basicsim.ObjectType; import com.jaamsim.math.Vec3d; import com.jaamsim.ui.ExceptionBox; import com.jaamsim.ui.FrameBox; import com.jaamsim.ui.LogBox; import com.sandwell.JavaSimulation.FileEntity; import com.sandwell.JavaSimulation.Simulation; 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; } 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 > 3) { InputAgent.logBadInput(tokens, "Maximum brace depth (3) 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.logError("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.logError("Could not read from %s", url.toString()); return false; } try { ArrayList<String> record = new ArrayList<>(); int braceDepth = 0; ParseContext pc = new ParseContext(resolved, root); 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( "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()); } } public static <T extends Entity> T generateEntityWithName(Class<T> proto, String key) { if (key != null && !isValidName(key)) { InputAgent.logError("Entity names cannot contain spaces, tabs, { or }: %s", key); return null; } T ent = null; try { ent = proto.newInstance(); ent.setFlag(Entity.FLAG_GENERATED); if (key != null) ent.setName(key); else ent.setName(proto.getSimpleName() + "-" + ent.getEntityNumber()); } catch (InstantiationException e) {} catch (IllegalAccessException e) {} finally { if (ent == null) { InputAgent.logError("Could not create new Entity: %s", key); return null; } } return ent; } /** * Like defineEntity(), but will generate a unique name if a name collision exists * @param proto * @param key * @param sep * @param addedEntity * @return */ public static <T extends Entity> T defineEntityWithUniqueName(Class<T> proto, String key, String sep, 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%s%d", key, sep, entityNum); if (Entity.getNamedEntity(name) == null) { return defineEntity(proto, name, addedEntity); } entityNum++; } } private static boolean isValidName(String key) { for (int i = 0; i < key.length(); ++i) { final char c = key.charAt(i); if (c == ' ' || c == '\t' || c == '{' || c == '}') return false; } return true; } /** * 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 */ private 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; } if (!isValidName(key)) { InputAgent.logError("Entity names cannot contain spaces, tabs, { or }: %s", key); 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.setName(key); return ent; } public static void processKeywordRecord(ArrayList<String> record, 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.getName(), keyword.keyword, e.getMessage()); } } } private static ArrayList<KeywordIndex> getKeywords(ArrayList<String> input, ParseContext context) { ArrayList<KeywordIndex> ret = new ArrayList<>(); int braceDepth = 0; int keyWordIdx = 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) { // validate keyword form String keyword = input.get(keyWordIdx); if (keyword.equals("{") || keyword.equals("}") || !input.get(keyWordIdx + 1).equals("{")) throw new InputErrorException("The input for a keyword must be enclosed by braces. Should be <keyword> { <args> }"); ret.add(new KeywordIndex(input, keyword, keyWordIdx + 2, i, context)); keyWordIdx = i + 1; continue; } } } if (keyWordIdx != input.size()) throw new InputErrorException("The input for a keyword must be enclosed by braces. Should be <keyword> { <args> }"); 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.logError("Keyword %s could not be found for Entity %s.", kw.keyword, ent.getName()); return; } InputAgent.apply(ent, in, kw); FrameBox.valueUpdate(); } public static final void apply(Entity ent, Input<?> in, KeywordIndex kw) { // If the input value is blank, restore the default if (kw.numArgs() == 0) { in.reset(); } else { in.parse(kw); in.setTokens(kw); } // Only mark the keyword edited if we have finished initial configuration if (InputAgent.recordEdits()) { in.setEdited(true); ent.setFlag(Entity.FLAG_EDITED); if (!ent.testFlag(Entity.FLAG_GENERATED)) sessionEdited = true; } ent.updateForInput(in); } public 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); } } 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); chooser.setSelectedFile(InputAgent.getConfigFile()); // 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, String.format("The file '%s' already exists.\n" + "Do you want to replace it?", file.getName()), "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 ) { InputAgent.doError(t); InputAgent.showErrorDialog("Fatal Error", "A fatal error has occured while loading the file '%s':\n\n%s", file.getName(), t.getMessage()); GUIFrame.shutdown(1); } } /** * 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(); 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.getName(); if ((count - 1) % 5 == 0) { inputReportFile.putString("Define"); inputReportFile.putTab(); inputReportFile.putString(type.getName()); 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.getName().compareTo(b.getName()); } }); // 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.getName(); 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; boolean beginLine = true; for (int i = 0; i < tokens.size(); i++) { if (!beginLine) logFile.write(" "); String tok = tokens.get(i); logFile.write(tok); beginLine = false; if (tok.startsWith("\"")) { logFile.newLine(); beginLine = true; } } // If there were any leftover string written out, make sure the line gets terminated if (!beginLine) 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); 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 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<>(); // Value if (!value.equals(Input.getNoValue())) Parser.tokenize(tokens, value, true); // Parse the keyword inputs KeywordIndex kw = new KeywordIndex(tokens, keyword, 0, tokens.size(), 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 ) { // 1) WRITE LINES FROM THE ORIGINAL CONFIGURATION FILE // 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<>(); 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); } // 2) WRITE THE DEFINITION STATEMENTS FOR NEW OBJECTS // Determine all the new classes that were created ArrayList<Class<? extends Entity>> newClasses = new ArrayList<>(); for (Entity ent : Entity.getAll()) { if (!ent.testFlag(Entity.FLAG_ADDED) || ent.testFlag(Entity.FLAG_GENERATED)) 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.getName()); break; } } // Print the new instances that were defined for (Entity ent : Entity.getAll()) { if (!ent.testFlag(Entity.FLAG_ADDED) || ent.testFlag(Entity.FLAG_GENERATED)) continue; if (ent.getClass() == newClass) file.format(" %s ", ent.getName()); } // Close the define statement file.format("}%n"); } // 3) WRITE THE ATTRIBUTE DEFINITIONS boolean blankLinePrinted = false; for (Entity ent : Entity.getAll()) { if (!ent.testFlag(Entity.FLAG_EDITED)) continue; if (ent.testFlag(Entity.FLAG_GENERATED)) continue; final Input<?> in = ent.getInput("AttributeDefinitionList"); if (in == null || !in.isEdited()) continue; if (!blankLinePrinted) { file.format("%n"); blankLinePrinted = true; } writeInputOnFile_ForEntity(file, ent, in); } // 4) WRITE THE INPUTS FOR KEYWORDS THAT WERE EDITED // Identify the entities whose inputs were edited for (Entity ent : Entity.getAll()) { if (!ent.testFlag(Entity.FLAG_EDITED)) continue; if (ent.testFlag(Entity.FLAG_GENERATED)) continue; file.format("%n"); ArrayList<Input<?>> deferredInputs = new ArrayList<>(); // Print the key inputs first for (Input<?> in : ent.getEditableInputs()) { if (!in.isEdited()) continue; if ("AttributeDefinitionList".equals(in.getKeyword())) continue; // defer all inputs outside the Key Inputs category if (!"Key Inputs".equals(in.getCategory())) { deferredInputs.add(in); continue; } writeInputOnFile_ForEntity(file, ent, in); } for (Input<?> in : deferredInputs) { writeInputOnFile_ForEntity(file, ent, in); } } // Close the new configuration file file.flush(); file.close(); } static void writeInputOnFile_ForEntity(FileEntity file, Entity ent, Input<?> in) { file.format("%s %s { %s }%n", ent.getName(), in.getKeyword(), in.getValueString()); } /** * 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; } public static KeywordIndex formatPointsInputs(String keyword, ArrayList<Vec3d> points, Vec3d offset) { ArrayList<String> tokens = new ArrayList<>(points.size() * 6); for (Vec3d v : points) { tokens.add("{"); tokens.add(String.format((Locale)null, "%.3f", v.x + offset.x)); tokens.add(String.format((Locale)null, "%.3f", v.y + offset.y)); tokens.add(String.format((Locale)null, "%.3f", v.z + offset.z)); tokens.add("m"); tokens.add("}"); } // Parse the keyword inputs return new KeywordIndex(tokens, keyword, 0, tokens.size(), null); } public static KeywordIndex formatPointInputs(String keyword, Vec3d point, String unit) { ArrayList<String> tokens = new ArrayList<>(4); tokens.add(String.format((Locale)null, "%.6f", point.x)); tokens.add(String.format((Locale)null, "%.6f", point.y)); tokens.add(String.format((Locale)null, "%.6f", point.z)); if (unit != null) tokens.add(unit); // Parse the keyword inputs return new KeywordIndex(tokens, keyword, 0, tokens.size(), null); } /** * 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<>(); int braceDepth = 0; ArrayList<String> currentLine = null; for (int i = 0; i < input.size(); i++) { if (currentLine == null) currentLine = new ArrayList<>(); 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; } /** * 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; } } public static void showErrorDialog(String title, String fmt, Object... args) { final String msg = String.format(fmt, args); JOptionPane.showMessageDialog(null, msg, title, JOptionPane.ERROR_MESSAGE); } }
/** WebUtil.java */ package com.lhjz.portal.util; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.authentication.AbstractAuthenticationToken; import org.springframework.security.authentication.RememberMeAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.web.context.request.RequestAttributes; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import com.lhjz.portal.constant.SysConstant; import com.lhjz.portal.model.RespBody; /** * @author XiWeiCheng * */ public final class WebUtil { private static Logger logger = LoggerFactory.getLogger(WebUtil.class); private WebUtil() { super(); } /** * json. * * @param response * @param respBody */ public static void writeResult(HttpServletResponse response, RespBody respBody) { PrintWriter pw = null; try { response.setContentType("text/html;charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); pw = response.getWriter(); pw.write(JsonUtil.toJson(respBody)); } catch (IOException e) { e.printStackTrace(); } finally { if (pw != null) { pw.flush(); pw.close(); } } } /** * json. * * @param response * @param resultMsg */ public static void writeObject(HttpServletResponse response, Object resultMsg) { PrintWriter pw = null; try { response.setContentType("text/html;charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); pw = response.getWriter(); pw.write(JsonUtil.toJson(resultMsg)); } catch (IOException e) { e.printStackTrace(); } finally { if (pw != null) { pw.flush(); pw.close(); } } } /** * j. * * @param response * @param object */ public static void writeString(HttpServletResponse response, Object object) { PrintWriter pw = null; try { response.setContentType("text/html;charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); pw = response.getWriter(); pw.write(String.valueOf(object)); } catch (IOException e) { e.printStackTrace(); } finally { if (pw != null) { pw.flush(); pw.close(); } } } /** * . * * @param request * @return */ public static Map<String, String[]> parseParams( HttpServletRequest request) { Map<String, String[]> map = new HashMap<String, String[]>(); Enumeration<?> params = request.getParameterNames(); StringBuffer paramSb = null; StringBuffer emptyParamSb = null; if (logger.isDebugEnabled()) { paramSb = new StringBuffer(); emptyParamSb = new StringBuffer(); paramSb.append("<<[request params]>>"); paramSb.append(SysConstant.NEW_LINE); } while (params.hasMoreElements()) { String name = params.nextElement().toString(); String[] value = request.getParameterValues(name); map.put(name, value); if (logger.isDebugEnabled()) { String values = StringUtil.join(SysConstant.COMMA, value); if (StringUtil.isEmpty(values)) { emptyParamSb.append(name + "=" + values); emptyParamSb.append(SysConstant.NEW_LINE); } else { paramSb.append(name + "=" + values); paramSb.append(SysConstant.NEW_LINE); } } } if (logger.isDebugEnabled()) { if (emptyParamSb.length() > 0) { paramSb.append(" paramSb.append(SysConstant.NEW_LINE); paramSb.append(emptyParamSb); } if (paramSb.length() > 0) { paramSb.delete(paramSb.length() - SysConstant.NEW_LINE.length(), paramSb.length()); } logger.debug(paramSb.toString()); } return map; } /** * . * * @param request * @return */ public static StringBuffer joinParams(HttpServletRequest request) { Enumeration<?> params = request.getParameterNames(); StringBuffer paramSb = new StringBuffer(); StringBuffer emptyParamSb = new StringBuffer(); while (params.hasMoreElements()) { String name = params.nextElement().toString(); String[] value = request.getParameterValues(name); String values = StringUtil.join(SysConstant.COMMA, value); if (StringUtil.isEmpty(values)) { emptyParamSb.append(name + "=" + values); emptyParamSb.append(SysConstant.NEW_LINE); } else { paramSb.append(name + "=" + values); paramSb.append(SysConstant.NEW_LINE); } } if (emptyParamSb.length() > 0) { paramSb.append(" paramSb.append(SysConstant.NEW_LINE); paramSb.append(emptyParamSb); } if (paramSb.length() > 0) { paramSb.delete(paramSb.length() - SysConstant.NEW_LINE.length(), paramSb.length()); } return paramSb; } /** * URL * * @author xiweicheng * @creation 20131230 12:39:45 * @modification 20131230 12:39:45 * @param baseUrl * @param path * @return */ public static String JoinUrls(String baseUrl, String... paths) { String url = baseUrl; for (String path : paths) { url = JoinUrl(url, path); } logger.debug(url); return url == null ? SysConstant.EMPTY : url; } /** * URL * * @author xiweicheng * @creation 20131230 12:39:45 * @modification 20131230 12:39:45 * @param baseUrl * @param path * @return */ public static String JoinUrl(String baseUrl, String path) { if (baseUrl == null) { return path == null ? SysConstant.EMPTY : path; } if (path == null) { return baseUrl == null ? SysConstant.EMPTY : baseUrl; } if (baseUrl.endsWith("/") && path.startsWith("/")) { return baseUrl + path.substring(1); } else if (!baseUrl.endsWith("/") && !path.startsWith("/")) { return baseUrl + "/" + path; } else { return baseUrl + path; } } /** * Request. * * @author xiweicheng * @creation 201412 4:42:29 * @modification 201412 4:42:29 * @return */ public static HttpServletRequest getRequest() { RequestAttributes requestAttributes = RequestContextHolder .getRequestAttributes(); if (requestAttributes != null) { return ((ServletRequestAttributes) requestAttributes).getRequest(); } return null; } /** * Session. * * @author xiweicheng * @creation 201412 4:42:41 * @modification 201412 4:42:41 * @return */ public static HttpSession getSession() { HttpServletRequest request = getRequest(); return request == null ? null : request.getSession(); } /** * Session. * * @author xiweicheng * @creation 201412 4:47:18 * @modification 201412 4:47:18 * @return */ // public static User getSessionUser() { // HttpSession session = getSession(); // Object object = (session == null ? null : // session.getAttribute(SysConstant.SESSION_USER)); // // if (object instanceof User) { // // return (User) object; // return null; /** * SessionId. * * @author xiweicheng * @creation 2014113 3:00:49 * @modification 2014113 3:00:49 * @return */ // public static String getSessionUserId() { // User user = getSessionUser(); // return user == null ? null : String.valueOf(user.getUserid()); /** * session id. * * @author xiweicheng * @creation 201412 4:48:29 * @modification 201412 4:48:29 * @return */ public static String getSessionId() { HttpSession session = getSession(); return session == null ? null : session.getId(); } public static String calcServerBaseUrl(HttpServletRequest request) { logger.debug("[]base url."); String serverBaseUrl = null; String cxtPath = request.getContextPath(); if (StringUtil.isEmpty(cxtPath)) { serverBaseUrl = StringUtil.replace("{?1}: request.getScheme(), request.getServerName(), request.getServerPort()); } else { if (cxtPath.startsWith("/")) { cxtPath = cxtPath.substring(1); } if (cxtPath.endsWith("/")) { cxtPath = cxtPath.substring(0, cxtPath.length() - 1); } serverBaseUrl = StringUtil.replace("{?1}://{?2}:{?3}/{?4}", request.getScheme(), request.getServerName(), request.getServerPort(), cxtPath); } logger.debug(serverBaseUrl); return serverBaseUrl; } /** * servlet context * * @author xiweicheng * @creation 2014329 4:25:29 * @modification 2014329 4:25:29 * @param request * @return */ public static String getRealPath(HttpServletRequest request) { String realPath = request.getSession().getServletContext() .getRealPath("/").replace("\\", "/"); if (!realPath.endsWith("/")) { return realPath + "/"; } logger.debug("servlet context real path: {}", realPath); return realPath; } /** * * * @return */ public static String getUsername() { try { Object principal = SecurityContextHolder.getContext() .getAuthentication().getPrincipal(); if (principal instanceof UserDetails) { return ((UserDetails) principal).getUsername(); } else { return principal.toString(); } } catch (Exception e) { logger.warn(" {}", e.getMessage()); return StringUtil.EMPTY; } } /** * * * @return */ public static void setUsername(String username) { try { AbstractAuthenticationToken authenticationToken = new AbstractAuthenticationToken(null) { private static final long serialVersionUID = 1033003540219681089L; @Override public Object getPrincipal() { return username; } @Override public Object getCredentials() { return null; } }; authenticationToken.setAuthenticated(true); SecurityContextHolder.getContext().setAuthentication(authenticationToken); } catch (Exception e) { } } /** * . * @return */ public static boolean isLogin() { String username = getUsername(); return StringUtil.isNotEmpty(username) && !"anonymousUser".equals(username); } /** * * * @return */ public static UserDetails getUserDetails() { try { Object principal = SecurityContextHolder.getContext() .getAuthentication().getPrincipal(); if (principal instanceof UserDetails) { return ((UserDetails) principal); } else { logger.warn(" {}", principal.toString()); return null; } } catch (Exception e) { logger.warn(" {}", e.getMessage()); return null; } } /** * * * @return */ public static List<String> getUserAuthorities() { List<String> aus = new ArrayList<>(); try { UserDetails userDetails = WebUtil.getUserDetails(); Collection<? extends GrantedAuthority> authorities = userDetails .getAuthorities(); authorities.forEach((au) -> { aus.add(au.getAuthority()); }); } catch (Exception e) { logger.warn(" {}", e.getMessage()); } return aus; } /** * remember me cookie . * * @return */ public static boolean isRememberMeAuthenticated() { Authentication authentication = SecurityContextHolder.getContext() .getAuthentication(); if (authentication == null) { return false; } return RememberMeAuthenticationToken.class .isAssignableFrom(authentication.getClass()); } public static String getIpAddr(final HttpServletRequest request) { String ip = request.getHeader("x-forwarded-for"); if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } // unknownip final String[] arr = ip.split(","); for (final String str : arr) { if (!"unknown".equalsIgnoreCase(str)) { ip = str; break; } } return ip; } }
package com.moebiusgames.xdata; import com.moebiusgames.xdata.marshaller.DateMarshaller; import com.moebiusgames.xdata.marshaller.URLMarshaller; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; /** * Main class for storing and loading xdata files * <p/> * Sample: * <pre> * final static DataKey&lt;String&gt; MY_KEY = DataKey.create("mykey", String.class); * //... * DataNode node = new DataNode(); * node.setObject(MY_KEY, "hello world"); * XData.store(node, new File("somefile.xdata")); * //... * DataNode restoredNode = XData.load(new File("somefile.xdata")); * //do sth with the data in the node e.g. * System.out.println(node.getObject(MY_KEY)); * </pre> * @author Florian Frankenberger */ public class XData { private static final DummyProgressListener DUMMY_PROGRESS_LISTENER = new DummyProgressListener(); private static final byte[] XDATA_HEADER = new byte[] {'x', 'd', 'a', 't', 'a'}; private static final DataKey<String> META_CLASS_NAME = DataKey.create("_meta_classname", String.class); private static final Map<Class<?>, Serializer<?>> PRIMITIVE_SERIALIZERS_BY_CLASS = new HashMap<Class<?>, Serializer<?>>(); private static final Map<Byte, Serializer<?>> PRIMITIVE_SERIALIZERS_BY_ID = new HashMap<Byte, Serializer<?>>(); private static final List<DataMarshaller<?>> DEFAULT_MARSHALLERS = new ArrayList<DataMarshaller<?>>(); private static final int VAL_NULL = 0; private static final int VAL_ELEMENT = 1; private static final int VAL_LIST = 2; private static final int VAL_NODE = 3; static { //default marshallers DEFAULT_MARSHALLERS.add(new DateMarshaller()); DEFAULT_MARSHALLERS.add(new URLMarshaller()); //primitive serializers final IntSerializer intSerializer = new IntSerializer(); PRIMITIVE_SERIALIZERS_BY_CLASS.put(Integer.class, intSerializer); PRIMITIVE_SERIALIZERS_BY_CLASS.put(int.class, intSerializer); final LongSerializer longSerializer = new LongSerializer(); PRIMITIVE_SERIALIZERS_BY_CLASS.put(Long.class, longSerializer); PRIMITIVE_SERIALIZERS_BY_CLASS.put(long.class, longSerializer); final ShortSerializer shortSerializer = new ShortSerializer(); PRIMITIVE_SERIALIZERS_BY_CLASS.put(Short.class, shortSerializer); PRIMITIVE_SERIALIZERS_BY_CLASS.put(short.class, shortSerializer); final ByteSerializer byteSerializer = new ByteSerializer(); PRIMITIVE_SERIALIZERS_BY_CLASS.put(Byte.class, byteSerializer); PRIMITIVE_SERIALIZERS_BY_CLASS.put(byte.class, byteSerializer); final CharSerializer charSerializer = new CharSerializer(); PRIMITIVE_SERIALIZERS_BY_CLASS.put(Character.class, charSerializer); PRIMITIVE_SERIALIZERS_BY_CLASS.put(char.class, charSerializer); final FloatSerializer floatSerializer = new FloatSerializer(); PRIMITIVE_SERIALIZERS_BY_CLASS.put(Float.class, floatSerializer); PRIMITIVE_SERIALIZERS_BY_CLASS.put(float.class, floatSerializer); final DoubleSerializer doubleSerializer = new DoubleSerializer(); PRIMITIVE_SERIALIZERS_BY_CLASS.put(Double.class, doubleSerializer); PRIMITIVE_SERIALIZERS_BY_CLASS.put(double.class, doubleSerializer); final BooleanSerializer booleanSerializer = new BooleanSerializer(); PRIMITIVE_SERIALIZERS_BY_CLASS.put(Boolean.class, booleanSerializer); PRIMITIVE_SERIALIZERS_BY_CLASS.put(boolean.class, booleanSerializer); final StringSerializer stringSerializer = new StringSerializer(); PRIMITIVE_SERIALIZERS_BY_CLASS.put(String.class, stringSerializer); for (Serializer<?> serializer : PRIMITIVE_SERIALIZERS_BY_CLASS.values()) { PRIMITIVE_SERIALIZERS_BY_ID.put(serializer.getSerializerId(), serializer); } } private static interface Serializer<T> { byte getSerializerId(); Class<T> getClazz(); void serialize(T object, DataOutputStream dOut) throws IOException; T deserialize(DataInputStream dIn) throws IOException; } private XData() { } /** * loads a xdata file from disk using the given marshallers. For all classes other * than these a special marshaller is required to map the class' data to a data node * object: * <ul> * <li>Boolean</li> * <li>Long</li> * <li>Integer</li> * <li>String</li> * <li>Float</li> * <li>Double</li> * <li>Byte</li> * <li>Short</li> * <li>Character</li> * <li>DataNode</li> * <li>List&lt;?&gt;</li> * </ul> * <p/> * Also take a look at {@link com.moebiusgames.xdata.marshaller}. There are a bunch of * standard marshallers that ARE INCLUDED by default. So you don't need to add them here * to work. * * @param file * @param marshallers * @return * @throws IOException */ public static DataNode load(File file, DataMarshaller<?>... marshallers) throws IOException { return load(file, DUMMY_PROGRESS_LISTENER, marshallers); } /** * loads a xdata file from disk using the given marshallers. For all classes other * than these a special marshaller is required to map the class' data to a data node * object: * <ul> * <li>Boolean</li> * <li>Long</li> * <li>Integer</li> * <li>String</li> * <li>Float</li> * <li>Double</li> * <li>Byte</li> * <li>Short</li> * <li>Character</li> * <li>DataNode</li> * <li>List&lt;?&gt;</li> * </ul> * <p/> * Also take a look at {@link com.moebiusgames.xdata.marshaller}. There are a bunch of * standard marshallers that ARE INCLUDED by default. So you don't need to add them here * to work. * * @param file * @param ignoreMissingMarshallers if this is set true then no IOException is thrown * when a marshaller is missing. * @param marshallers * @return * @throws IOException */ public static DataNode load(File file, boolean ignoreMissingMarshallers, DataMarshaller<?>... marshallers) throws IOException { return load(file, DUMMY_PROGRESS_LISTENER, ignoreMissingMarshallers, marshallers); } /** * loads a xdata file from disk using the given marshallers. For all classes other * than these a special marshaller is required to map the class' data to a data node * object: * <ul> * <li>Boolean</li> * <li>Long</li> * <li>Integer</li> * <li>String</li> * <li>Float</li> * <li>Double</li> * <li>Byte</li> * <li>Short</li> * <li>Character</li> * <li>DataNode</li> * <li>List&lt;?&gt;</li> * </ul> * <p/> * Also take a look at {@link com.moebiusgames.xdata.marshaller}. There are a bunch of * standard marshallers that ARE INCLUDED by default. So you don't need to add them here * to work. * * @param file * @param progressListener * @param marshallers * @return * @throws IOException */ public static DataNode load(File file, ProgressListener progressListener, DataMarshaller<?>... marshallers) throws IOException { return load(file, progressListener, false, marshallers); } /** * loads a xdata file from disk using the given marshallers. For all classes other * than these a special marshaller is required to map the class' data to a data node * object: * <ul> * <li>Boolean</li> * <li>Long</li> * <li>Integer</li> * <li>String</li> * <li>Float</li> * <li>Double</li> * <li>Byte</li> * <li>Short</li> * <li>Character</li> * <li>DataNode</li> * <li>List&lt;?&gt;</li> * </ul> * <p/> * Also take a look at {@link com.moebiusgames.xdata.marshaller}. There are a bunch of * standard marshallers that ARE INCLUDED by default. So you don't need to add them here * to work. * * @param file * @param progressListener * @param ignoreMissingMarshallers if this is set true then no IOException is thrown * when a marshaller is missing. * @param marshallers * @return * @throws IOException */ public static DataNode load(File file, ProgressListener progressListener, boolean ignoreMissingMarshallers, DataMarshaller<?>... marshallers) throws IOException { return load(new FileInputStream(file), progressListener, ignoreMissingMarshallers, marshallers); } /** * loads a xdata file from from an inputstream using the given marshallers. For all classes other * than these a special marshaller is required to map the class' data to a data node * object: * <ul> * <li>Boolean</li> * <li>Long</li> * <li>Integer</li> * <li>String</li> * <li>Float</li> * <li>Double</li> * <li>Byte</li> * <li>Short</li> * <li>Character</li> * <li>DataNode</li> * <li>List&lt;?&gt;</li> * </ul> * <p/> * Also take a look at {@link com.moebiusgames.xdata.marshaller}. There are a bunch of * standard marshallers that ARE INCLUDED by default. So you don't need to add them here * to work. * * @param in * @param marshallers * @return * @throws IOException */ public static DataNode load(InputStream in, DataMarshaller<?>... marshallers) throws IOException { return load(in, DUMMY_PROGRESS_LISTENER, marshallers); } /** * loads a xdata file from from an inputstream using the given marshallers. For all classes other * than these a special marshaller is required to map the class' data to a data node * object: * <ul> * <li>Boolean</li> * <li>Long</li> * <li>Integer</li> * <li>String</li> * <li>Float</li> * <li>Double</li> * <li>Byte</li> * <li>Short</li> * <li>Character</li> * <li>DataNode</li> * <li>List&lt;?&gt;</li> * </ul> * <p/> * Also take a look at {@link com.moebiusgames.xdata.marshaller}. There are a bunch of * standard marshallers that ARE INCLUDED by default. So you don't need to add them here * to work. * * @param in * @param ignoreMissingMarshallers if this is set true then no IOException is thrown * when a marshaller is missing. * @param marshallers * @return * @throws IOException */ public static DataNode load(InputStream in, boolean ignoreMissingMarshallers, DataMarshaller<?>... marshallers) throws IOException { return load(in, DUMMY_PROGRESS_LISTENER, ignoreMissingMarshallers, marshallers); } /** * loads a xdata file from from an inputstream using the given marshallers. For all classes other * than these a special marshaller is required to map the class' data to a data node * object: * <ul> * <li>Boolean</li> * <li>Long</li> * <li>Integer</li> * <li>String</li> * <li>Float</li> * <li>Double</li> * <li>Byte</li> * <li>Short</li> * <li>Character</li> * <li>DataNode</li> * <li>List&lt;?&gt;</li> * </ul> * <p/> * Also take a look at {@link com.moebiusgames.xdata.marshaller}. There are a bunch of * standard marshallers that ARE INCLUDED by default. So you don't need to add them here * to work. * * @param in * @param progressListener * @param marshallers * @return * @throws IOException */ public static DataNode load(InputStream in, ProgressListener progressListener, DataMarshaller<?>... marshallers) throws IOException { return load(in, progressListener, false, marshallers); } /** * loads a xdata file from an inputstream using the given marshallers. For all classes other * than these a special marshaller is required to map the class' data to a data node * object: * <ul> * <li>Boolean</li> * <li>Long</li> * <li>Integer</li> * <li>String</li> * <li>Float</li> * <li>Double</li> * <li>Byte</li> * <li>Short</li> * <li>Character</li> * <li>DataNode</li> * <li>List&lt;?&gt;</li> * </ul> * <p/> * Also take a look at {@link com.moebiusgames.xdata.marshaller}. There are a bunch of * standard marshallers that ARE INCLUDED by default. So you don't need to add them here * to work. * * @param in * @param progressListener * @param ignoreMissingMarshallers if this is set true then no IOException is thrown * when a marshaller is missing. * @param marshallers * @return * @throws IOException */ public static DataNode load(InputStream in, ProgressListener progressListener, boolean ignoreMissingMarshallers, DataMarshaller<?>... marshallers) throws IOException { final Map<String, DataMarshaller<?>> marshallerMap = generateMarshallerMap(false, Arrays.asList(marshallers)); marshallerMap.putAll(generateMarshallerMap(false, DEFAULT_MARSHALLERS)); DataInputStream dIn = new DataInputStream(new GZIPInputStream(in)); try { //check the header for (int i = 0; i < XDATA_HEADER.length; ++i) { if (dIn.readByte() != XDATA_HEADER[i]) { throw new IOException("not a xdata file"); } } final Object raw = deSerialize(dIn, progressListener); if (!(raw instanceof DataNode)) { throw new IOException("first object in xdata file MUST be a DataNode but was " + raw == null ? "null" : raw.getClass().getCanonicalName()); } final DataNode dataNode = (DataNode) raw; final Object rawUnMarshalled = unMarshal(marshallerMap, ignoreMissingMarshallers, dataNode); if (!(rawUnMarshalled instanceof DataNode)) { throw new IOException("first object in xdata file MUST be a DataNode but was " + rawUnMarshalled == null ? "null" : rawUnMarshalled.getClass().getCanonicalName()); } return (DataNode) rawUnMarshalled; } finally { dIn.close(); } } private static Object deSerialize(DataInputStream dIn, ProgressListener progressListener) throws IOException { final int type = dIn.readByte(); switch(type) { case VAL_NULL: return null; case VAL_ELEMENT: final byte elementType = dIn.readByte(); final Serializer<Object> serializer = (Serializer<Object>)PRIMITIVE_SERIALIZERS_BY_ID.get(elementType); if (serializer == null) { throw new IOException("can't deserialize type " + Integer.toHexString(elementType) + " (maybe newer format?)."); } return serializer.deserialize(dIn); case VAL_LIST: final int listSize = dIn.readInt(); //because of type erasure we just create a list //of objects here ... final List<Object> list = new ArrayList<Object>(); for (int i = 0; i < listSize; ++i) { final Object object = deSerialize(dIn, DUMMY_PROGRESS_LISTENER); list.add(object); } return list; case VAL_NODE: final DataNode dataNode = new DataNode(); int length = dIn.readInt(); progressListener.onTotalSteps(length); for (int i = 0; i < length; ++i) { final String key = dIn.readUTF(); final Object object = deSerialize(dIn, DUMMY_PROGRESS_LISTENER); dataNode.replaceObject(key, object); progressListener.onStep(); } return dataNode; default: throw new IOException("expected node (" + Integer.toHexString(type) + ") but found " + Integer.toHexString(type)); } } private static Object unMarshal(Map<String, DataMarshaller<?>> marshallerMap, boolean ignoreMissingMarshallers, DataNode node) throws IOException { final Map<String, Object> replacements = new HashMap<String, Object>(); for (Entry<String, Object> entry : node.getAll()) { final String key = entry.getKey(); final Object object = entry.getValue(); if (object != null) { if (object instanceof DataNode) { replacements.put(key, unMarshal(marshallerMap, ignoreMissingMarshallers, (DataNode) object)); } else if (object instanceof List) { final List<Object> list = (List<Object>) object; unMarshalList(list, marshallerMap, ignoreMissingMarshallers); } } } for (Entry<String, Object> entry : replacements.entrySet()) { node.replaceObject(entry.getKey(), entry.getValue()); } if (node.containsKey(META_CLASS_NAME)) { final String className = node.getObject(META_CLASS_NAME); final DataMarshaller<Object> marshaller = (DataMarshaller<Object>) marshallerMap.get(className); if (marshaller == null) { if (!ignoreMissingMarshallers) { throw new IOException("no marshaller found for class " + className); } else { return node; } } return marshaller.unMarshal(node); } else { return node; } } private static void unMarshalList(final List<Object> list, Map<String, DataMarshaller<?>> marshallerMap, boolean ignoreMissingMarshallers) throws IOException { for (int i = 0; i < list.size(); ++i) { final Object aObject = list.get(i); if (aObject != null) { if (aObject instanceof DataNode) { list.set(i, unMarshal(marshallerMap, ignoreMissingMarshallers, (DataNode) aObject)); } else if (aObject instanceof List) { final List<Object> aList = (List<Object>) aObject; unMarshalList(aList, marshallerMap, ignoreMissingMarshallers); } } } } /** * stores a datanode in a xdata file using the given marshallers. For all classes other * than these a special marshaller is required to map the class' data to a data node * object: * <ul> * <li>Boolean</li> * <li>Long</li> * <li>Integer</li> * <li>String</li> * <li>Float</li> * <li>Double</li> * <li>Byte</li> * <li>Short</li> * <li>Character</li> * <li>DataNode</li> * <li>List&lt;?&gt;</li> * </ul> * <p/> * Also take a look at {@link com.moebiusgames.xdata.marshaller}. There are a bunch of * standard marshallers that ARE INCLUDED by default. So you don't need to add them here * to work. * * @param node * @param file * @param marshallers * @throws IOException */ public static void store(DataNode node, File file, DataMarshaller<?>... marshallers) throws IOException { store(node, file, DUMMY_PROGRESS_LISTENER, marshallers); } /** * stores a datanode in a xdata file using the given marshallers. For all classes other * than these a special marshaller is required to map the class' data to a data node * object: * <ul> * <li>Boolean</li> * <li>Long</li> * <li>Integer</li> * <li>String</li> * <li>Float</li> * <li>Double</li> * <li>Byte</li> * <li>Short</li> * <li>Character</li> * <li>DataNode</li> * <li>List&lt;?&gt;</li> * </ul> * <p/> * Also take a look at {@link com.moebiusgames.xdata.marshaller}. There are a bunch of * standard marshallers that ARE INCLUDED by default. So you don't need to add them here * to work. * * @param node * @param file * @param progressListener * @param marshallers * @throws IOException */ public static void store(DataNode node, File file, ProgressListener progressListener, DataMarshaller<?>... marshallers) throws IOException { store(node, new FileOutputStream(file), progressListener, marshallers); } /** * stores a datanode in a xdata file using the given marshallers. For all classes other * than these a special marshaller is required to map the class' data to a data node * object: * <ul> * <li>Boolean</li> * <li>Long</li> * <li>Integer</li> * <li>String</li> * <li>Float</li> * <li>Double</li> * <li>Byte</li> * <li>Short</li> * <li>Character</li> * <li>DataNode</li> * <li>List&lt;?&gt;</li> * </ul> * <p/> * Also take a look at {@link com.moebiusgames.xdata.marshaller}. There are a bunch of * standard marshallers that ARE INCLUDED by default. So you don't need to add them here * to work. * * @param node * @param out * @param marshallers * @throws IOException */ public static void store(DataNode node, OutputStream out, DataMarshaller<?>... marshallers) throws IOException { store(node, out, DUMMY_PROGRESS_LISTENER, marshallers); } /** * stores a datanode in a xdata file using the given marshallers. For all classes other * than these a special marshaller is required to map the class' data to a data node * object: * <ul> * <li>Boolean</li> * <li>Long</li> * <li>Integer</li> * <li>String</li> * <li>Float</li> * <li>Double</li> * <li>Byte</li> * <li>Short</li> * <li>Character</li> * <li>DataNode</li> * <li>List&lt;?&gt;</li> * </ul> * <p/> * Also take a look at {@link com.moebiusgames.xdata.marshaller}. There are a bunch of * standard marshallers that ARE INCLUDED by default. So you don't need to add them here * to work. * * @param node * @param out * @param progressListener * @param marshallers * @throws IOException */ public static void store(DataNode node, OutputStream out, ProgressListener progressListener, DataMarshaller<?>... marshallers) throws IOException { final Map<String, DataMarshaller<?>> marshallerMap = generateMarshallerMap(true, Arrays.asList(marshallers)); marshallerMap.putAll(generateMarshallerMap(true, DEFAULT_MARSHALLERS)); DataOutputStream dOut = new DataOutputStream(new GZIPOutputStream(out)); try { //write header dOut.write(XDATA_HEADER); //serialize the node serialize(marshallerMap, dOut, node, progressListener); } finally { dOut.close(); } } /** * wraps an object using the data marshaller for that given object or returns * a the object when it is already a DataNode, a primitive, array or string. * * @param marshallerMap * @param object * @return */ private static Object marshalObject(Map<String, DataMarshaller<?>> marshallerMap, Object object) { if (!isMarshalled(object)) { //can't be null here because it is not resolved: meaning, it is an instance of an unknown class final Class<?> clazz = object.getClass(); if (object instanceof List) { final List<Object> list = (List<Object>) object; final List<Object> newList = new ArrayList<Object>(list.size()); for (int i = 0; i < list.size(); ++i) { final Object aObject = list.get(i); newList.add(marshalObject(marshallerMap, aObject)); } return newList; } else { final DataMarshaller<Object> serializer = (DataMarshaller<Object>) marshallerMap.get(clazz.getCanonicalName()); if (serializer == null) { throw new IllegalStateException("No serializer defined for class " + clazz.getCanonicalName()); } final DataNode node = serializer.marshal(object); node.setObject(META_CLASS_NAME, serializer.getDataClassName()); return node; } } return object; } /** * serializes a data node that just contains primitives or references to other data * nodes. * * @param dataNode */ private static void serialize(Map<String, DataMarshaller<?>> marshallerMap, DataOutputStream dOut, DataNode dataNode, ProgressListener progressListener) throws IOException { dOut.writeByte(VAL_NODE); dOut.writeInt(dataNode.getSize()); progressListener.onTotalSteps(dataNode.getSize()); for (Entry<String, Object> entry : dataNode.getAll()) { final String key = entry.getKey(); final Object object = entry.getValue(); final Object resolvedObject = marshalObject(marshallerMap, object); dOut.writeUTF(key); serializeElement(marshallerMap, dOut, resolvedObject); progressListener.onStep(); } } /** * serializes a single object * * @param serializerMap * @param dOut * @param resolvedObject * @throws IOException */ private static void serializeElement(Map<String, DataMarshaller<?>> marshallerMap, DataOutputStream dOut, Object resolvedObject) throws IOException { if (resolvedObject == null) { dOut.writeByte(VAL_NULL); } else if (resolvedObject instanceof List) { final List<Object> list = (List<Object>) resolvedObject; final int size = list.size(); dOut.writeByte(VAL_LIST); dOut.writeInt(size); for (int i = 0; i < size; ++i) { serializeElement(marshallerMap, dOut, list.get(i)); } } else if (resolvedObject instanceof DataNode) { final DataNode aDataNode = (DataNode) resolvedObject; serialize(marshallerMap, dOut, aDataNode, DUMMY_PROGRESS_LISTENER); } else { dOut.writeByte(VAL_ELEMENT); final Class<?> resolvedObjectClass = resolvedObject.getClass(); Serializer<Object> serializer = (Serializer<Object>) PRIMITIVE_SERIALIZERS_BY_CLASS.get(resolvedObjectClass); if (serializer == null) { throw new IllegalStateException("Can't serialize resolved class " + resolvedObjectClass.getCanonicalName()); } dOut.writeByte(serializer.getSerializerId()); serializer.serialize(resolvedObject, dOut); } } /** * checkes if the given object is already marshalled, that is * if it is a DataNode, primitive object or array. * * @param object * @return */ private static boolean isMarshalled(Object object) { return (object == null || PRIMITIVE_SERIALIZERS_BY_CLASS.containsKey(object.getClass()) || object instanceof DataNode); } private static Map<String, DataMarshaller<?>> generateMarshallerMap(boolean fullyQualifiedClassName, List<DataMarshaller<?>> marshallers) { final Map<String, DataMarshaller<?>> map = new HashMap<String, DataMarshaller<?>>(); for (DataMarshaller<?> marshaller : marshallers) { final String key = fullyQualifiedClassName ? marshaller.getDataClass().getCanonicalName() : marshaller.getDataClassName(); map.put(key, marshaller); map.putAll(generateMarshallerMap(fullyQualifiedClassName, marshaller.getRequiredMarshallers())); } return map; } private static class BooleanSerializer implements Serializer<Boolean> { @Override public byte getSerializerId() { return 0x00; } @Override public Class<Boolean> getClazz() { return Boolean.class; } @Override public void serialize(Boolean object, DataOutputStream dOut) throws IOException { dOut.writeBoolean(object); } @Override public Boolean deserialize(DataInputStream dIn) throws IOException { return dIn.readBoolean(); } } private static class ByteSerializer implements Serializer<Byte> { @Override public byte getSerializerId() { return 0x01; } @Override public Class<Byte> getClazz() { return Byte.class; } @Override public void serialize(Byte object, DataOutputStream dOut) throws IOException { dOut.writeByte(object); } @Override public Byte deserialize(DataInputStream dIn) throws IOException { return dIn.readByte(); } } private static class CharSerializer implements Serializer<Character> { @Override public byte getSerializerId() { return 0x02; } @Override public Class<Character> getClazz() { return Character.class; } @Override public void serialize(Character object, DataOutputStream dOut) throws IOException { dOut.writeChar(object); } @Override public Character deserialize(DataInputStream dIn) throws IOException { return dIn.readChar(); } } private static class ShortSerializer implements Serializer<Short> { @Override public byte getSerializerId() { return 0x03; } @Override public Class<Short> getClazz() { return Short.class; } @Override public void serialize(Short object, DataOutputStream dOut) throws IOException { dOut.writeShort(object); } @Override public Short deserialize(DataInputStream dIn) throws IOException { return dIn.readShort(); } } private static class IntSerializer implements Serializer<Integer> { @Override public byte getSerializerId() { return 0x04; } @Override public Class<Integer> getClazz() { return Integer.class; } @Override public void serialize(Integer object, DataOutputStream dOut) throws IOException { dOut.writeInt(object); } @Override public Integer deserialize(DataInputStream dIn) throws IOException { return dIn.readInt(); } } private static class LongSerializer implements Serializer<Long> { @Override public byte getSerializerId() { return 0x05; } @Override public Class<Long> getClazz() { return Long.class; } @Override public void serialize(Long object, DataOutputStream dOut) throws IOException { dOut.writeLong(object); } @Override public Long deserialize(DataInputStream dIn) throws IOException { return dIn.readLong(); } } private static class FloatSerializer implements Serializer<Float> { @Override public byte getSerializerId() { return 0x06; } @Override public Class<Float> getClazz() { return Float.class; } @Override public void serialize(Float object, DataOutputStream dOut) throws IOException { dOut.writeFloat(object); } @Override public Float deserialize(DataInputStream dIn) throws IOException { return dIn.readFloat(); } } private static class DoubleSerializer implements Serializer<Double> { @Override public byte getSerializerId() { return 0x07; } @Override public Class<Double> getClazz() { return Double.class; } @Override public void serialize(Double object, DataOutputStream dOut) throws IOException { dOut.writeDouble(object); } @Override public Double deserialize(DataInputStream dIn) throws IOException { return dIn.readDouble(); } } private static class StringSerializer implements Serializer<String> { @Override public byte getSerializerId() { return 0x08; } @Override public Class<String> getClazz() { return String.class; } @Override public void serialize(String object, DataOutputStream dOut) throws IOException { dOut.writeUTF(object); } @Override public String deserialize(DataInputStream dIn) throws IOException { return dIn.readUTF(); } } private static class DummyProgressListener implements ProgressListener { @Override public void onTotalSteps(int totalSteps) { } @Override public void onStep() { } } }
package com.simsilica.mathd; /** * * * @author Paul Speed */ public class Matrix3d { public double m00, m01, m02; public double m10, m11, m12; public double m20, m21, m22; public Matrix3d() { makeIdentity(); } public Matrix3d( double m00, double m01, double m02, double m10, double m11, double m12, double m20, double m21, double m22 ) { this.m00 = m00; this.m01 = m01; this.m02 = m02; this.m10 = m10; this.m11 = m11; this.m12 = m12; this.m20 = m20; this.m21 = m21; this.m22 = m22; } public Matrix3d clone() { return new Matrix3d(m00, m01, m02, m10, m11, m12, m20, m21, m22); } public Matrix3d set( Matrix3d mat ) { this.m00 = mat.m00; this.m01 = mat.m01; this.m02 = mat.m02; this.m10 = mat.m10; this.m11 = mat.m11; this.m12 = mat.m12; this.m20 = mat.m20; this.m21 = mat.m21; this.m22 = mat.m22; return this; } public Matrix3d makeIdentity() { m01 = m02 = m10 = m12 = m20 = m21 = 0; m00 = m11 = m22 = 1; return this; } public Vec3d getColumn( int i ) { switch( i ) { case 0: return new Vec3d(m00,m10,m20); case 1: return new Vec3d(m01,m11,m21); case 2: return new Vec3d(m02,m12,m22); } return null; } public Matrix3d setColumn( int i, Vec3d col ) { switch( i ) { case 0: m00 = col.x; m10 = col.y; m20 = col.z; break; case 1: m01 = col.x; m11 = col.y; m21 = col.z; break; case 2: m02 = col.x; m12 = col.y; m22 = col.z; break; default: throw new IllegalArgumentException( "Column does not exist:" + i ); } return this; } public Matrix3d mult( Matrix3d mat ) { double temp00 = m00 * mat.m00 + m01 * mat.m10 + m02 * mat.m20; double temp01 = m00 * mat.m01 + m01 * mat.m11 + m02 * mat.m21; double temp02 = m00 * mat.m02 + m01 * mat.m12 + m02 * mat.m22; double temp10 = m10 * mat.m00 + m11 * mat.m10 + m12 * mat.m20; double temp11 = m10 * mat.m01 + m11 * mat.m11 + m12 * mat.m21; double temp12 = m10 * mat.m02 + m11 * mat.m12 + m12 * mat.m22; double temp20 = m20 * mat.m00 + m21 * mat.m10 + m22 * mat.m20; double temp21 = m20 * mat.m01 + m21 * mat.m11 + m22 * mat.m21; double temp22 = m20 * mat.m02 + m21 * mat.m12 + m22 * mat.m22; return new Matrix3d( temp00, temp01, temp02, temp10, temp11, temp12, temp20, temp21, temp22 ); } public Vec3d mult( Vec3d v ) { double x = v.x; double y = v.y; double z = v.z; double xr = (m00 * x) + (m01 * y) + (m02 * z); double yr = (m10 * x) + (m11 * y) + (m12 * z); double zr = (m20 * x) + (m21 * y) + (m22 * z); return new Vec3d(xr,yr,zr); } public Matrix3d multLocal( Matrix3d mat ) { double temp00 = m00 * mat.m00 + m01 * mat.m10 + m02 * mat.m20; double temp01 = m00 * mat.m01 + m01 * mat.m11 + m02 * mat.m21; double temp02 = m00 * mat.m02 + m01 * mat.m12 + m02 * mat.m22; double temp10 = m10 * mat.m00 + m11 * mat.m10 + m12 * mat.m20; double temp11 = m10 * mat.m01 + m11 * mat.m11 + m12 * mat.m21; double temp12 = m10 * mat.m02 + m11 * mat.m12 + m12 * mat.m22; double temp20 = m20 * mat.m00 + m21 * mat.m10 + m22 * mat.m20; double temp21 = m20 * mat.m01 + m21 * mat.m11 + m22 * mat.m21; double temp22 = m20 * mat.m02 + m21 * mat.m12 + m22 * mat.m22; this.m00 = temp00; this.m01 = temp01; this.m02 = temp02; this.m10 = temp10; this.m11 = temp11; this.m12 = temp12; this.m20 = temp20; this.m21 = temp21; this.m22 = temp22; return this; } public Matrix3d multLocal( double scale ) { this.m00 *= scale; this.m01 *= scale; this.m02 *= scale; this.m10 *= scale; this.m11 *= scale; this.m12 *= scale; this.m20 *= scale; this.m21 *= scale; this.m22 *= scale; return this; } public double determinant() { double co00 = (m11 * m22) - (m12 * m21); double co10 = (m12 * m20) - (m10 * m22); double co20 = (m10 * m21) - (m11 * m20); return m00 * co00 + m01 * co10 + m02 * co20; } public Matrix3d invert() { double d = determinant(); if( d == 0 ) return new Matrix3d(); // questionable double rm00 = m11 * m22 - m12 * m21; double rm01 = m02 * m21 - m01 * m22; double rm02 = m01 * m12 - m02 * m11; double rm10 = m12 * m20 - m10 * m22; double rm11 = m00 * m22 - m02 * m20; double rm12 = m02 * m10 - m00 * m12; double rm20 = m10 * m21 - m11 * m20; double rm21 = m01 * m20 - m00 * m21; double rm22 = m00 * m11 - m01 * m10; double s = 1.0 / d; return new Matrix3d( rm00 * s, rm01 * s, rm02 * s, rm10 * s, rm11 * s, rm12 * s, rm20 * s, rm21 * s, rm22 * s ); } public Matrix3d transpose() { return new Matrix3d( m00, m10, m20, m01, m11, m21, m02, m12, m22 ); } public Matrix3d setSkewSymmetric( Vec3d v ) { m00 = 0; m11 = 0; m22 = 0; m01 = -v.z; m02 = v.y; m10 = v.z; m12 = -v.x; m20 = -v.y; m21 = v.x; return this; } public Matrix3d addLocal( Matrix3d add ) { m00 = m00 + add.m00; m01 = m01 + add.m01; m02 = m02 + add.m02; m10 = m10 + add.m10; m11 = m11 + add.m11; m12 = m12 + add.m12; m20 = m20 + add.m20; m21 = m21 + add.m21; m22 = m22 + add.m22; return this; } public String toString() { return "Matrix3d[{" + m00 + ", " + m01 + ", " + m02 + "}, {" + m10 + ", " + m11 + ", " + m12 + "}, {" + m20 + ", " + m21 + ", " + m22 + "}]"; } }
package com.tagmycode.plugin; import com.sun.deploy.uitoolkit.impl.fx.HostServicesFactory; import javafx.application.Application; import javafx.stage.Stage; public class Browser implements IBrowser { private Application application; public Browser() { this.application = new Application() { @Override public void start(Stage primaryStage) throws Exception { } }; } @Override public boolean openUrl(String url) { HostServicesFactory.getInstance(application).showDocument(url); return true; } }
package de.iani.cubequest; import de.iani.cubequest.util.ChatAndTextUtil; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogRecord; import org.bukkit.Bukkit; import org.bukkit.entity.Player; public class LogHandler extends Handler { private static final int MAX_LOGS_PER_TIME = 3; private static final long TIME_IN_TICKS = 1200; // 1 Minute private CubeQuest plugin; private Map<Player, Boolean> listeners; private int count; public LogHandler() { this.plugin = CubeQuest.getInstance(); this.listeners = new HashMap<>(); setLevel(Level.WARNING); this.plugin.getEventListener().addOnPlayerJoin(p -> playerJoined(p)); this.plugin.getEventListener().addOnPlayerQuit(p -> playerQuit(p)); this.plugin.getLogger().addHandler(this); } public void playerJoined(Player player) { if (player.hasPermission(CubeQuest.SEE_EXCEPTIONS_PERMISSION)) { this.listeners.put(player, false); } } public void playerQuit(Player player) { this.listeners.remove(player); } public void notifyPersonalLog(Player player) { this.listeners.put(player, true); } @Override public void publish(LogRecord record) { if (record.getLevel().intValue() < Level.WARNING.intValue()) { return; } if (this.count >= MAX_LOGS_PER_TIME) { return; } this.count++; Iterator<Player> it = this.listeners.keySet().iterator(); while (it.hasNext()) { Player player = it.next(); if (!player.hasPermission(CubeQuest.SEE_EXCEPTIONS_PERMISSION)) { it.remove(); continue; } if (this.listeners.get(player)) { this.listeners.put(player, false); continue; } ChatAndTextUtil.sendErrorMessage(player, "A servere log was made:"); ChatAndTextUtil.sendWarningMessage(player, record.getMessage()); if (record.getThrown() != null) { ChatAndTextUtil.sendWarningMessage(player, ChatAndTextUtil.exceptionToString(record.getThrown())); } } Bukkit.getScheduler().scheduleSyncDelayedTask(this.plugin, () -> this.count TIME_IN_TICKS); } @Override public void flush() { // nothing } @Override public void close() throws SecurityException { // nothing } }
package de.pi3g.pi.rcswitch; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.Pin; import com.pi4j.wiringpi.Gpio; import java.util.BitSet; public class RCSwitch { private final GpioPinDigitalOutput transmitterPin; private Protocol protocol; private final int repeatTransmit = 10; public RCSwitch(Pin transmitterPin) { this(transmitterPin, Protocol.PROTOCOL_01); } public RCSwitch(Pin transmitterPin, Protocol protocol) { final GpioController gpio = GpioFactory.getInstance(); this.transmitterPin = gpio.provisionDigitalOutputPin(transmitterPin); this.protocol = protocol; } /** * Switch a remote switch on (Type A with 10 pole DIP switches) * * @param switchGroupAddress Code of the switch group (refers to DIP * switches 1..5 where "1" = on and "0" = off, if all DIP switches are on * it's "11111") * @param switchCode Number of the switch itself (1..4) */ public void switchOn(BitSet switchGroupAddress, int switchCode) { if (switchGroupAddress.length() > 5) { throw new IllegalArgumentException("switch group address has more than 5 bits!"); } this.sendTriState(this.getCodeWordA(switchGroupAddress, switchCode, true)); } /** * Switch a remote switch off * * @param switchGroupAddress Code of the switch group (refers to DIP * switches 1..5 where "1" = on and "0" = off, if all DIP switches are on * it's "11111") * @param switchCode Number of the switch itself (1..4 for A..D) */ public void switchOff(BitSet switchGroupAddress, int switchCode) { if (switchGroupAddress.length() > 5) { throw new IllegalArgumentException("switch group address has more than 5 bits!"); } this.sendTriState(this.getCodeWordA(switchGroupAddress, switchCode, false)); } /** * Switch a remote switch on (Type B with two rotary/sliding switches) * * @param nAddressCode Number of the switch group (1..4) * @param nChannelCode Number of the switch itself (1..4) */ public void switchOn(int nAddressCode, int nChannelCode) { sendTriState(getCodeWordB(nAddressCode, nChannelCode, true)); } /** * Switch a remote switch off (Type B with two rotary/sliding switches) * * @param nAddressCode Number of the switch group (1..4) * @param nChannelCode Number of the switch itself (1..4) */ public void switchOff(int nAddressCode, int nChannelCode) { sendTriState(getCodeWordB(nAddressCode, nChannelCode, false)); } /** * Send a string of bits * * @param bitString Bits (e.g. 000000000001010100010001) */ public void send(final String bitString) { BitSet bitSet = new BitSet(bitString.length()); for (int i = 0; i < bitString.length(); i++) { if (bitString.charAt(i) == '1') { bitSet.set(i); } } send(bitSet, bitString.length()); } /** * Send a set of bits * * @param bitSet Bits (000000000001010100010001) * @param length Length of the bit string (24) */ public void send(final BitSet bitSet, int length) { if (transmitterPin != null) { for (int nRepeat = 0; nRepeat < repeatTransmit; nRepeat++) { for (int i = 0; i < length; i++) { if (bitSet.get(i)) { transmit(protocol.getOneBit()); } else { transmit(protocol.getZeroBit()); } } sendSync(); } transmitterPin.low(); } } /** * Like getCodeWord (Type A) */ private String getCodeWordA(BitSet switchGroupAddress, int switchCode, boolean status) { int nReturnPos = 0; char[] sReturn = new char[12]; String[] code = new String[]{"FFFFF", "0FFFF", "F0FFF", "FF0FF", "FFF0F", "FFFF0"}; if (switchCode < 1 || switchCode > 5) { throw new IllegalArgumentException("switch code has to be between " + "1 (outlet A) and 5 (outlet E)"); } for (int i = 0; i < 5; i++) { if (!switchGroupAddress.get(i)) { sReturn[nReturnPos++] = 'F'; } else { sReturn[nReturnPos++] = '0'; } } for (int i = 0; i < 5; i++) { sReturn[nReturnPos++] = code[switchCode].charAt(i); } if (status) { sReturn[nReturnPos++] = '0'; sReturn[nReturnPos++] = 'F'; } else { sReturn[nReturnPos++] = 'F'; sReturn[nReturnPos++] = '0'; } return new String(sReturn); } private String getCodeWordB(int nAddressCode, int nChannelCode, boolean bStatus) { int nReturnPos = 0; char[] sReturn = new char[13]; String[] code = new String[]{"FFFF", "0FFF", "F0FF", "FF0F", "FFF0"}; if (nAddressCode < 1 || nAddressCode > 4 || nChannelCode < 1 || nChannelCode > 4) { return ""; } for (int i = 0; i < 4; i++) { sReturn[nReturnPos++] = code[nAddressCode].charAt(i); } for (int i = 0; i < 4; i++) { sReturn[nReturnPos++] = code[nChannelCode].charAt(i); } sReturn[nReturnPos++] = 'F'; sReturn[nReturnPos++] = 'F'; sReturn[nReturnPos++] = 'F'; if (bStatus) { sReturn[nReturnPos++] = 'F'; } else { sReturn[nReturnPos++] = '0'; } return new String(sReturn); } /** * Sends a Code Word * * @param codeWord /^[10FS]*$/ -> see getCodeWord */ public void sendTriState(String codeWord) { if (transmitterPin != null) { for (int nRepeat = 0; nRepeat < repeatTransmit; nRepeat++) { for (int i = 0; i < codeWord.length(); ++i) { switch (codeWord.charAt(i)) { case '0': this.sendT0(); break; case 'F': this.sendTF(); break; case '1': this.sendT1(); break; } } this.sendSync(); } transmitterPin.low(); } } private void sendSync() { this.transmit(this.protocol.getSyncBit()); } private void sendT0() { transmit(this.protocol.getZeroBit()); transmit(this.protocol.getZeroBit()); } private void sendT1() { transmit(this.protocol.getOneBit()); transmit(this.protocol.getOneBit()); } private void sendTF() { transmit(this.protocol.getZeroBit()); transmit(this.protocol.getOneBit()); } private void transmit(final Waveform waveform) { transmit(waveform.getHigh(), waveform.getLow()); } private void transmit(int nHighPulses, int nLowPulses) { adjustPinValue(true); Gpio.delayMicroseconds(this.protocol.getPulseLength() * nHighPulses); adjustPinValue(false); Gpio.delayMicroseconds(this.protocol.getPulseLength() * nLowPulses); } private void adjustPinValue(boolean value) { if (protocol.isInvertedSignal() ^ value) { transmitterPin.high(); } else { transmitterPin.low(); } } /** * convenient method to convert a string like "11011" to a BitSet. * * @param address the string representation of the rc address * @return a bitset containing the address that can be used for * switchOn()/switchOff() */ public static BitSet getSwitchGroupAddress(String address) { if (address.length() != 5) { throw new IllegalArgumentException("the switchGroupAddress must consist of exactly 5 bits!"); } BitSet bitSet = new BitSet(5); for (int i = 0; i < 5; i++) { bitSet.set(i, address.charAt(i) == '1'); } return bitSet; } public void setProtocol(final Protocol protocol) { this.protocol = protocol; } }
package enmasse.systemtest; import io.fabric8.kubernetes.api.model.Pod; import io.fabric8.kubernetes.api.model.Service; import io.fabric8.kubernetes.api.model.ServicePort; import io.fabric8.kubernetes.client.Config; import io.fabric8.kubernetes.client.ConfigBuilder; import io.fabric8.openshift.api.model.Route; import io.fabric8.openshift.client.DefaultOpenShiftClient; import io.fabric8.openshift.client.OpenShiftClient; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * Handles interaction with openshift cluster */ public class OpenShift { private final Environment environment; private final OpenShiftClient client; public OpenShift(Environment environment) { this.environment = environment; Config config = new ConfigBuilder() .withMasterUrl(environment.openShiftUrl()) .withOauthToken(environment.openShiftToken()) .withNamespace(environment.namespace()) .withUsername(environment.openShiftUser()) .build(); client = new DefaultOpenShiftClient(config); } private Endpoint getEndpoint(String serviceName, String port) { Service service = client.services().inNamespace(environment.namespace()).withName(serviceName).get(); return new Endpoint(service.getSpec().getPortalIP(), getPort(service, port)); } public Endpoint getSecureEndpoint() { return getEndpoint("messaging", "amqps"); } public Endpoint getInsecureEndpoint() { return getEndpoint("messaging", "amqp"); } private static int getPort(Service service, String portName) { List<ServicePort> ports = service.getSpec().getPorts(); for (ServicePort port : ports) { if (port.getName().equals(portName)) { return port.getPort(); } } throw new IllegalArgumentException("Unable to find port " + portName + " for service " + service.getMetadata().getName()); } public String getRouteHost() { Route route = client.routes().inNamespace(environment.namespace()).withName("messaging").get(); return route.getSpec().getHost(); } public Endpoint getRestEndpoint() { return getEndpoint("admin", "restapi"); } public void setDeploymentReplicas(String name, int numReplicas) { client.deploymentConfigs() .inNamespace(environment.namespace()) .withName(name) .scale(numReplicas, true); } public List<Pod> listPods() { return client.pods() .inNamespace(environment.namespace()) .list() .getItems().stream() .filter(pod -> !pod.getMetadata().getName().endsWith("-deploy")) .collect(Collectors.toList()); } public List<Pod> listPods(Map<String, String> labelSelector) { return client.pods() .inNamespace(environment.namespace()) .withLabels(labelSelector) .list() .getItems().stream() .filter(pod -> !pod.getMetadata().getName().endsWith("-deploy")) .collect(Collectors.toList()); } }
package io.github.classgraph; import java.io.File; import java.io.IOException; import java.util.AbstractMap.SimpleEntry; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import io.github.classgraph.ClassGraph.FailureHandler; import io.github.classgraph.ClassGraph.ScanResultProcessor; import io.github.classgraph.utils.ClassLoaderAndModuleFinder; import io.github.classgraph.utils.ClasspathFinder; import io.github.classgraph.utils.ClasspathOrModulePathEntry; import io.github.classgraph.utils.InterruptionChecker; import io.github.classgraph.utils.JarUtils; import io.github.classgraph.utils.LogNode; import io.github.classgraph.utils.NestedJarHandler; import io.github.classgraph.utils.ScanSpec; import io.github.classgraph.utils.SingletonMap; import io.github.classgraph.utils.WorkQueue; import io.github.classgraph.utils.WorkQueue.WorkUnitProcessor; /** The classpath scanner. */ class Scanner implements Callable<ScanResult> { private final ScanSpec scanSpec; private final ExecutorService executorService; private final int numParallelTasks; private final InterruptionChecker interruptionChecker = new InterruptionChecker(); private final ScanResultProcessor scanResultProcessor; private final FailureHandler failureHandler; private final LogNode topLevelLog; /** The classpath scanner. */ Scanner(final ScanSpec scanSpec, final ExecutorService executorService, final int numParallelTasks, final ScanResultProcessor scannResultProcessor, final FailureHandler failureHandler, final LogNode log) { this.scanSpec = scanSpec; scanSpec.sortPrefixes(); this.executorService = executorService; this.numParallelTasks = numParallelTasks; this.scanResultProcessor = scannResultProcessor; this.failureHandler = failureHandler; this.topLevelLog = log; // Add ScanSpec to beginning of log scanSpec.log(log); } /** A map from relative path to classpath element singleton. */ private static class ClasspathOrModulePathEntryToClasspathElementMap extends SingletonMap<ClasspathOrModulePathEntry, ClasspathElement> { private final ScanSpec scanSpec; private final NestedJarHandler nestedJarHandler; private WorkQueue<ClasspathOrModulePathEntry> workQueue; /** A map from relative path to classpath element singleton. */ ClasspathOrModulePathEntryToClasspathElementMap(final ScanSpec scanSpec, final NestedJarHandler nestedJarHandler) { this.scanSpec = scanSpec; this.nestedJarHandler = nestedJarHandler; } /** * Work queue -- needs to be set for zipfiles, but not for directories, since zipfiles can contain * Class-Path manifest entries, which require the adding of additional work units to the scanning work * queue. */ void setWorkQueue(final WorkQueue<ClasspathOrModulePathEntry> workQueue) { this.workQueue = workQueue; } /** Create a new classpath element singleton instance. */ @Override public ClasspathElement newInstance(final ClasspathOrModulePathEntry classpathElt, final LogNode log) { final LogNode jarLog = log == null ? null : log.log("Reading " + classpathElt.getResolvedPath()); if (classpathElt.isValidClasspathElement(scanSpec, jarLog)) { try { final boolean isModule = classpathElt.getModuleRef() != null; final boolean isFile = !isModule && classpathElt.isFile(jarLog); final boolean isDir = !isModule && classpathElt.isDirectory(jarLog); if (isFile && !scanSpec.scanJars) { if (jarLog != null) { jarLog.log("Skipping because jar scanning has been disabled: " + classpathElt); } } else if (isFile && !scanSpec.jarWhiteBlackList .isWhitelistedAndNotBlacklisted(classpathElt.getCanonicalPath(jarLog))) { if (jarLog != null) { jarLog.log("Skipping jarfile that is blacklisted or not whitelisted: " + classpathElt); } } else if (isDir && !scanSpec.scanDirs) { if (jarLog != null) { jarLog.log("Skipping because directory scanning has been disabled: " + classpathElt); } } else if (isModule && !scanSpec.scanModules) { if (jarLog != null) { jarLog.log("Skipping because module scanning has been disabled: " + classpathElt); } } else { // Classpath element is valid => add as a singleton. This will trigger // calling the ClasspathElementZip constructor in the case of jarfiles, // which will check the manifest file for Class-Path entries, and if // any are found, additional work units will be added to the work queue // to scan those jarfiles too. If Class-Path entries are found, they // are added as child elements of the current classpath element, so // that they can be inserted at the correct location in the classpath // order. return ClasspathElement.newInstance(classpathElt, scanSpec, nestedJarHandler, workQueue, jarLog); } } catch (final Exception e) { if (jarLog != null) { // Could not create singleton, possibly due to canonicalization problem jarLog.log("Skipping invalid classpath element " + classpathElt + " : " + e); } } } // Return null if classpath element is not valid. return null; } } /** * Recursively perform a depth-first search of jar interdependencies, breaking cycles if necessary, to determine * the final classpath element order. */ private static void findClasspathOrder(final ClasspathElement currClasspathElement, final ClasspathOrModulePathEntryToClasspathElementMap classpathElementMap, final HashSet<ClasspathElement> visitedClasspathElts, final ArrayList<ClasspathElement> order) throws InterruptedException { if (visitedClasspathElts.add(currClasspathElement)) { if (!currClasspathElement.skipClasspathElement) { // Don't add a classpath element if it is marked to be skipped. order.add(currClasspathElement); } // Whether or not a classpath element should be skipped, add any child classpath elements that are // not marked to be skipped (i.e. keep recursing) if (currClasspathElement.childClasspathElts != null) { for (final ClasspathOrModulePathEntry childClasspathElt : currClasspathElement.childClasspathElts) { final ClasspathElement childSingleton = classpathElementMap.get(childClasspathElt); if (childSingleton != null) { findClasspathOrder(childSingleton, classpathElementMap, visitedClasspathElts, order); } } } if (currClasspathElement.skipClasspathElement) { // If classpath element is marked to be skipped, close it (it will not be used again). currClasspathElement.closeRecyclers(); } } } /** * Recursively perform a depth-first search of jar interdependencies, breaking cycles if necessary, to determine * the final classpath element order. */ private static List<ClasspathElement> findClasspathOrder( final List<ClasspathOrModulePathEntry> rawClasspathElements, final ClasspathOrModulePathEntryToClasspathElementMap classpathElementMap) throws InterruptedException { // Recurse from toplevel classpath elements to determine a total ordering of classpath elements (jars with // Class-Path entries in their manifest file should have those child resources included in-place in the // classpath). final HashSet<ClasspathElement> visitedClasspathElts = new HashSet<>(); final ArrayList<ClasspathElement> order = new ArrayList<>(); for (final ClasspathOrModulePathEntry toplevelClasspathElt : rawClasspathElements) { final ClasspathElement toplevelSingleton = classpathElementMap.get(toplevelClasspathElt); if (toplevelSingleton != null) { findClasspathOrder(toplevelSingleton, classpathElementMap, visitedClasspathElts, order); } } return order; } /** Used to enqueue classfiles for scanning. */ private static class ClassfileScanWorkUnit { ClasspathElement classpathElement; Resource classfileResource; boolean isExternalClass; ClassfileScanWorkUnit(final ClasspathElement classpathElement, final Resource classfileResource, final boolean isExternalClass) { this.classpathElement = classpathElement; this.classfileResource = classfileResource; this.isExternalClass = isExternalClass; } } /** WorkUnitProcessor for scanning classfiles. */ private static class ClassfileScannerWorkUnitProcessor implements WorkUnitProcessor<ClassfileScanWorkUnit> { private final ScanSpec scanSpec; private final Map<String, Resource> classNameToNonBlacklistedResource; private final Set<String> scannedClassNames; private final ConcurrentLinkedQueue<ClassInfoUnlinked> classInfoUnlinkedQueue; private final LogNode log; private final InterruptionChecker interruptionChecker; public ClassfileScannerWorkUnitProcessor(final ScanSpec scanSpec, final Map<String, Resource> classNameToNonBlacklistedResource, final Set<String> scannedClassNames, final ConcurrentLinkedQueue<ClassInfoUnlinked> classInfoUnlinkedQueue, final LogNode log, final InterruptionChecker interruptionChecker) { this.scanSpec = scanSpec; this.classNameToNonBlacklistedResource = classNameToNonBlacklistedResource; this.scannedClassNames = scannedClassNames; this.classInfoUnlinkedQueue = classInfoUnlinkedQueue; this.log = log; this.interruptionChecker = interruptionChecker; } /** Extend scanning to a superclass, interface or annotation. */ private List<ClassfileScanWorkUnit> extendScanningUpwards(final String className, final String relationship, final ClasspathElement classpathElement, final List<ClassfileScanWorkUnit> additionalWorkUnitsIn, final LogNode subLog) { List<ClassfileScanWorkUnit> additionalWorkUnits = additionalWorkUnitsIn; // Don't scan a class more than once if (className != null && scannedClassNames.add(className)) { // See if the named class can be found as a non-blacklisted resource final Resource classResource = classNameToNonBlacklistedResource.get(className); if (classResource != null) { // Class is a non-blacklisted external class -- enqueue for scanning if (subLog != null) { subLog.log("Scheduling external class for scanning: " + relationship + " " + className); } if (additionalWorkUnits == null) { additionalWorkUnits = new ArrayList<>(); } additionalWorkUnits.add(new ClassfileScanWorkUnit(classpathElement, classResource, /* isExternalClass = */ true)); } else { if (subLog != null && !className.equals("java.lang.Object")) { subLog.log("External " + relationship + " " + className + " was not found in non-blacklisted packages + "cannot extend scanning to this superclass"); } } } return additionalWorkUnits; } @Override public void processWorkUnit(final ClassfileScanWorkUnit workUnit, final WorkQueue<ClassfileScanWorkUnit> workQueue) throws Exception { final LogNode subLog = log == null ? null : log.log(workUnit.classfileResource.getPath(), "Parsing classfile " + workUnit.classfileResource); try { // Parse classfile binary format, creating a ClassInfoUnlinked object final ClassInfoUnlinked classInfoUnlinked = new ClassfileBinaryParser() .readClassInfoFromClassfileHeader(workUnit.classpathElement, workUnit.classfileResource.getPath(), workUnit.classfileResource, workUnit.isExternalClass, scanSpec, subLog); // If class was successfully read, output new ClassInfoUnlinked object if (classInfoUnlinked != null) { classInfoUnlinkedQueue.add(classInfoUnlinked); classInfoUnlinked.logTo(subLog); // Check if any superclasses, interfaces or annotations are external (non-whitelisted) classes if (scanSpec.extendScanningUpwardsToExternalClasses) { // Check superclass List<ClassfileScanWorkUnit> additionalWorkUnits = null; additionalWorkUnits = extendScanningUpwards(classInfoUnlinked.superclassName, "superclass", workUnit.classpathElement, additionalWorkUnits, subLog); // Check implemented interfaces if (classInfoUnlinked.implementedInterfaces != null) { for (final String className : classInfoUnlinked.implementedInterfaces) { additionalWorkUnits = extendScanningUpwards(className, "interface", workUnit.classpathElement, additionalWorkUnits, subLog); } } // Check class annotations if (classInfoUnlinked.classAnnotations != null) { for (final AnnotationInfo annotationInfo : classInfoUnlinked.classAnnotations) { additionalWorkUnits = extendScanningUpwards(annotationInfo.getName(), "class annotation", workUnit.classpathElement, additionalWorkUnits, subLog); } } // Check method annotations and method parameter annotations if (classInfoUnlinked.methodInfoList != null) { for (final MethodInfo methodInfo : classInfoUnlinked.methodInfoList) { if (methodInfo.annotationInfo != null) { for (final AnnotationInfo methodAnnotationInfo : methodInfo.annotationInfo) { additionalWorkUnits = extendScanningUpwards(methodAnnotationInfo.getName(), "method annotation", workUnit.classpathElement, additionalWorkUnits, subLog); } if (methodInfo.parameterAnnotationInfo != null && methodInfo.parameterAnnotationInfo.length > 0) { for (final AnnotationInfo[] paramAnns : methodInfo.parameterAnnotationInfo) { if (paramAnns != null && paramAnns.length > 0) { for (final AnnotationInfo paramAnn : paramAnns) { additionalWorkUnits = extendScanningUpwards(paramAnn.getName(), "method parameter annotation", workUnit.classpathElement, additionalWorkUnits, subLog); } } } } } } } // Check field annotations if (classInfoUnlinked.fieldInfoList != null) { for (final FieldInfo fieldInfo : classInfoUnlinked.fieldInfoList) { if (fieldInfo.annotationInfo != null) { for (final AnnotationInfo fieldAnnotationInfo : fieldInfo.annotationInfo) { additionalWorkUnits = extendScanningUpwards(fieldAnnotationInfo.getName(), "field annotation", workUnit.classpathElement, additionalWorkUnits, subLog); } } } } // If any external classes were found, schedule them for scanning if (additionalWorkUnits != null) { workQueue.addWorkUnits(additionalWorkUnits); } } } if (subLog != null) { subLog.addElapsedTime(); } } catch ( final IOException e) { if (subLog != null) { subLog.log("IOException while attempting to read classfile " + workUnit.classfileResource + " -- skipping", e); } } catch (final Throwable e) { if (subLog != null) { subLog.log("Exception while parsing classfile " + workUnit.classfileResource, e); } // Re-throw throw e; } interruptionChecker.check(); } } /** * Determine the unique ordered classpath elements, and run a scan looking for file or classfile matches if * necessary. */ @Override public ScanResult call() throws InterruptedException, ExecutionException { final LogNode classpathFinderLog = topLevelLog == null ? null : topLevelLog.log("Finding classpath entries"); NestedJarHandler nestedJarHandler = new NestedJarHandler(scanSpec, classpathFinderLog); final ClasspathOrModulePathEntryToClasspathElementMap classpathElementMap = new ClasspathOrModulePathEntryToClasspathElementMap(scanSpec, nestedJarHandler); try { final long scanStart = System.nanoTime(); // Get classpath finder final LogNode getRawElementsLog = classpathFinderLog == null ? null : classpathFinderLog.log("Getting raw classpath elements"); final ClasspathFinder classpathFinder = new ClasspathFinder(scanSpec, nestedJarHandler, getRawElementsLog); final ClassLoaderAndModuleFinder classLoaderAndModuleFinder = classpathFinder .getClassLoaderAndModuleFinder(); final ClassLoader[] classLoaderOrder = classLoaderAndModuleFinder.getClassLoaders(); final List<ClasspathOrModulePathEntry> rawClasspathEltOrder = new ArrayList<>(); if (scanSpec.overrideClasspath == null && scanSpec.overrideClassLoaders == null) { // Add modules to start of classpath order, before traditional classpath final List<ModuleRef> systemModules = classLoaderAndModuleFinder.getSystemModuleRefs(); if (systemModules != null) { for (final ModuleRef systemModule : systemModules) { final String moduleName = systemModule.getName(); if ((!scanSpec.blacklistSystemJarsOrModules || !JarUtils.isInSystemPackageOrModule(moduleName)) && scanSpec.overrideModuleLayers == null) { if (scanSpec.moduleWhiteBlackList.isWhitelistedAndNotBlacklisted(moduleName)) { rawClasspathEltOrder.add(new ClasspathOrModulePathEntry(systemModule, nestedJarHandler, getRawElementsLog)); } else { if (classpathFinderLog != null) { classpathFinderLog.log( "Skipping non-whitelisted or blacklisted system module: " + moduleName); } } } else { if (classpathFinderLog != null) { classpathFinderLog.log("Skipping system module: " + moduleName); } } } } final List<ModuleRef> nonSystemModules = classLoaderAndModuleFinder.getNonSystemModuleRefs(); if (nonSystemModules != null) { for (final ModuleRef nonSystemModule : nonSystemModules) { final String moduleName = nonSystemModule.getName(); if (scanSpec.moduleWhiteBlackList.isWhitelistedAndNotBlacklisted(moduleName)) { rawClasspathEltOrder.add(new ClasspathOrModulePathEntry(nonSystemModule, nestedJarHandler, getRawElementsLog)); } else { if (classpathFinderLog != null) { classpathFinderLog .log("Skipping non-whitelisted or blacklisted module: " + moduleName); } } } } } // Add traditional classpath entries to the classpath order rawClasspathEltOrder.addAll(classpathFinder.getRawClasspathElements()); final List<String> rawClasspathEltOrderStrs = new ArrayList<>(rawClasspathEltOrder.size()); for (final ClasspathOrModulePathEntry entry : rawClasspathEltOrder) { rawClasspathEltOrderStrs.add(entry.getResolvedPath()); } // In parallel, resolve raw classpath elements to canonical paths, creating a ClasspathElement singleton // for each unique canonical path. Also check jars against jar whitelist/blacklist. final LogNode preScanLog = classpathFinderLog == null ? null : classpathFinderLog.log("Reading jarfile metadata"); WorkQueue.runWorkQueue(rawClasspathEltOrder, executorService, numParallelTasks, new WorkUnitProcessor<ClasspathOrModulePathEntry>() { @Override public void processWorkUnit(final ClasspathOrModulePathEntry rawClasspathEltPath, final WorkQueue<ClasspathOrModulePathEntry> workQueue) throws Exception { try { // Ensure the work queue is set -- will be done multiple times, but is idempotent classpathElementMap.setWorkQueue(workQueue); // Add the classpath element as a singleton. This will trigger calling // the ClasspathElementZip constructor in the case of jarfiles, which // will check the manifest file for Class-Path entries, and if any are // found, additional work units will be added to the work queue to scan // those jarfiles too. If Class-Path entries are found, they are added // as child elements of the current classpath element, so that they can // be inserted at the correct location in the classpath order. classpathElementMap.getOrCreateSingleton(rawClasspathEltPath, preScanLog); } catch (final IllegalArgumentException e) { // Thrown if classpath element is invalid (already logged) } } }, interruptionChecker, preScanLog); // Determine total ordering of classpath elements, inserting jars referenced in manifest Class-Path // entries in-place into the ordering, if they haven't been listed earlier in the classpath already. List<ClasspathElement> classpathOrder = findClasspathOrder(rawClasspathEltOrder, classpathElementMap); // Log final classpath element order, after inserting Class-Path entries from manifest files if (classpathFinderLog != null) { final LogNode logNode = classpathFinderLog.log("Final classpath element order:"); for (int i = 0; i < classpathOrder.size(); i++) { final ClasspathElement classpathElt = classpathOrder.get(i); final ModuleRef classpathElementModuleRef = classpathElt.getClasspathElementModuleRef(); if (classpathElementModuleRef != null) { logNode.log(i + ": module " + classpathElementModuleRef.getName() + " ; module location: " + classpathElementModuleRef.getLocationStr()); } else { final String classpathEltStr = classpathElt.toString(); final String classpathEltFileStr = "" + classpathElt.getClasspathElementFile(logNode); final String packageRoot = classpathElt.getJarfilePackageRoot(); logNode.log(i + ": " + (classpathEltStr.equals(classpathEltFileStr) && packageRoot.isEmpty() ? classpathEltStr : classpathElt + " -> " + classpathEltFileStr + (packageRoot.isEmpty() ? "" : " ; package root: " + packageRoot))); } } } ScanResult scanResult; if (!scanSpec.performScan) { if (topLevelLog != null) { topLevelLog.log("Only returning classpath elements (not performing a scan)"); } // This is the result of a call to ClassGraph#getUniqueClasspathElements(), so just // create placeholder ScanResult to contain classpathElementFilesOrdered. scanResult = new ScanResult(scanSpec, classpathOrder, rawClasspathEltOrderStrs, classLoaderOrder, /* classNameToClassInfo = */ null, /* packageNameToPackageInfo = */ null, /* moduleNameToModuleInfo = */ null, /* fileToLastModified = */ null, nestedJarHandler, topLevelLog); } else { // Perform scan of the classpath // Find classpath elements that are path prefixes of other classpath elements final List<SimpleEntry<String, ClasspathElement>> classpathEltResolvedPathToElement = new ArrayList<>(); for (int i = 0; i < classpathOrder.size(); i++) { final ClasspathElement classpathElement = classpathOrder.get(i); classpathEltResolvedPathToElement.add(new SimpleEntry<>( classpathElement.classpathEltPath.getResolvedPath(), classpathElement)); } Collections.sort(classpathEltResolvedPathToElement, new Comparator<SimpleEntry<String, ClasspathElement>>() { // Sort classpath elements into lexicographic order @Override public int compare(final SimpleEntry<String, ClasspathElement> o1, final SimpleEntry<String, ClasspathElement> o2) { // Path strings will all be unique return o1.getKey().compareTo(o2.getKey()); } }); LogNode nestedClasspathRootNode = null; for (int i = 0; i < classpathEltResolvedPathToElement.size(); i++) { // See if each classpath element is a prefix of any others (if so, they will immediately follow // in lexicographic order) final SimpleEntry<String, ClasspathElement> ei = classpathEltResolvedPathToElement.get(i); final String basePath = ei.getKey(); final int basePathLen = basePath.length(); for (int j = i + 1; j < classpathEltResolvedPathToElement.size(); j++) { final SimpleEntry<String, ClasspathElement> ej = classpathEltResolvedPathToElement.get(j); final String comparePath = ej.getKey(); final int comparePathLen = comparePath.length(); boolean foundNestedClasspathRoot = false; if (comparePath.startsWith(basePath) && comparePathLen > basePathLen) { // Require a separator after the prefix final char nextChar = comparePath.charAt(basePathLen); if (nextChar == '/' || nextChar == '!') { // basePath is a path prefix of comparePath. Ensure that the nested classpath does // not contain another '!' zip-separator (since classpath scanning does not recurse // to jars-within-jars unless they are explicitly listed on the classpath) final String nestedClasspathRelativePath = comparePath.substring(basePathLen + 1); if (nestedClasspathRelativePath.indexOf('!') < 0) { // Found a nested classpath root foundNestedClasspathRoot = true; // Store link from prefix element to nested elements final ClasspathElement baseElement = ei.getValue(); if (baseElement.nestedClasspathRootPrefixes == null) { baseElement.nestedClasspathRootPrefixes = new ArrayList<>(); } baseElement.nestedClasspathRootPrefixes.add(nestedClasspathRelativePath + "/"); if (classpathFinderLog != null) { if (nestedClasspathRootNode == null) { nestedClasspathRootNode = classpathFinderLog .log("Found nested classpath elements"); } nestedClasspathRootNode.log( basePath + " is a prefix of the nested element " + comparePath); } } } } if (!foundNestedClasspathRoot) { // After the first non-match, there can be no more prefix matches in the sorted order break; } } } // Scan for matching classfiles / files, looking only at filenames / file paths, and not contents final LogNode pathScanLog = classpathFinderLog == null ? null : classpathFinderLog.log("Scanning filenames within classpath elements"); WorkQueue.runWorkQueue(classpathOrder, executorService, numParallelTasks, new WorkUnitProcessor<ClasspathElement>() { @Override public void processWorkUnit(final ClasspathElement classpathElement, final WorkQueue<ClasspathElement> workQueueIgnored) throws Exception { // Scan the paths within a directory or jar classpathElement.scanPaths(pathScanLog); if (preScanLog != null) { preScanLog.addElapsedTime(); } } }, interruptionChecker, pathScanLog); // Filter out classpath elements that do not contain required whitelisted paths. if (!scanSpec.classpathElementResourcePathWhiteBlackList.whitelistIsEmpty()) { final List<ClasspathElement> classpathOrderFiltered = new ArrayList<>(classpathOrder.size()); for (final ClasspathElement classpathElement : classpathOrder) { if (classpathElement.containsSpecificallyWhitelistedClasspathElementResourcePath) { classpathOrderFiltered.add(classpathElement); } } classpathOrder = classpathOrderFiltered; } // Implement classpath masking -- if the same relative classfile path occurs multiple times in the // classpath, ignore (remove) the second and subsequent occurrences. Note that classpath masking is // performed whether or not a jar is whitelisted, and whether or not jar or dir scanning is enabled, // in order to ensure that class references passed into MatchProcessors are the same as those that // would be loaded by standard classloading. (See bug #100.) { final LogNode maskLog = topLevelLog == null ? null : topLevelLog.log("Masking classfiles"); final HashSet<String> nonBlacklistedClasspathRelativePathsFound = new HashSet<>(); final HashSet<String> whitelistedClasspathRelativePathsFound = new HashSet<>(); for (int classpathIdx = 0; classpathIdx < classpathOrder.size(); classpathIdx++) { classpathOrder.get(classpathIdx).maskClassfiles(classpathIdx, whitelistedClasspathRelativePathsFound, nonBlacklistedClasspathRelativePathsFound, maskLog); } } // Merge the maps from file to timestamp across all classpath elements (there will be no overlap in // keyspace, since file masking was already performed) final Map<File, Long> fileToLastModified = new HashMap<>(); for (final ClasspathElement classpathElement : classpathOrder) { fileToLastModified.putAll(classpathElement.fileToLastModified); } final Map<String, ClassInfo> classNameToClassInfo = new HashMap<>(); final Map<String, PackageInfo> packageNameToPackageInfo = new HashMap<>(); final Map<String, ModuleInfo> moduleNameToModuleInfo = new HashMap<>(); if (!scanSpec.enableClassInfo) { if (topLevelLog != null) { topLevelLog.log("Classfile scanning is disabled"); } } else { // Get whitelisted classfile order, and a map from class name to non-blacklisted classfile final List<ClassfileScanWorkUnit> classfileScanWorkItems = new ArrayList<>(); final Map<String, Resource> classNameToNonBlacklistedResource = new HashMap<>(); final Set<String> scannedClassNames = Collections .newSetFromMap(new ConcurrentHashMap<String, Boolean>()); for (final ClasspathElement classpathElement : classpathOrder) { // Get classfile scan order across all classpath elements for (final Resource resource : classpathElement.whitelistedClassfileResources) { classfileScanWorkItems.add(new ClassfileScanWorkUnit(classpathElement, resource, /* isExternal = */ false)); // Pre-seed scanned class names with all whitelisted classes (since these will // be scanned for sure) scannedClassNames.add(JarUtils.classfilePathToClassName(resource.getPath())); } // Get mapping from class name to Resource object for non-blacklisted classes // (these are used to scan superclasses, interfaces and annotations of whitelisted // classes that are not themselves whitelisted) for (final Resource resource : classpathElement.nonBlacklistedClassfileResources) { classNameToNonBlacklistedResource .put(JarUtils.classfilePathToClassName(resource.getPath()), resource); } } // Scan classfiles in parallel final ConcurrentLinkedQueue<ClassInfoUnlinked> classInfoUnlinkedQueue = new ConcurrentLinkedQueue<>(); final LogNode classfileScanLog = topLevelLog == null ? null : topLevelLog.log("Scanning classfiles"); WorkQueue.runWorkQueue(classfileScanWorkItems, executorService, numParallelTasks, new ClassfileScannerWorkUnitProcessor(scanSpec, classNameToNonBlacklistedResource, scannedClassNames, classInfoUnlinkedQueue, classfileScanLog, interruptionChecker), interruptionChecker, classfileScanLog); if (classfileScanLog != null) { classfileScanLog.addElapsedTime(); } // Build the class graph: convert ClassInfoUnlinked to linked ClassInfo objects. final LogNode classGraphLog = topLevelLog == null ? null : topLevelLog.log("Building class graph"); for (final ClassInfoUnlinked c : classInfoUnlinkedQueue) { c.link(scanSpec, classNameToClassInfo, packageNameToPackageInfo, moduleNameToModuleInfo, classGraphLog); } // Uncomment the following code to create placeholder external classes for any classes // referenced in type descriptors or type signatures, so that a ClassInfo object can be // obtained for those class references. This will cause all type descriptors and type // signatures to be parsed, and class names extracted from them. This will add some // overhead to the scanning time, and the only benefit is that // ClassRefTypeSignature.getClassInfo() and AnnotationClassRef.getClassInfo() will never // return null, since all external classes found in annotation class refs will have a // placeholder ClassInfo object created for them. This is obscure enough that it is // probably not worth slowing down scanning for all other usecases, by forcibly parsing // all type descriptors and type signatures before returning the ScanResult. // With this code commented out, type signatures and type descriptors are only parsed // lazily, on demand. // final Set<String> referencedClassNames = new HashSet<>(); // for (final ClassInfo classInfo : classNameToClassInfo.values()) { // classInfo.getClassNamesFromTypeDescriptors(referencedClassNames); // for (final String referencedClass : referencedClassNames) { // ClassInfo.getOrCreateClassInfo(referencedClass, /* modifiers = */ 0, scanSpec, // classNameToClassInfo); if (classGraphLog != null) { classGraphLog.addElapsedTime(); } } // Create ScanResult scanResult = new ScanResult(scanSpec, classpathOrder, rawClasspathEltOrderStrs, classLoaderOrder, classNameToClassInfo, packageNameToPackageInfo, moduleNameToModuleInfo, fileToLastModified, nestedJarHandler, topLevelLog); } if (topLevelLog != null) { topLevelLog.log("Completed", System.nanoTime() - scanStart); } // Run scanResultProcessor in the current thread if (scanResultProcessor != null) { try { scanResultProcessor.processScanResult(scanResult); } catch (final Throwable e) { throw new ExecutionException("Exception while calling scan result processor", e); } } // No exceptions were thrown -- return scan result return scanResult; } catch (final Throwable e) { // Remove temporary files if an exception was thrown nestedJarHandler.close(topLevelLog); if (topLevelLog != null) { topLevelLog.log(e); } if (failureHandler != null) { try { failureHandler.onFailure(e); // The return value is discarded when using a scanResultProcessor and failureHandler return null; } catch (final Throwable t) { throw new ExecutionException("Exception while calling failure handler", t); } } else { throw new ExecutionException("Exception while scanning", e); } } finally { if (scanSpec.removeTemporaryFilesAfterScan) { // If requested, remove temporary files and close zipfile/module recyclers nestedJarHandler.close(topLevelLog); } else { // Don't delete temporary files yet, but close zipfile/module recyclers nestedJarHandler.closeRecyclers(); } // Close ClasspathElement recyclers for (final ClasspathElement elt : classpathElementMap.values()) { if (elt != null) { elt.closeRecyclers(); } } if (topLevelLog != null) { topLevelLog.flush(); } } } }
package io.wovn.wovnjava; import java.io.IOException; import java.io.PrintWriter; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.parser.Tag; import us.codecraft.xsoup.Xsoup; class Interceptor { private Store store; Interceptor(FilterConfig config) { store = new Store(config); } void call(HttpServletRequest request, ServletResponse response, FilterChain chain) { if (!store.settings.isValid()) { try { chain.doFilter(request, response); } catch (ServletException e) { } catch (IOException e) { } return; } Headers h = new Headers(request, store.settings); if (store.settings.testMode && !store.settings.testUrl.equals(h.url)) { try { chain.doFilter(request, response); } catch (ServletException e) { } catch (IOException e) { } } if (h.getPathLang().equals(store.settings.defaultLang)) { try { ((HttpServletResponse) response).sendRedirect( h.redirectLocation(store.settings.defaultLang) ); } catch (IOException e) { } return; } WovnHttpServletResponse wovnResponse = new WovnHttpServletResponse( (HttpServletResponse)response, h ); try { chain.doFilter(request, wovnResponse); } catch (ServletException e) { } catch (IOException e) { } String body = wovnResponse.toString(); // There is a possibility that response.getContentType() is null when the response is an image. if (response.getContentType() != null && Pattern.compile("html").matcher(response.getContentType()).find()) { Values values = store.getValues(h.pageUrl); if (!String.valueOf(wovnResponse.status).matches("^1|302")) { String lang = h.langCode(); HashMap<String,String> url = new HashMap<String,String>(); url.put("protocol", h.protocol); url.put("host", h.host); url.put("pathname", h.pathName); body = this.switchLang(body, values, url, lang, h); wovnResponse.setContentLength(body.getBytes().length); } } try { PrintWriter out = response.getWriter(); out.write(body); out.close(); } catch (IOException e) { } h.out(request, wovnResponse); } private String addLangCode(String href, String pattern, String lang, Headers headers) { if (href != null && href.length() > 0 && href.matches("^( return href; } String newHref = href; if ( href != null && href.length() > 0 && Pattern.compile("^(https?:)?//", Pattern.CASE_INSENSITIVE).matcher(href).find() ) { URL uri; try { uri = new URL(href); } catch (MalformedURLException e) { return newHref; } if (uri.getHost().toLowerCase().equals(headers.host.toLowerCase())) { if (pattern.equals("subdomain")) { Matcher m = Pattern.compile("//([^\\.]*)\\.").matcher(href); String subCode = Lang.getCode(m.group(1)); if (subCode != null && subCode.length() > 0 && subCode.toLowerCase().equals(lang.toLowerCase()) ) { newHref = Pattern.compile(lang, Pattern.CASE_INSENSITIVE) .matcher(href) .replaceFirst(lang.toLowerCase()); } else { newHref = href.replaceFirst("(//)([^\\.]*)", "$1" + lang.toLowerCase() + ".$2"); } } else if (pattern.equals("query")) { if (href.matches("\\?")) { newHref = href + "&wovn=" + lang; } else { newHref = href + "?wovn=" + lang; } } else { newHref = href.replaceFirst("([^\\.]*\\.[^/]*)(/|$)", "$1/" + lang + "/"); } } } else if (href != null && href.length() > 0) { String currentDir; if (pattern.equals("subdomain")) { String langUrl = headers.protocol + "://" + lang.toLowerCase() + headers.host; currentDir = headers.pathName.replaceFirst("[^/]*\\.[^\\.]{2,6}$", ""); if (href.matches("^\\.\\..*$")) { newHref = langUrl + "/" + href.replaceAll("^\\.\\./", ""); } else if (href.matches("^\\..*$")) { newHref = langUrl + currentDir + "/" + href.replaceAll("^\\./", ""); } else if (href.matches("^/.*$")) { newHref = langUrl + href; } else { newHref = langUrl + currentDir + "/" + href; } } else if (pattern.equals("query")) { if (href.matches("\\?")) { newHref = href + "&wovn=" + lang; } else { newHref = href + "?wovn=" + lang; } } else { if (href.matches("^/")) { newHref = "/" + lang + href; } else { currentDir = headers.pathName.replaceFirst("[^/]*\\.[^\\.]{2,6}$", ""); newHref = "/" + lang + currentDir + href; } } } return newHref; } private boolean checkWovnIgnore(Element el) { if (el.hasAttr("wovn-ignore")) { return true; } else if (el.parent() == null) { return false; } return this.checkWovnIgnore(el.parent()); } private String switchLang(String body, Values values, HashMap<String, String> url, String lang, Headers headers) { lang = Lang.getCode(lang); Document doc = Jsoup.parse(body); if (Xsoup.compile("//html[@wovn-ignore]").evaluate(doc).get() != null) { return doc.html(); } if (!lang.equals(this.store.settings.defaultLang)) { for (Element el : Xsoup.compile("//a").evaluate(doc).getElements()) { if (this.checkWovnIgnore(el)) { continue; } String href = el.attr("href"); String newHref = this.addLangCode(href, this.store.settings.urlPattern, lang, headers); el.attr("href", newHref); } } for (Element el : Xsoup.compile("//*/text()").evaluate(doc).getElements()) { String nodeText = el.ownText(); if (nodeText == null || nodeText.length() == 0) { continue; } if (this.checkWovnIgnore(el)) { continue; } nodeText = Pattern.compile("^\\s+|\\s+$").matcher(nodeText).replaceAll(""); String destText = values.getText(nodeText, lang); if (destText != null) { String newText = Pattern.compile("^(\\s*)[\\S\\s]*(\\s*)$") .matcher(el.text()) .replaceAll("$1" + destText + "$2"); el.text(newText); } } Pattern p = Pattern.compile("^(description|title|og:title|og:description|twitter:title|twitter:description)$"); for (Element el : Xsoup.compile("//meta").evaluate(doc).getElements()) { if (this.checkWovnIgnore(el)) { continue; } if ( !(el.hasAttr("name") && p.matcher(el.attr("name")).find()) && !(el.hasAttr("property") && p.matcher(el.attr("name")).find()) ) { continue; } String nodeContent = el.attr("content"); if (nodeContent == null) { continue; } nodeContent = Pattern.compile("^\\s+|\\s+$").matcher(nodeContent).replaceAll(""); if (nodeContent.length() == 0) { continue; } String destContent = values.getText(nodeContent, lang); if (destContent != null) { String newContent = Pattern.compile("^(\\s*)[\\S\\s]*(\\s*)$") .matcher(nodeContent) .replaceAll("$1" + destContent + "$2"); el.attr("content", newContent); } } for (Element el : Xsoup.compile("//img").evaluate(doc).getElements()) { if (this.checkWovnIgnore(el)) { continue; } Matcher m = Pattern.compile("src=['\"]([^'\"]*)['\"]", Pattern.CASE_INSENSITIVE) .matcher(el.outerHtml()); if (m.find()) { String src = m.group(1); if (!Pattern.compile("://").matcher(src).find()) { if (Pattern.compile("^/").matcher(src).find()) { src = url.get("protocol") + "://" + url.get("host") + src; } else { src = url.get("protocol") + "://" + url.get("host") + url.get("path") + src; } } String destSrc = values.getImage(src, lang); if (destSrc != null) { el.attr("src", destSrc); } } if (el.hasAttr("alt")) { String alt = el.attr("alt"); alt = Pattern.compile("^\\s+|\\s+$").matcher(alt).replaceAll(""); String destAlt = values.getText(alt, lang); if (destAlt != null) { String newAlt = Pattern.compile("^(\\s*)[\\S\\s]*(\\s*)$") .matcher(alt) .replaceAll("$1" + destAlt + "$2"); el.attr("alt", newAlt); } } } for (Element el : Xsoup.compile("//script").evaluate(doc).getElements()) { if ( el.hasAttr("src") && Pattern.compile("//j\\.(dev-)?wovn\\.io(:3000)?/").matcher(el.attr("src")).find() ) { el.remove(); } } Element parentNode = doc.head(); if (parentNode == null) { parentNode = doc.body(); } if (parentNode == null) { parentNode = doc; } Element insertNode = new Element(Tag.valueOf("script"), ""); insertNode.attr("src", "//j.wovn.io/1"); insertNode.attr("async", true); String version = WovnServletFilter.VERSION; insertNode.attr( "data-wovnio", "key=" + this.store.settings.userToken + "&backend=true&currentLang=" + lang + "&defaultLang=" + this.store.settings.defaultLang + "&urlPattern=" + this.store.settings.urlPattern + "&version=" + version ); insertNode.text(" "); parentNode.prependChild(insertNode); for (String l : values.getLangs()) { insertNode = new Element(Tag.valueOf("link"), ""); insertNode.attr("ref", "altername"); insertNode.attr("hreflang", l); insertNode.attr("href", headers.redirectLocation(l)); parentNode.appendChild(insertNode); } Xsoup.compile("//html").evaluate(doc).getElements().first().attr("lang", lang); return doc.html(); } }
package jasper; import java.io.DataInputStream; import java.io.IOException; /** * Holds attributes that do not contribute to the disassembly, * such as stack map. * * @author Kohsuke Kawaguchi */ public class KnownIgnoredAttribute extends Attribute { public KnownIgnoredAttribute(DataInputStream ios, Pool_Collection pool, int attributeIndex) throws IOException { super(ios, pool, attributeIndex); ios.readFully(new byte[length]); } }
package jp.co.bizreach.camp; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.commons.mail.EmailConstants; import org.apache.commons.mail.EmailException; import org.apache.commons.mail.HtmlEmail; import org.springframework.stereotype.Component; import java.io.File; import java.util.Arrays; import java.util.List; /** * @author david.genesis.cruz * */ @Component public class SendMail { private static final Log log = LogFactory.getLog(SendMail.class); private HtmlEmail email = new HtmlEmail(); // account setup private static final String hostName = "smtp.gmail.com"; private static final int smtpPort = 587; private static final String userName = "luntiang.pentakulo@gmail.com"; private static final String password = System.getProperty("smtpPasswd"); private static final String fromEmail = "luntiang.pentakulo@gmail.com"; private static final String fromName = ""; // email contents private static final String toEmail = "david.genesis.cruz@bizreach.co.jp"; private static final List<String> toEmails = Arrays.asList(new String[]{ "ken.toriumi@bizreach.co.jp", "david.genesis.cruz@bizreach.co.jp", "kyunbum.yi@bizreach.co.jp", "akane.sutou@bizreach.co.jp", "hongseok.jeong@bizreach.co.jp", "misawa@bizreach.co.jp", "hayato.nakamura@bizreach.co.jp", "kota.inoue@bizreach.co.jp", "even.he@bizreach.co.jp", "akifumi.tominaga@bizreach.co.jp", "katsumaru@bizreach.co.jp", "kazuhiro.yoshimoto@bizreach.co.jp", "hori@bizreach.co.jp", "tomoya.masuri@bizreach.co.jp", "junya.masuda@bizreach.co.jp", "masayuki.ouchi@bizreach.co.jp", "yuki.ohnishi@bizreach.co.jp", "kyota.yasuda@bizreach.co.jp", "masaki.ogawa@bizreach.co.jp", "kosuke.obata@bizreach.co.jp", "tomoki.iwai@bizreach.co.jp", "kazuya.hirota@bizreach.co.jp", "daisuke.megumi@bizreach.co.jp", "sotsuka@bizreach.co.jp", "aram.park@bizreach.co.jp", "ayumi.toukairin@bizreach.co.jp", "koichiro.matsuoka@bizreach.co.jp", "yuta.yokoo@bizreach.co.jp", "yuuki.ikehata@bizreach.co.jp", "kouchi@bizreach.co.jp", "akira.tsuno@bizreach.co.jp", "daisuke.sei@bizreach.co.jp", "yu.watanabe@bizreach.co.jp", "sawaguchi@bizreach.co.jp", "mashiko@bizreach.co.jp", "yuta.ishizaka@bizreach.co.jp", "shinji.sogawa@bizreach.co.jp", "yuuta.inoo@bizreach.co.jp", "takayuki.takemura@bizreach.co.jp", "satoshi.tanaka@bizreach.co.jp", "toshiaki.arai@bizreach.co.jp", "masaki.kamachi@bizreach.co.jp", "shouta.fujino@bizreach.co.jp", "junpei.nishina@bizreach.co.jp", "jumpei.toyoda@bizreach.co.jp", "tatsuhiro.gunji@bizreach.co.jp", "mayuko.sakaba@bizreach.co.jp", "keisuke.shigematsu@bizreach.co.jp", "suzuki@bizreach.co.jp", "yuuki.nagahara@bizreach.co.jp", "yasuhiro.sakamoto@bizreach.co.jp", "takakura@bizreach.co.jp", "kohei.takata@bizreach.co.jp", "shuichiro.washio@bizreach.co.jp", "hiroki.saito@bizreach.co.jp" }); private static final String subject = ""; private static final String mailGreeting = ""; private static final String mailHeader = ""; private static final String mailFooter = ""; /** * @param file */ public void send(File file) { log.info("setting up email account..."); setupEmailAccount(); log.info("creating email body..."); if (file.exists()) { createEmail(file); log.info("sending mail..."); try { email.send(); log.info("mail sent!"); } catch (EmailException e) { log.error("failed to send mail: " + email, e); } } else { log.error("attachment is null."); } } private void setupEmailAccount() { email.setHostName(hostName); email.setSmtpPort(smtpPort); email.setSslSmtpPort(String.valueOf(smtpPort)); email.setStartTLSEnabled(true); email.setAuthentication(userName, password); email.setSSLOnConnect(true); try { email.setFrom(fromEmail, fromName); } catch (EmailException e) { log.error("failed to set FROM address:" + fromEmail, e); } } private void createEmail(File file) { try { email.addTo(toEmail); // for (String toEmail : toEmails) { // email.addTo(toEmail); } catch (EmailException e) { log.error("failed to set TO: " + toEmail, e); } email.setSubject(subject); createEmailBody(file); } private void createEmailBody(File file) { String cid = embedImage(file); String mailBody = buildHtmlBody(cid); email.setCharset(EmailConstants.UTF_8); try { email.setHtmlMsg(mailBody); } catch (EmailException e) { log.error("failed to create email body: " + mailBody, e); } } private String buildHtmlBody(String cid) { String htmlOpenTags = "<html><body>"; String htmlCloseTags = "</body></html>"; String image = htmlCreateImageUrl("cid:" + cid); String signature = htmlBold(fromName); String htmlBody = htmlOpenTags + mailGreeting + htmlNewLine(3) + mailHeader + htmlNewLine(1) + image + htmlNewLine(1) + mailFooter + htmlNewLine(2) + signature + htmlCloseTags; return htmlBody; } private String embedImage(File file) { String cid = new String(); try { log.info("attaching file: " + file); cid = email.embed(file); } catch (EmailException e) { log.error("failed to attach image: " + file.getPath(), e); } return cid; } // HTML helpers private String htmlCreateImageUrl(String src) { String imageOpenTag = "<img src="; String imageCloseTag = ">"; return imageOpenTag + src + imageCloseTag; } private String htmlBold(String string) { String htmlStrongOpenTag = "<strong>"; String htmlStrongCloseTag = "</strong>"; return htmlStrongOpenTag + string + htmlStrongCloseTag; } private String htmlNewLine(int count) { StringBuilder builder = new StringBuilder(); for (int i = 0; i <= count; i++) { builder.append("<br>"); } return builder.toString(); } }
package jp.gecko655.bot; import java.io.IOException; import java.io.InputStream; import java.net.ConnectException; import java.net.HttpURLConnection; import java.net.URL; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import twitter4j.Status; import twitter4j.StatusUpdate; import twitter4j.Twitter; import twitter4j.TwitterException; import twitter4j.TwitterFactory; import twitter4j.conf.ConfigurationBuilder; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.services.customsearch.Customsearch; import com.google.api.services.customsearch.model.Result; import com.google.api.services.customsearch.model.Search; public abstract class AbstractCron implements Job{ static protected Logger logger = Logger.getLogger("Fujimiya"); static String consumerKey = System.getenv("consumerKey"); static String consumerSecret = System.getenv("consumerSecret"); static String accessToken = System.getenv("accessToken"); static String accessTokenSecret = System.getenv("accessTokenSecret"); static String customSearchCx = System.getenv("customSearchCx"); static String customSearchKey = System.getenv("customSearchKey"); static protected Twitter twitter; static Customsearch.Builder builder = new Customsearch.Builder(new NetHttpTransport(), new JacksonFactory(), null).setApplicationName("Google"); //$NON-NLS-1$ static Customsearch search = builder.build(); public AbstractCron() { logger.setLevel(Level.FINE); } @Override public void execute(JobExecutionContext context) throws JobExecutionException { ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true) .setOAuthAccessToken(accessToken) .setOAuthAccessTokenSecret(accessTokenSecret) .setOAuthConsumerKey(consumerKey) .setOAuthConsumerSecret(consumerSecret); twitter = new TwitterFactory(cb.build()).getInstance(); twitterCron(); } /** * Search fujimiya-san's image and return the url. * The return is randomly picked up from the 100 result of google image search. * @param query * @return */ FetchedImage getFujimiyaUrl(String query){ return getFujimiyaUrl(query,100); } /** * Search fujimiya-san's image and return the url. * The return is randomly picked up from the maxRankOfResult result of google image search. * @param query * @param maxRankOfResult * @return */ FetchedImage getFujimiyaUrl(String query,int maxRankOfResult){ try{ //Get SearchResult Search search = getSearchResult(query, maxRankOfResult); List<Result> items = search.getItems(); for(int i=0;i<10;i++){ Result result = items.get(i); logger.log(Level.INFO,"query: " + query + " URL: "+result.getLink()); logger.log(Level.INFO,"page URL: "+result.getImage().getContextLink()); if(result.getImage().getWidth()+result.getImage().getHeight()<600){ logger.log(Level.INFO,"Result No."+i+" is too small image. next."); continue; } if(DBConnection.isInBlackList(result.getLink())){ logger.log(Level.INFO,"Result No."+i+" is included in the blacklist. next."); continue; } HttpURLConnection connection = (HttpURLConnection)(new URL(result.getLink())).openConnection(); connection.setRequestMethod("GET"); connection.setInstanceFollowRedirects(false); connection.connect(); if(connection.getResponseCode()==200){ return new FetchedImage(connection.getInputStream(),result.getLink()); }else{ logger.log(Level.INFO,"Result No."+i+" occurs error while fetching the image. next."); continue; } } //If execution comes here, connection has failed 10 times. throw new ConnectException("Connection failed 10 times"); } catch (IOException e) { // TODO Auto-generated catch block logger.log(Level.SEVERE,e.toString()); e.printStackTrace(); } return null; } static private int pageSize = 10; private Search getSearchResult(String query, int maxRankOfResult) throws IOException { if(maxRankOfResult>100-pageSize+1) maxRankOfResult=100-pageSize+1; Customsearch.Cse.List list = search.cse().list(query); list.setCx(customSearchCx); list.setKey(customSearchKey); list.setSearchType("image"); list.setNum((long)pageSize); long rand = (long)(Math.random()*maxRankOfResult+1); list.setStart(rand); logger.log(Level.INFO,"rand: "+rand); return list.execute(); } protected void updateStatusWithMedia(StatusUpdate update, String query, int maxRankOfResult){ FetchedImage fetchedImage = getFujimiyaUrl(query,maxRankOfResult); update.media("fujimiya.jpg",fetchedImage.getInputStream()); for(int i=0;i<10;i++){ try{ Status succeededStatus = twitter.updateStatus(update); logger.log(Level.INFO,"Successfully tweeted: "+succeededStatus.getText()); DBConnection.storeImageUrl(succeededStatus,fetchedImage); return; }catch(TwitterException e){ logger.log(Level.INFO,"updateStatusWithMedia failed. try again. "+ e.getErrorMessage()); } } logger.log(Level.SEVERE,"updateStatusWithMedia failed 10 times. Stop."); } abstract protected void twitterCron(); } class FetchedImage{ private InputStream in; private String url; public FetchedImage(InputStream in, String url) { this.in = in; this.url = url; } public InputStream getInputStream() { return in; } public String getUrl() { return url; } }
package net.atomcode.bearing; import android.content.Context; import android.location.LocationManager; import net.atomcode.bearing.geocoding.GeocodingTask; import net.atomcode.bearing.geocoding.GeocodingTaskListener; import net.atomcode.bearing.geocoding.ReverseGeocodingTask; import net.atomcode.bearing.location.Accuracy; import net.atomcode.bearing.location.CurrentLocationListener; import net.atomcode.bearing.location.CurrentLocationTask; /** * Entry class for Bearing library. Has functions for all major actions */ public class Bearing { /** * Geocode query into latitude and longitude * @param context The context of the request * @param query The string queried * @param listener The listener to call back to */ public static void getAddressListForQuery(Context context, String query, GeocodingTaskListener listener) { GeocodingTask geocodingTask = new GeocodingTask(context); geocodingTask.setGeocodingTaskListener(listener); geocodingTask.execute(query); } /** * Reverse geocode the location into an address * @param context The context of the request * @param latitude The latitude to lookup * @param longitude The longitude to check * @param listener The listener to call back to */ public static void getAddressListForLocation(Context context, Double latitude, Double longitude, GeocodingTaskListener listener) { ReverseGeocodingTask geocodingTask = new ReverseGeocodingTask(context); geocodingTask.setGeocodingTaskListener(listener); geocodingTask.execute(latitude, longitude); } /** * Get the current location of the user to the given accuracy * @param context The context of the request * @param accuracy The accuracy to which the users location should match. * @param listener The listener to call back to */ public static void getCurrentLocation(Context context, Accuracy accuracy, CurrentLocationListener listener) { CurrentLocationTask currentLocationTask = new CurrentLocationTask(context); currentLocationTask.setCurrentLocationListener(listener); currentLocationTask.execute(accuracy); } /** * Get the current location of the user to the closest 50 metres. * @param context The context of the request * @param listener The listener to call back to */ public static void getCurrentLocation(Context context, CurrentLocationListener listener) { getCurrentLocation(context, Accuracy.MEDIUM, listener); } public static boolean isLocationServicesAvailable(Context context) { if (context == null) { throw new IllegalArgumentException("Context cannot be null on Bearing.isLocationServicesAvailable call"); } LocationManager lm = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE); boolean gps_enabled; boolean network_enabled; try { gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER); if (gps_enabled) return true; } catch(Exception ex) { // Ignore } try { network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER); if (network_enabled) return true; } catch(Exception ex) { // Ignore } return false; } }
package net.trajano.auth; import static net.trajano.auth.internal.OAuthParameters.CLIENT_ID; import static net.trajano.auth.internal.OAuthParameters.CODE; import static net.trajano.auth.internal.OAuthParameters.GRANT_TYPE; import static net.trajano.auth.internal.OAuthParameters.REDIRECT_URI; import static net.trajano.auth.internal.OAuthParameters.RESPONSE_TYPE; import static net.trajano.auth.internal.OAuthParameters.SCOPE; import static net.trajano.auth.internal.OAuthParameters.STATE; import static net.trajano.auth.internal.Utils.isGetRequest; import static net.trajano.auth.internal.Utils.isHeadRequest; import static net.trajano.auth.internal.Utils.isNullOrEmpty; import static net.trajano.auth.internal.Utils.isRetrievalRequest; import static net.trajano.auth.internal.Utils.validateIdToken; import java.io.ByteArrayInputStream; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URI; import java.security.GeneralSecurityException; import java.text.MessageFormat; import java.util.Map; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; import javax.crypto.SecretKey; import javax.json.Json; import javax.json.JsonObject; import javax.security.auth.Subject; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.callback.UnsupportedCallbackException; import javax.security.auth.message.AuthException; import javax.security.auth.message.AuthStatus; import javax.security.auth.message.MessageInfo; import javax.security.auth.message.MessagePolicy; import javax.security.auth.message.callback.CallerPrincipalCallback; import javax.security.auth.message.callback.GroupPrincipalCallback; import javax.security.auth.message.config.ServerAuthContext; import javax.security.auth.message.module.ServerAuthModule; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.BadRequestException; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedHashMap; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriBuilder; import net.trajano.auth.internal.Base64; import net.trajano.auth.internal.CipherUtil; import net.trajano.auth.internal.JsonWebKeySet; import net.trajano.auth.internal.OAuthToken; import net.trajano.auth.internal.OpenIDProviderConfiguration; import net.trajano.auth.internal.TokenCookie; import net.trajano.auth.internal.Utils; public abstract class OAuthModule implements ServerAuthModule, ServerAuthContext { /** * Access token attribute name. */ public static final String ACCESS_TOKEN_KEY = "auth_access"; /** * Client ID option key and JSON key. */ public static final String CLIENT_ID_KEY = "client_id"; /** * Client secret option key and JSON key. */ public static final String CLIENT_SECRET_KEY = "client_secret"; /** * Cookie context option key. The value is optional. */ public static final String COOKIE_CONTEXT_KEY = "cookie_context"; /** * https prefix. */ private static final String HTTPS_PREFIX = "https: /** * Open ID token attribute name. */ public static final String ID_TOKEN_KEY = "auth_idtoken"; /** * Logger. */ private static final Logger LOG; /** * Logger for configuration. */ private static final Logger LOGCONFIG; /** * Messages resource path. */ private static final String MESSAGES = "META-INF/Messages"; /** * Age cookie name. The value of this cookie is an encrypted version of the * IP Address and will expire based on the max age of the token. */ public static final String NET_TRAJANO_AUTH_AGE = "net.trajano.auth.age"; /** * ID token cookie name. This one expires when the browser closes. */ public static final String NET_TRAJANO_AUTH_ID = "net.trajano.auth.id"; /** * Resource bundle. */ private static final ResourceBundle R; /** * Redirection endpoint URI key. The value is optional and defaults to the * context root of the application. */ public static final String REDIRECTION_ENDPOINT_URI_KEY = "redirection_endpoint"; //$NON-NLS-1$ /** * Refresh token attribute name. */ public static final String REFRESH_TOKEN_KEY = "auth_refresh"; /** * Scope option key. The value is optional and defaults to "openid" */ public static final String SCOPE_KEY = "scope"; /** * Token URI key. The value is optional and if not specified, the token * request functionality will not be available. */ public static final String TOKEN_URI_KEY = "token_uri"; /** * User info attribute name. */ public static final String USERINFO_KEY = "auth_userinfo"; /** * User Info URI key. The value is optional and if not specified, the * userinfo request functionality will not be available. */ public static final String USERINFO_URI_KEY = "userinfo_uri"; static { LOG = Logger.getLogger("net.trajano.auth.oauthsam", MESSAGES); LOGCONFIG = Logger.getLogger("net.trajano.auth.oauthsam.config", MESSAGES); R = ResourceBundle.getBundle(MESSAGES); } /** * Client ID. This is set through "client.id" option. */ private String clientId; /** * Client secret. This is set through "client.secret" option. */ private String clientSecret; /** * Cookie context path. Set through through "cookie.context" option. This is * optional. */ private String cookieContext; /** * Callback handler. */ private CallbackHandler handler; /** * Flag to indicate that authentication is mandatory. */ private boolean mandatory; /** * Options for the module. */ private Map<String, String> moduleOptions; /** * Redirection endpoint URI. This is set through "redirection_endpoint" * option. This must start with a forward slash. This value is optional. */ private String redirectionEndpointUri; /** * REST Client. This is not final so a different one can be put in for * testing. */ private Client restClient = ClientBuilder.newClient(); /** * Scope. */ private String scope; /** * Secret key used for module level ciphers. */ private SecretKey secret; /** * Token URI. This is set through "token_uri" option. This must start with a * forward slash. This value is optional. The calling the token URI will * return the contents of the JWT token object to the user. Make sure that * this is intended before setting the value. */ private String tokenUri; /** * User info URI. This is set through "userinfo_uri" option. This must start * with a forward slash. This value is optional. The calling the user info * URI will return the contents of the user info object to the user. Make * sure that this is intended before setting the value. */ private String userInfoUri; /** * Does nothing. * * @param messageInfo * message info * @param subject * subject */ @Override public void cleanSubject(final MessageInfo messageInfo, final Subject subject) throws AuthException { // Does nothing. } /** * Client ID. * * @return the client ID. */ protected String getClientId() { return clientId; } /** * Client Secret. * * @return the client secret. */ protected String getClientSecret() { return clientSecret; } /** * Gets the ID token. This ensures that both cookies are present, if not * then this will return <code>null</code>. * * @param req * HTTP servlet request * @return ID token * @throws GeneralSecurityException * @throws IOException */ private String getIdToken(final HttpServletRequest req) throws GeneralSecurityException, IOException { final Cookie[] cookies = req.getCookies(); if (cookies == null) { return null; } String idToken = null; boolean foundAge = false; for (final Cookie cookie : cookies) { if (NET_TRAJANO_AUTH_ID.equals(cookie.getName()) && !isNullOrEmpty(cookie.getValue())) { idToken = cookie.getValue(); } else if (NET_TRAJANO_AUTH_AGE.equals(cookie.getName())) { final String remoteAddr = req.getRemoteAddr(); final String cookieAddr = new String(CipherUtil.decrypt(Base64.decode(cookie.getValue()), secret), "US-ASCII"); if (!remoteAddr.equals(cookieAddr)) { throw new AuthException(MessageFormat.format(R.getString("ipaddressMismatch"), remoteAddr, cookieAddr)); } foundAge = true; } if (idToken != null && foundAge) { return idToken; } } return idToken; } /** * Lets subclasses change the provider configuration. * * @param client * REST client * @param options * module options * @return configuration * @throws AuthException * wraps exceptions thrown during processing */ protected abstract OpenIDProviderConfiguration getOpenIDProviderConfig(Client client, Map<String, String> options) throws AuthException; /** * This gets the redirection endpoint URI. It uses the * {@link #REDIRECTION_ENDPOINT_URI_KEY} option resolved against the request * URL to get the host name. * * @param req * request * @return redirection endpoint URI. */ protected URI getRedirectionEndpointUri(final HttpServletRequest req) { return URI.create(req.getRequestURL() .toString()) .resolve(redirectionEndpointUri); } /** * Gets an option and ensures it is present. * * @param optionKey * option key * @return the option value * @throws AuthException * missing option exception */ private String getRequiredOption(final String optionKey) throws AuthException { final String optionValue = moduleOptions.get(optionKey); if (optionValue == null) { LOG.log(Level.SEVERE, "missingOption", optionKey); throw new AuthException(MessageFormat.format(R.getString("missingOption"), optionKey)); } return optionValue; } /** * REST client. * * @return REST client */ protected Client getRestClient() { return restClient; } /** * <p> * Supported message types. For our case we only need to deal with HTTP * servlet request and responses. On Java EE 7 this will handle WebSockets * as well. * </p> * <p> * This creates a new array for security at the expense of performance. * </p> * * @return {@link HttpServletRequest} and {@link HttpServletResponse} * classes. */ @SuppressWarnings("rawtypes") @Override public Class[] getSupportedMessageTypes() { return new Class<?>[] { HttpServletRequest.class, HttpServletResponse.class }; } /** * Sends a request to the token endpoint to get the token for the code. * * @param req * servlet request * @param oidProviderConfig * OpenID provider config * @return token response */ protected OAuthToken getToken(final HttpServletRequest req, final OpenIDProviderConfiguration oidProviderConfig) throws IOException { final MultivaluedMap<String, String> requestData = new MultivaluedHashMap<>(); requestData.putSingle(CODE, req.getParameter("code")); requestData.putSingle(GRANT_TYPE, "authorization_code"); requestData.putSingle(REDIRECT_URI, getRedirectionEndpointUri(req).toASCIIString()); try { final String authorization = "Basic " + Base64.encode((clientId + ":" + clientSecret).getBytes("UTF8")); final OAuthToken authorizationTokenResponse = restClient.target(oidProviderConfig.getTokenEndpoint()) .request(MediaType.APPLICATION_JSON_TYPE) .header("Authorization", authorization) .post(Entity.form(requestData), OAuthToken.class); if (LOG.isLoggable(Level.FINEST)) { LOG.finest("authorization token response = " + authorizationTokenResponse); } return authorizationTokenResponse; } catch (final BadRequestException e) { // workaround for google that does not support BASIC authentication // on their endpoint. requestData.putSingle(CLIENT_ID, clientId); requestData.putSingle(CLIENT_SECRET_KEY, clientSecret); final OAuthToken authorizationTokenResponse = restClient.target(oidProviderConfig.getTokenEndpoint()) .request(MediaType.APPLICATION_JSON_TYPE) .post(Entity.form(requestData), OAuthToken.class); if (LOG.isLoggable(Level.FINEST)) { LOG.finest("authorization token response = " + authorizationTokenResponse); } return authorizationTokenResponse; } } /** * Gets the web keys from the options and the OpenID provider configuration. * This may be overridden by clients. * * @param options * module options * @param config * provider configuration * @return web keys * @throws GeneralSecurityException * wraps exceptions thrown during processing */ protected JsonWebKeySet getWebKeys(final Map<String, String> options, final OpenIDProviderConfiguration config) throws GeneralSecurityException { return new JsonWebKeySet(restClient.target(config.getJwksUri()) .request(MediaType.APPLICATION_JSON_TYPE) .get(JsonObject.class)); } private String googleWorkaround(final String issuer) { if (issuer.startsWith(HTTPS_PREFIX)) { return issuer; } return HTTPS_PREFIX + issuer; } /** * Handles the callback. * * @param req * servlet request * @param resp * servlet response * @param subject * user subject * @return status * @throws GeneralSecurityException */ private AuthStatus handleCallback(final HttpServletRequest req, final HttpServletResponse resp, final Subject subject) throws GeneralSecurityException, IOException { final OpenIDProviderConfiguration oidProviderConfig = getOpenIDProviderConfig(restClient, moduleOptions); final OAuthToken token = getToken(req, oidProviderConfig); final JsonWebKeySet webKeys = getWebKeys(moduleOptions, oidProviderConfig); LOG.log(Level.FINEST, "tokenValue", token); final JsonObject claimsSet = Json.createReader(new ByteArrayInputStream(Utils.getJwsPayload(token.getIdToken(), webKeys))) .readObject(); validateIdToken(clientId, claimsSet); final String iss = googleWorkaround(claimsSet.getString("iss")); final String issuer = googleWorkaround(oidProviderConfig.getIssuer()); if (!iss.equals(issuer)) { LOG.log(Level.SEVERE, "issuerMismatch", new Object[] { iss, issuer }); throw new GeneralSecurityException(MessageFormat.format(R.getString("issuerMismatch"), iss, issuer)); } updateSubjectPrincipal(subject, claimsSet); final TokenCookie tokenCookie; if (oidProviderConfig.getUserinfoEndpoint() != null && Pattern.compile("\\bprofile\\b") .matcher(scope) .find()) { final Response userInfoResponse = restClient.target(oidProviderConfig.getUserinfoEndpoint()) .request(MediaType.APPLICATION_JSON_TYPE) .header("Authorization", token.getTokenType() + " " + token.getAccessToken()) .get(); if (userInfoResponse.getStatus() == 200) { tokenCookie = new TokenCookie(token.getAccessToken(), token.getRefreshToken(), claimsSet, userInfoResponse.readEntity(JsonObject.class)); } else { LOG.log(Level.WARNING, "unableToGetProfile"); tokenCookie = new TokenCookie(claimsSet); } } else { tokenCookie = new TokenCookie(claimsSet); } final String requestCookieContext; if (isNullOrEmpty(cookieContext)) { requestCookieContext = req.getContextPath(); } else { requestCookieContext = cookieContext; } final Cookie idTokenCookie = new Cookie(NET_TRAJANO_AUTH_ID, tokenCookie.toCookieValue(clientId, clientSecret)); idTokenCookie.setMaxAge(-1); idTokenCookie.setSecure(true); idTokenCookie.setPath(requestCookieContext); resp.addCookie(idTokenCookie); final Cookie ageCookie = new Cookie(NET_TRAJANO_AUTH_AGE, Base64.encodeWithoutPadding(CipherUtil.encrypt(req.getRemoteAddr() .getBytes("US-ASCII"), secret))); if (isNullOrEmpty(req.getParameter("expires_in"))) { ageCookie.setMaxAge(3600); } else { ageCookie.setMaxAge(Integer.parseInt(req.getParameter("expires_in"))); } ageCookie.setPath(requestCookieContext); idTokenCookie.setSecure(true); resp.addCookie(ageCookie); final String stateEncoded = req.getParameter("state"); final String redirectUri = new String(Base64.decode(stateEncoded)); resp.sendRedirect(resp.encodeRedirectURL(redirectUri)); return AuthStatus.SEND_SUCCESS; } /** * {@inheritDoc} * * @param requestPolicy * request policy, ignored * @param responsePolicy * response policy, ignored * @param h * callback handler * @param options * options */ @SuppressWarnings("unchecked") @Override public void initialize(final MessagePolicy requestPolicy, final MessagePolicy responsePolicy, final CallbackHandler h, @SuppressWarnings("rawtypes") final Map options) throws AuthException { try { moduleOptions = options; clientId = getRequiredOption(CLIENT_ID_KEY); cookieContext = moduleOptions.get(COOKIE_CONTEXT_KEY); redirectionEndpointUri = getRequiredOption(REDIRECTION_ENDPOINT_URI_KEY); tokenUri = moduleOptions.get(TOKEN_URI_KEY); userInfoUri = moduleOptions.get(USERINFO_URI_KEY); scope = moduleOptions.get(SCOPE_KEY); if (isNullOrEmpty(scope)) { scope = "openid"; } clientSecret = getRequiredOption(CLIENT_SECRET_KEY); LOGCONFIG.log(Level.CONFIG, "options", moduleOptions); handler = h; mandatory = requestPolicy.isMandatory(); secret = CipherUtil.buildSecretKey(clientId, clientSecret); } catch (final Exception e) { // Should not happen LOG.log(Level.SEVERE, "initializeException", e); throw new AuthException(MessageFormat.format(R.getString("initializeException"), e.getMessage())); } } /** * Checks to see whether the {@link ServerAuthModule} is called by the * resource owner. This is indicated by the presence of a <code>code</code> * and a <code>state</code> on the URL and is an idempotent request (i.e. * GET or HEAD). The resource owner would be a web browser that got a * redirect sent by the OAuth 2.0 provider. * * @param req * HTTP servlet request * @return the module is called by the resource owner. */ public boolean isCallback(final HttpServletRequest req) { return moduleOptions.get(REDIRECTION_ENDPOINT_URI_KEY) .equals(req.getRequestURI()) && isRetrievalRequest(req) && !isNullOrEmpty(req.getParameter(CODE)) && !isNullOrEmpty(req.getParameter(STATE)); } /** * Builds the token cookie and updates the subject principal and sets the * token and user info attribute in the request. Any exceptions or * validation problems during validation will make this return * <code>null</code> to indicat that there was no valid token. * * @param subject * subject * @param req * servlet request * @return token cookie. */ private TokenCookie processTokenCookie(final Subject subject, final HttpServletRequest req) { try { final String idToken = getIdToken(req); TokenCookie tokenCookie = null; if (idToken != null) { tokenCookie = new TokenCookie(idToken, clientId, clientSecret); validateIdToken(clientId, tokenCookie.getIdToken()); updateSubjectPrincipal(subject, tokenCookie.getIdToken()); req.setAttribute(ACCESS_TOKEN_KEY, tokenCookie.getAccessToken()); req.setAttribute(REFRESH_TOKEN_KEY, tokenCookie.getRefreshToken()); req.setAttribute(ID_TOKEN_KEY, tokenCookie.getIdToken()); if (tokenCookie.getUserInfo() != null) { req.setAttribute(USERINFO_KEY, tokenCookie.getUserInfo()); } } return tokenCookie; } catch (final GeneralSecurityException | IOException e) { LOG.log(Level.FINE, "invalidToken", e.getMessage()); LOG.throwing(this.getClass() .getName(), "validateRequest", e); return null; } } /** * Sends a redirect to the authorization endpoint. It sends the current * request URI as the state so that the user can be redirected back to the * last place. However, this does not work for non-idempotent requests such * as POST in those cases it will result in a 401 error and * {@link AuthStatus#SEND_FAILURE}. For idempotent requests, it will build * the redirect URI and return {@link AuthStatus#SEND_CONTINUE}. * * @param req * HTTP servlet request * @param resp * HTTP servlet response * @return authentication status * @throws AuthException */ private AuthStatus redirectToAuthorizationEndpoint(final HttpServletRequest req, final HttpServletResponse resp) throws AuthException { URI authorizationEndpointUri = null; try { final OpenIDProviderConfiguration oidProviderConfig = getOpenIDProviderConfig(restClient, moduleOptions); restClient.close(); final String state = Base64.encodeWithoutPadding(req.getRequestURI() .getBytes("UTF-8")); authorizationEndpointUri = UriBuilder.fromUri(oidProviderConfig.getAuthorizationEndpoint()) .queryParam(CLIENT_ID, clientId) .queryParam(RESPONSE_TYPE, "code") .queryParam(SCOPE, scope) .queryParam(REDIRECT_URI, URI.create(req.getRequestURL() .toString()) .resolve(moduleOptions.get(REDIRECTION_ENDPOINT_URI_KEY))) .queryParam(STATE, state) .build(); resp.sendRedirect(authorizationEndpointUri.toASCIIString()); return AuthStatus.SEND_CONTINUE; } catch (final IOException e) { // Should not happen LOG.log(Level.SEVERE, "sendRedirectException", new Object[] { authorizationEndpointUri, e.getMessage() }); LOG.throwing(this.getClass() .getName(), "redirectToAuthorizationEndpoint", e); throw new AuthException(MessageFormat.format(R.getString("sendRedirectException"), authorizationEndpointUri, e.getMessage())); } } /** * Return {@link AuthStatus#SEND_SUCCESS}. * * @param messageInfo * contains the request and response messages. At this point the * response message is already committed so nothing can be * changed. * @param subject * subject. * @return {@link AuthStatus#SEND_SUCCESS} */ @Override public AuthStatus secureResponse(final MessageInfo messageInfo, final Subject subject) throws AuthException { return AuthStatus.SEND_SUCCESS; } /** * Override REST client for testing. * * @param restClient * REST client. May be mocked. */ public void setRestClient(final Client restClient) { this.restClient = restClient; } /** * Updates the principal for the subject. This is done through the * callbacks. * * @param subject * subject * @param jwtPayload * JWT payload * @throws AuthException * @throws GeneralSecurityException */ private void updateSubjectPrincipal(final Subject subject, final JsonObject jwtPayload) throws GeneralSecurityException { try { final String iss = googleWorkaround(jwtPayload.getString("iss")); handler.handle(new Callback[] { new CallerPrincipalCallback(subject, UriBuilder.fromUri(iss) .userInfo(jwtPayload.getString("sub")) .build() .toASCIIString()), new GroupPrincipalCallback(subject, new String[] { iss }) }); } catch (final IOException | UnsupportedCallbackException e) { // Should not happen LOG.log(Level.SEVERE, "updatePrincipalException", e.getMessage()); LOG.throwing(this.getClass() .getName(), "updateSubjectPrincipal", e); throw new AuthException(MessageFormat.format(R.getString("updatePrincipalException"), e.getMessage())); } } /** * Validates the request. The request must be secure otherwise it will * return {@link AuthStatus#FAILURE}. It then tries to build the token * cookie data if available, if the token is valid, subject is set correctly * and user info data if present is stored in the request, then call HTTP * method specific operations. * * @param messageInfo * request and response * @param clientSubject * client subject * @param serviceSubject * service subject, ignored. * @return Auth status */ @Override public AuthStatus validateRequest(final MessageInfo messageInfo, final Subject clientSubject, final Subject serviceSubject) throws AuthException { final HttpServletRequest req = (HttpServletRequest) messageInfo.getRequestMessage(); final HttpServletResponse resp = (HttpServletResponse) messageInfo.getResponseMessage(); try { final TokenCookie tokenCookie = processTokenCookie(clientSubject, req); if (tokenCookie != null && req.isSecure() && isGetRequest(req) && req.getRequestURI() .equals(tokenUri)) { resp.setContentType(MediaType.APPLICATION_JSON); resp.getWriter() .print(tokenCookie.getIdToken()); return AuthStatus.SEND_SUCCESS; } if (tokenCookie != null && req.isSecure() && isGetRequest(req) && req.getRequestURI() .equals(userInfoUri)) { resp.setContentType(MediaType.APPLICATION_JSON); resp.getWriter() .print(tokenCookie.getUserInfo()); return AuthStatus.SEND_SUCCESS; } if (!mandatory && !req.isSecure()) { // successful if the module is not mandatory and the channel is // not secure. return AuthStatus.SUCCESS; } if (!req.isSecure() && mandatory) { // Fail authorization 3.1.2.1 resp.sendError(HttpURLConnection.HTTP_FORBIDDEN, R.getString("SSLReq")); return AuthStatus.SEND_FAILURE; } if (!req.isSecure() && isCallback(req)) { resp.sendError(HttpURLConnection.HTTP_FORBIDDEN, R.getString("SSLReq")); return AuthStatus.SEND_FAILURE; } if (req.isSecure() && isCallback(req)) { return handleCallback(req, resp, clientSubject); } if (!mandatory || tokenCookie != null && !tokenCookie.isExpired()) { return AuthStatus.SUCCESS; } if (req.isSecure() && isHeadRequest(req) && req.getRequestURI() .equals(tokenUri)) { resp.setContentType(MediaType.APPLICATION_JSON); return AuthStatus.SEND_SUCCESS; } if (req.getRequestURI() .equals(userInfoUri) && isHeadRequest(req)) { resp.setContentType(MediaType.APPLICATION_JSON); return AuthStatus.SEND_SUCCESS; } if (!isRetrievalRequest(req)) { resp.sendError(HttpURLConnection.HTTP_FORBIDDEN, "Unable to POST when unauthorized."); return AuthStatus.SEND_FAILURE; } return redirectToAuthorizationEndpoint(req, resp); } catch (final Exception e) { // Any problems with the data should be caught and force redirect to // authorization endpoint. LOG.log(Level.FINE, "validationException", e.getMessage()); LOG.throwing(this.getClass() .getName(), "validateRequest", e); return redirectToAuthorizationEndpoint(req, resp); } } }
package nl.mawoo.smokesignal.gui; import nl.mawoo.smokesignal.networking.Peer; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Scanner; import java.util.function.Consumer; /** * Controls every in and output of the application * * @author Bob van der Valk */ public class Cli extends Thread { private final Scanner scanner; private final List<Peer> peers = new ArrayList<>(); private final String handle; private final Consumer<String> connectCallback; public Cli(Scanner scanner, String handle, Consumer<String> connectCallback) { this.scanner = scanner; this.handle = handle; this.connectCallback = connectCallback; } public void addPeer(Peer peer) { peer.addMessageListener(System.out::println); peers.add(peer); say("welcome in the network", peer); } private void say(String message, Peer peer) { peer.send(MessageFormat.format("{0,time,medium} [{1}] - {2}", new Date(), handle, message)); } private void sayToAll(String message) { for (Peer peer : peers) { say(message, peer); } } @Override public void run() { while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (line.startsWith("/")) { connectCallback.accept(line.substring(1)); } else { sayToAll(line); } } } }
package nu.peg.svmeal.model; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.Serializable; import static nu.peg.svmeal.AppInitializer.logger; public class PriceDto implements Serializable { public double internalPrice; public double externalPrice; public PriceDto() { } public PriceDto(double internalPrice, double externalPrice) { this.internalPrice = internalPrice; this.externalPrice = externalPrice; } public static PriceDto fromElements(final Elements elements) { final double[] intPrice = new double[1]; final double[] extPrice = new double[1]; elements.stream().map(Element::text).forEach(elementString -> { double price = Double.parseDouble(elementString.split(" ")[1]); if (elementString.startsWith("INT")) { intPrice[0] = price; } else if (elementString.startsWith("EXT")) { extPrice[0] = price; } else if (elementString.startsWith("CHF")) { // For our derpy people in Zollikofen intPrice[0] = price; } else { logger.warning(String.format("Found non-matching price tag: `%s`", elementString)); } }); return new PriceDto(intPrice[0], extPrice[0]); } public double getInternalPrice() { return internalPrice; } public void setInternalPrice(double internalPrice) { this.internalPrice = internalPrice; } public double getExternalPrice() { return externalPrice; } public void setExternalPrice(double externalPrice) { this.externalPrice = externalPrice; } }