repo_name
stringlengths 7
104
| file_path
stringlengths 11
238
| context
list | import_statement
stringlengths 103
6.85k
| code
stringlengths 60
38.4k
| next_line
stringlengths 10
824
| gold_snippet_index
int32 0
8
|
---|---|---|---|---|---|---|
HadoopGenomics/Hadoop-BAM | src/main/java/org/seqdoop/hadoop_bam/BAMInputFormat.java | [
"public class LinearBAMIndex extends CachingBAMFileIndex {\n\n public LinearBAMIndex(SeekableStream stream, SAMSequenceDictionary dict) {\n super(stream, dict);\n }\n \n public LinearIndex getLinearIndex(int idx) {\n return getQueryResults(idx).getLinearIndex();\n }\n}",
"public final class IntervalUtil {\n\n // declared to prevent instantiation.\n private IntervalUtil() {}\n\n /**\n * Returns the list of intervals found in a string configuration property separated by colons.\n * @param conf the source configuration.\n * @param intervalPropertyName the property name holding the intervals.\n * @return {@code null} if there is no such a property in the configuration.\n * @throws NullPointerException if either input is null.\n */\n public static List<Interval> getIntervals(final Configuration conf, final String intervalPropertyName) {\n final String intervalsProperty = conf.get(intervalPropertyName);\n if (intervalsProperty == null) {\n return null;\n }\n if (intervalsProperty.isEmpty()) {\n return ImmutableList.of();\n }\n final List<Interval> intervals = new ArrayList<>();\n for (final String s : intervalsProperty.split(\",\")) {\n final int lastColonIdx = s.lastIndexOf(':');\n if (lastColonIdx < 0) {\n throw new FormatException(\"no colon found in interval string: \" + s);\n }\n final int hyphenIdx = s.indexOf('-', lastColonIdx + 1);\n if (hyphenIdx < 0) {\n throw new FormatException(\"no hyphen found after colon interval string: \" + s);\n }\n final String sequence = s.substring(0, lastColonIdx);\n final int start = parseIntOrThrowFormatException(s.substring(lastColonIdx + 1, hyphenIdx),\n \"invalid start position\", s);\n final int stop = parseIntOrThrowFormatException(s.substring(hyphenIdx + 1),\n \"invalid stop position\", s);\n intervals.add(new Interval(sequence, start, stop));\n }\n return intervals;\n }\n\n private static int parseIntOrThrowFormatException(final String str, final String error, final String input) {\n try {\n return Integer.parseInt(str);\n } catch (final NumberFormatException ex) {\n throw new FormatException(error + \" in interval '\" + input + \"': '\" + str + \"'\");\n }\n }\n}",
"public class NIOFileUtil {\n private NIOFileUtil() {\n }\n\n static final String PARTS_GLOB = \"glob:**/part-[mr]-[0-9][0-9][0-9][0-9][0-9]*\";\n\n /**\n * Convert the given path {@link URI} to a {@link Path} object.\n * @param uri the path to convert\n * @return a {@link Path} object\n */\n public static Path asPath(URI uri) {\n try {\n return Paths.get(uri);\n } catch (FileSystemNotFoundException e) {\n ClassLoader cl = Thread.currentThread().getContextClassLoader();\n if (cl == null) {\n throw e;\n }\n try {\n return FileSystems.newFileSystem(uri, new HashMap<>(), cl).provider().getPath(uri);\n } catch (IOException ex) {\n throw new RuntimeException(\"Cannot create filesystem for \" + uri, ex);\n }\n }\n }\n\n /**\n * Convert the given path string to a {@link Path} object.\n * @param path the path to convert\n * @return a {@link Path} object\n */\n public static Path asPath(String path) {\n URI uri = URI.create(path);\n return uri.getScheme() == null ? Paths.get(path) : asPath(uri);\n }\n\n /**\n * Delete the given directory and all of its contents if non-empty.\n * @param directory the directory to delete\n * @throws IOException\n */\n static void deleteRecursive(Path directory) throws IOException {\n Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {\n @Override\n public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {\n Files.delete(file);\n return FileVisitResult.CONTINUE;\n }\n @Override\n public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {\n Files.deleteIfExists(dir);\n return FileVisitResult.CONTINUE;\n }\n });\n }\n\n /**\n * Returns all the files in a directory that match the given pattern, and that don't\n * have the given extension.\n * @param directory the directory to look for files in, subdirectories are not\n * considered\n * @param syntaxAndPattern the syntax and pattern to use for matching (see\n * {@link java.nio.file.FileSystem#getPathMatcher}\n * @param excludesExt the extension to exclude, or null to exclude nothing\n * @return a list of files, sorted by name\n * @throws IOException\n */\n static List<Path> getFilesMatching(Path directory,\n String syntaxAndPattern, String excludesExt) throws IOException {\n PathMatcher matcher = directory.getFileSystem().getPathMatcher(syntaxAndPattern);\n List<Path> parts = Files.walk(directory)\n .filter(matcher::matches)\n .filter(path -> excludesExt == null || !path.toString().endsWith(excludesExt))\n .collect(Collectors.toList());\n Collections.sort(parts);\n return parts;\n }\n\n /**\n * Merge the given part files in order into an output stream.\n * This deletes the parts.\n * @param parts the part files to merge\n * @param out the stream to write each file into, in order\n * @throws IOException\n */\n static void mergeInto(List<Path> parts, OutputStream out)\n throws IOException {\n for (final Path part : parts) {\n Files.copy(part, out);\n Files.delete(part);\n }\n }\n}",
"public final class SAMHeaderReader {\n\t/** A String property corresponding to a ValidationStringency\n\t * value. If set, the given stringency is used when any part of the\n\t * Hadoop-BAM library reads SAM or BAM.\n\t */\n\tpublic static final String VALIDATION_STRINGENCY_PROPERTY =\n\t\t\"hadoopbam.samheaderreader.validation-stringency\";\n\n\tpublic static SAMFileHeader readSAMHeaderFrom(Path path, Configuration conf)\n\t\tthrows IOException\n\t{\n\t\tInputStream i = path.getFileSystem(conf).open(path);\n\t\tfinal SAMFileHeader h = readSAMHeaderFrom(i, conf);\n\t\ti.close();\n\t\treturn h;\n\t}\n\n\t/** Does not close the stream. */\n\tpublic static SAMFileHeader readSAMHeaderFrom(\n\t\tfinal InputStream in, final Configuration conf)\n\t{\n\t\tfinal ValidationStringency\n\t\t\tstringency = getValidationStringency(conf);\n\t\tSamReaderFactory readerFactory = SamReaderFactory.makeDefault()\n\t\t\t\t.setOption(SamReaderFactory.Option.EAGERLY_DECODE, false)\n\t\t\t\t.setUseAsyncIo(false);\n\t\tif (stringency != null) {\n\t\t\treaderFactory.validationStringency(stringency);\n\t\t}\n\n\t\tfinal ReferenceSource refSource = getReferenceSource(conf);\n\t\tif (null != refSource) {\n\t\t\treaderFactory.referenceSource(refSource);\n\t\t}\n\t\treturn readerFactory.open(SamInputResource.of(in)).getFileHeader();\n\t}\n\n\tpublic static ValidationStringency getValidationStringency(\n\t\tfinal Configuration conf)\n\t{\n\t\tfinal String p = conf.get(VALIDATION_STRINGENCY_PROPERTY);\n\t\treturn p == null ? null : ValidationStringency.valueOf(p);\n\t}\n\n\tpublic static ReferenceSource getReferenceSource(\n\t\t\tfinal Configuration conf)\n\t{\n\t\t//TODO: There isn't anything particularly CRAM-specific about reference source or validation\n\t\t// stringency other than that a reference source is required for CRAM files. We should move\n\t\t// the reference source and validation stringency property names and utility methods out of\n\t\t// CRAMInputFormat and SAMHeaderReader and combine them together into a single class for extracting\n\t\t// configuration params, but it would break backward compatibility with existing code that\n\t\t// is dependent on the CRAMInputFormat.REFERENCE_SOURCE_PATH_PROPERTY.\n\t\tfinal String refSourcePath = conf.get(CRAMInputFormat.REFERENCE_SOURCE_PATH_PROPERTY);\n\t\treturn refSourcePath == null ? null : new ReferenceSource(NIOFileUtil.asPath(refSourcePath));\n\t}\n}",
"public class WrapSeekable<S extends InputStream & Seekable>\n\textends SeekableStream\n{\n\tprivate final S stm;\n\tprivate final long len;\n\tprivate final Path path;\n\n\tpublic WrapSeekable(final S s, long length, Path p) {\n\t\tstm = s;\n\t\tlen = length;\n\t\tpath = p;\n\t}\n\n\t/** A helper for the common use case. */\n\tpublic static WrapSeekable<FSDataInputStream> openPath(\n\t\tFileSystem fs, Path p) throws IOException\n\t{\n\t\treturn new WrapSeekable<FSDataInputStream>(\n\t\t\tfs.open(p), fs.getFileStatus(p).getLen(), p);\n\t}\n\tpublic static WrapSeekable<FSDataInputStream> openPath(\n\t\tConfiguration conf, Path path) throws IOException\n\t{\n\t\treturn openPath(path.getFileSystem(conf), path);\n\t}\n\n\t@Override public String getSource() { return path.toString(); }\n\t@Override public long length () { return len; }\n\n\t@Override public long position() throws IOException { return stm.getPos(); }\n\t@Override public void close() throws IOException { stm.close(); }\n\t@Override public boolean eof () throws IOException {\n\t\treturn stm.getPos() == length();\n\t}\n\t@Override public void seek(long pos) throws IOException {\n\t\tstm.seek(pos);\n\t}\n\t@Override public int read() throws IOException {\n\t\treturn stm.read();\n\t}\n\t@Override public int read(byte[] buf, int offset, int len)\n\t\tthrows IOException\n\t{\n\t\treturn stm.read(buf, offset, len);\n\t}\n}"
] | import htsjdk.samtools.AbstractBAMFileIndex;
import htsjdk.samtools.BAMFileReader;
import htsjdk.samtools.BAMFileSpan;
import htsjdk.samtools.BAMIndex;
import htsjdk.samtools.Chunk;
import htsjdk.samtools.LinearBAMIndex;
import htsjdk.samtools.LinearIndex;
import htsjdk.samtools.QueryInterval;
import htsjdk.samtools.SAMFileHeader;
import htsjdk.samtools.SAMFileSpan;
import htsjdk.samtools.SAMSequenceDictionary;
import htsjdk.samtools.SamInputResource;
import htsjdk.samtools.SamReader;
import htsjdk.samtools.SamReaderFactory;
import htsjdk.samtools.util.Interval;
import htsjdk.samtools.util.Locatable;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.seqdoop.hadoop_bam.util.IntervalUtil;
import org.seqdoop.hadoop_bam.util.NIOFileUtil;
import org.seqdoop.hadoop_bam.util.SAMHeaderReader;
import org.seqdoop.hadoop_bam.util.WrapSeekable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.file.ProviderNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import htsjdk.samtools.seekablestream.SeekableStream;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.JobContext;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.FileSplit; | // Copyright (c) 2010 Aalto University
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// File created: 2010-08-03 11:50:19
package org.seqdoop.hadoop_bam;
/** An {@link org.apache.hadoop.mapreduce.InputFormat} for BAM files. Values
* are the individual records; see {@link BAMRecordReader} for the meaning of
* the key.
*/
public class BAMInputFormat
extends FileInputFormat<LongWritable,SAMRecordWritable>
{
private static final Logger logger = LoggerFactory.getLogger(BAMInputFormat.class);
/**
* If set to true, only include reads that overlap the given intervals (if specified),
* and unplaced unmapped reads (if specified). For programmatic use
* {@link #setTraversalParameters(Configuration, List, boolean)} should be preferred.
*/
public static final String BOUNDED_TRAVERSAL_PROPERTY = "hadoopbam.bam.bounded-traversal";
/**
* If set to true, enables the use of BAM indices to calculate splits.
* For programmatic use
* {@link #setEnableBAISplitCalculator(Configuration, boolean)} should be preferred.
* By default, this split calculator is disabled in favor of the splitting-bai calculator.
*/
public static final String ENABLE_BAI_SPLIT_CALCULATOR = "hadoopbam.bam.enable-bai-splitter";
/**
* Filter by region, like <code>-L</code> in SAMtools. Takes a comma-separated
* list of intervals, e.g. <code>chr1:1-20000,chr2:12000-20000</code>. For
* programmatic use {@link #setIntervals(Configuration, List)} should be preferred.
*/
public static final String INTERVALS_PROPERTY = "hadoopbam.bam.intervals";
/**
* If set to true, include unplaced unmapped reads (that is, unmapped reads with no
* position). For programmatic use
* {@link #setTraversalParameters(Configuration, List, boolean)} should be preferred.
*/
public static final String TRAVERSE_UNPLACED_UNMAPPED_PROPERTY = "hadoopbam.bam.traverse-unplaced-unmapped";
/**
* If set to true, use the Intel inflater for decompressing DEFLATE compressed streams.
* If set, the <a href="https://github.com/Intel-HLS/GKL">GKL library</a> must be
* provided on the classpath.
*/
public static final String USE_INTEL_INFLATER_PROPERTY = "hadoopbam.bam.use-intel-inflater";
/**
* Only include reads that overlap the given intervals. Unplaced unmapped reads are not
* included.
* @param conf the Hadoop configuration to set properties on
* @param intervals the intervals to filter by
* @param <T> the {@link Locatable} type
*/
public static <T extends Locatable> void setIntervals(Configuration conf,
List<T> intervals) {
setTraversalParameters(conf, intervals, false);
}
/**
* Enables or disables the split calculator that uses the BAM index to calculate splits.
*/
public static void setEnableBAISplitCalculator(Configuration conf,
boolean setEnabled) {
conf.setBoolean(ENABLE_BAI_SPLIT_CALCULATOR, setEnabled);
}
/**
* Only include reads that overlap the given intervals (if specified) and unplaced
* unmapped reads (if <code>true</code>).
* @param conf the Hadoop configuration to set properties on
* @param intervals the intervals to filter by, or <code>null</code> if all reads
* are to be included (in which case <code>traverseUnplacedUnmapped</code> must be
* <code>true</code>)
* @param traverseUnplacedUnmapped whether to included unplaced unampped reads
* @param <T> the {@link Locatable} type
*/
public static <T extends Locatable> void setTraversalParameters(Configuration conf,
List<T> intervals, boolean traverseUnplacedUnmapped) {
if (intervals == null && !traverseUnplacedUnmapped) {
throw new IllegalArgumentException("Traversing mapped reads only is not supported.");
}
conf.setBoolean(BOUNDED_TRAVERSAL_PROPERTY, true);
if (intervals != null) {
StringBuilder sb = new StringBuilder();
for (Iterator<T> it = intervals.iterator(); it.hasNext(); ) {
Locatable l = it.next();
sb.append(String.format("%s:%d-%d", l.getContig(), l.getStart(), l.getEnd()));
if (it.hasNext()) {
sb.append(",");
}
}
conf.set(INTERVALS_PROPERTY, sb.toString());
}
conf.setBoolean(TRAVERSE_UNPLACED_UNMAPPED_PROPERTY, traverseUnplacedUnmapped);
}
/**
* Reset traversal parameters so that all reads are included.
* @param conf the Hadoop configuration to set properties on
*/
public static void unsetTraversalParameters(Configuration conf) {
conf.unset(BOUNDED_TRAVERSAL_PROPERTY);
conf.unset(INTERVALS_PROPERTY);
conf.unset(TRAVERSE_UNPLACED_UNMAPPED_PROPERTY);
}
static boolean isBoundedTraversal(Configuration conf) {
return conf.getBoolean(BOUNDED_TRAVERSAL_PROPERTY, false) ||
conf.get(INTERVALS_PROPERTY) != null; // backwards compatibility
}
static boolean traverseUnplacedUnmapped(Configuration conf) {
return conf.getBoolean(TRAVERSE_UNPLACED_UNMAPPED_PROPERTY, false);
}
static List<Interval> getIntervals(Configuration conf) {
return IntervalUtil.getIntervals(conf, INTERVALS_PROPERTY);
}
static boolean useIntelInflater(Configuration conf) {
return conf.getBoolean(USE_INTEL_INFLATER_PROPERTY, false);
}
static Path getIdxPath(Path path) {
return path.suffix(SplittingBAMIndexer.OUTPUT_FILE_EXTENSION);
}
static List<InputSplit> removeIndexFiles(List<InputSplit> splits) {
// Remove any splitting bai files
return splits.stream()
.filter(split -> !((FileSplit) split).getPath().getName().endsWith(
SplittingBAMIndexer.OUTPUT_FILE_EXTENSION))
.filter(split -> !((FileSplit) split).getPath().getName().endsWith(
BAMIndex.BAMIndexSuffix))
.collect(Collectors.toList());
}
static Path getBAIPath(Path path) {
return path.suffix(BAMIndex.BAMIndexSuffix);
}
/** Returns a {@link BAMRecordReader} initialized with the parameters. */
@Override public RecordReader<LongWritable,SAMRecordWritable>
createRecordReader(InputSplit split, TaskAttemptContext ctx)
throws InterruptedException, IOException
{
final RecordReader<LongWritable,SAMRecordWritable> rr =
new BAMRecordReader();
rr.initialize(split, ctx);
return rr;
}
/** The splits returned are {@link FileVirtualSplit FileVirtualSplits}. */
@Override public List<InputSplit> getSplits(JobContext job)
throws IOException
{
return getSplits(super.getSplits(job), job.getConfiguration());
}
public List<InputSplit> getSplits(
List<InputSplit> splits, Configuration cfg)
throws IOException
{
final List<InputSplit> origSplits = removeIndexFiles(splits);
// Align the splits so that they don't cross blocks.
// addIndexedSplits() requires the given splits to be sorted by file
// path, so do so. Although FileInputFormat.getSplits() does, at the time
// of writing this, generate them in that order, we shouldn't rely on it.
Collections.sort(origSplits, new Comparator<InputSplit>() {
public int compare(InputSplit a, InputSplit b) {
FileSplit fa = (FileSplit)a, fb = (FileSplit)b;
return fa.getPath().compareTo(fb.getPath());
}
});
final List<InputSplit> newSplits =
new ArrayList<InputSplit>(origSplits.size());
for (int i = 0; i < origSplits.size();) {
try {
i = addIndexedSplits (origSplits, i, newSplits, cfg);
} catch (IOException | ProviderNotFoundException e) {
if (cfg.getBoolean(ENABLE_BAI_SPLIT_CALCULATOR, false)) {
try {
i = addBAISplits (origSplits, i, newSplits, cfg);
} catch (IOException | ProviderNotFoundException e2) {
i = addProbabilisticSplits (origSplits, i, newSplits, cfg);
}
} else {
i = addProbabilisticSplits (origSplits, i, newSplits, cfg);
}
}
}
return filterByInterval(newSplits, cfg);
}
// Handles all the splits that share the Path of the one at index i,
// returning the next index to be used.
private int addIndexedSplits(
List<InputSplit> splits, int i, List<InputSplit> newSplits,
Configuration cfg)
throws IOException
{
final Path file = ((FileSplit)splits.get(i)).getPath();
List<InputSplit> potentialSplits = new ArrayList<InputSplit>();
final SplittingBAMIndex idx = new SplittingBAMIndex(
file.getFileSystem(cfg).open(getIdxPath(file)));
int splitsEnd = splits.size();
for (int j = i; j < splitsEnd; ++j)
if (!file.equals(((FileSplit)splits.get(j)).getPath()))
splitsEnd = j;
if (idx.size() == 1) { // no alignments, only the file size, so no splits to add
return splitsEnd;
}
for (int j = i; j < splitsEnd; ++j) {
final FileSplit fileSplit = (FileSplit)splits.get(j);
final long start = fileSplit.getStart();
final long end = start + fileSplit.getLength();
final Long blockStart = idx.nextAlignment(start);
// The last split needs to end where the last alignment ends, but the
// index doesn't store that data (whoops); we only know where the last
// alignment begins. Fortunately there's no need to change the index
// format for this: we can just set the end to the maximal length of
// the final BGZF block (0xffff), and then read until BAMRecordCodec
// hits EOF.
Long blockEnd;
if (j == splitsEnd - 1) {
blockEnd = idx.prevAlignment(end) | 0xffff;
} else {
blockEnd = idx.nextAlignment(end);
}
if (blockStart == null || blockEnd == null) {
logger.warn("Index for {} was not good. Generating probabilistic splits.", file);
return addProbabilisticSplits(splits, i, newSplits, cfg);
}
potentialSplits.add(new FileVirtualSplit(
file, blockStart, blockEnd, fileSplit.getLocations()));
}
for (InputSplit s : potentialSplits) {
newSplits.add(s);
}
return splitsEnd;
}
// Handles all the splits that share the Path of the one at index i,
// returning the next index to be used.
private int addBAISplits(List<InputSplit> splits,
int i,
List<InputSplit> newSplits,
Configuration conf) throws IOException {
int splitsEnd = i;
final Path path = ((FileSplit)splits.get(i)).getPath();
final Path baiPath = getBAIPath(path);
final FileSystem fs = path.getFileSystem(conf);
final Path sinPath;
if (fs.exists(baiPath)) {
sinPath = baiPath;
} else {
sinPath = new Path(path.toString().replaceFirst("\\.bam$", BAMIndex.BAMIndexSuffix));
}
try (final FSDataInputStream in = fs.open(path);
final SeekableStream guesserSin = WrapSeekable.openPath(fs, path);
final SeekableStream sin = WrapSeekable.openPath(fs, sinPath)) {
| SAMFileHeader header = SAMHeaderReader.readSAMHeaderFrom(in, conf); | 3 |
contentful/contentful.java | src/test/java/com/contentful/java/cda/integration/IntegrationWithMasterEnvironment.java | [
"public class CDAAsset extends LocalizedResource {\n\n private static final long serialVersionUID = -4645571481643616657L;\n\n /**\n * @return title of this asset.\n */\n public String title() {\n return getField(\"title\");\n }\n\n /**\n * @return url to the file of this asset.\n */\n public String url() {\n return fileField(\"url\");\n }\n\n /**\n * Returns a url with the given image manipulation.\n * <p>\n * If the asset is not pointing to an image (as identified by its mimetype) the {@link #url()} is\n * returned. Same happens if the options are empty or non existing, then the url gets returned.\n * <p>\n * In an error case (for instance, using the same option twice), the last option with the same\n * operation will be used.\n *\n * @param options to manipulate the image the returned url will be pointing to.\n * @return an url reflecting all the options given.\n * @throws IllegalArgumentException if no options are given.\n * @throws IllegalArgumentException if no mimetype was set on asset.\n * @throws IllegalArgumentException if mimetype was not an image.\n * @see ImageOption\n * @see #url()\n */\n public String urlForImageWith(ImageOption... options) {\n if (options == null || options.length == 0) {\n throw new IllegalArgumentException(\"Do not use empty options argument. \"\n + \"If you want to manipulate the url by hand, please use `CDAAsset.url()` instead.\");\n }\n\n final String mimeType = mimeType();\n if (mimeType == null || !mimeType.startsWith(\"image\")) {\n throw new IllegalStateException(\"Asset does not have an image mime type.\");\n }\n\n final Map<String, ImageOption> mappedOptions\n = new LinkedHashMap<>(options.length);\n\n for (final ImageOption option : options) {\n mappedOptions.put(option.getOperation(), option);\n }\n\n String url = url();\n for (final ImageOption option : mappedOptions.values()) {\n url = option.apply(url);\n }\n\n return url;\n }\n\n /**\n * @return mime-type of this asset.\n */\n public String mimeType() {\n return fileField(\"contentType\");\n }\n\n /**\n * Helper method to extract a field from the {@code file} map.\n *\n * @param key the key who's value to be returned.\n * @param <T> the type of this field.\n * @return field of this file.\n */\n @SuppressWarnings(\"unchecked\")\n public <T> T fileField(String key) {\n T result = null;\n Map<String, Object> file = getField(\"file\");\n if (file != null) {\n result = (T) file.get(key);\n }\n return result;\n }\n\n /**\n * Return a string, showing the id and title.\n *\n * @return a human readable string\n */\n @Override public String toString() {\n return \"CDAAsset{\"\n + \"id='\" + id() + '\\''\n + \", title='\" + title() + '\\''\n + '}';\n }\n}",
"public class CDAClient {\n private static final int CONTENT_TYPE_LIMIT_MAX = 1000;\n\n final String spaceId;\n\n final String environmentId;\n\n final String token;\n\n final CDAService service;\n\n final Cache cache;\n\n final Executor callbackExecutor;\n\n final boolean preview;\n\n CDAClient(Builder builder) {\n this(new Cache(),\n Platform.get().callbackExecutor(),\n createService(builder),\n builder);\n validate(builder);\n }\n\n CDAClient(Cache cache, Executor executor, CDAService service, Builder builder) {\n this.cache = cache;\n this.callbackExecutor = executor;\n this.service = service;\n this.spaceId = builder.space;\n this.environmentId = builder.environment;\n this.token = builder.token;\n this.preview = builder.preview;\n }\n\n private void validate(Builder builder) {\n checkNotNull(builder.space, \"Space ID must be provided.\");\n checkNotNull(builder.environment, \"Environment ID must not be null.\");\n\n if (builder.callFactory == null) {\n checkNotNull(builder.token, \"A token must be provided, if no call factory is specified.\");\n }\n }\n\n private static CDAService createService(Builder clientBuilder) {\n String endpoint = clientBuilder.endpoint;\n if (endpoint == null) {\n endpoint = ENDPOINT_PROD;\n }\n\n Retrofit.Builder retrofitBuilder = new Retrofit.Builder()\n .addConverterFactory(GsonConverterFactory.create(ResourceFactory.GSON))\n .addCallAdapterFactory(RxJava2CallAdapterFactory.create())\n .callFactory(clientBuilder.createOrGetCallFactory(clientBuilder))\n .baseUrl(endpoint);\n\n return retrofitBuilder.build().create(CDAService.class);\n }\n\n /**\n * Returns a {@link FetchQuery} for a given {@code type}, which can be used to fulfill the\n * request synchronously or asynchronously when a callback is provided.\n *\n * @param type resource type. This can be either a {@link CDALocale}, a {@link CDAEntry},\n * a {@link CDAAsset}, or a {@link CDAContentType}\n * @param <T> type for avoiding casting on calling side.\n * @return A query to call {@link FetchQuery#all()} or {@link FetchQuery#one(String)} on it.\n * @see #fetchSpace()\n */\n public <T extends CDAResource> FetchQuery<T> fetch(Class<T> type) {\n return new FetchQuery<>(type, this);\n }\n\n /**\n * Returns a {@link TransformQuery} to transform the default contentful response into a specific\n * custom model type.\n * <p>\n *\n * @param <T> An annotated custom {@link TransformQuery.ContentfulEntryModel} model.\n * @return a query for async calls to Contentful transforming the response to custom types\n * @see TransformQuery.ContentfulEntryModel\n * @see TransformQuery.ContentfulField\n * @see TransformQuery.ContentfulSystemField\n */\n public <T> TransformQuery<T> observeAndTransform(Class<T> type) {\n return new TransformQuery<>(type, this);\n }\n\n /**\n * Returns an {@link ObserveQuery} for a given {@code type}, which can be used to return\n * an {@link Flowable} that fetches the desired resources.\n *\n * @param type resource type. This can be either a {@link CDALocale}, a {@link CDAEntry},\n * a {@link CDAAsset}, or a {@link CDAContentType}\n * @param <T> type for avoiding casting on calling side.\n * @return A query to call {@link ObserveQuery#all()} or {@link ObserveQuery#one(String)} on it.\n * @see #observeSpace()\n */\n public <T extends CDAResource> ObserveQuery<T> observe(Class<T> type) {\n return new ObserveQuery<>(type, this);\n }\n\n /**\n * Populate the content type cache with _all_ available content types.\n * <p>\n * This method will run through all the content types, saving them in the process and also takes\n * care of paging.\n * <p>\n * This method is synchronous.\n *\n * @return the number of content types cached.\n */\n public int populateContentTypeCache() {\n return observeContentTypeCachePopulation().blockingFirst();\n }\n\n /**\n * Populate the content type cache with _all_ available content types.\n * <p>\n * This method is synchronous.\n *\n * @param limit the number of content types per page.\n * @return the number of content types cached.\n * @throws IllegalArgumentException if limit is less or equal to 0.\n * @throws IllegalArgumentException if limit is more then 1_000.\n * @see #populateContentTypeCache()\n */\n public int populateContentTypeCache(int limit) {\n if (limit > CONTENT_TYPE_LIMIT_MAX) {\n throw new IllegalArgumentException(\"Content types per page limit cannot be more then 1000.\");\n }\n if (limit <= 0) {\n throw new IllegalArgumentException(\"Content types per page limit cannot be \"\n + \"less or equal to 0.\");\n }\n\n return observeContentTypeCachePopulation(limit).blockingFirst();\n }\n\n /**\n * Populate the content type cache with _all_ available content types.\n * <p>\n * This method will run through all the content types, saving them in the process and also takes\n * care of paging.\n * <p>\n * This method is asynchronous and needs to be subscribed to.\n *\n * @return the flowable representing the asynchronous call.\n */\n public Flowable<Integer> observeContentTypeCachePopulation() {\n return observeContentTypeCachePopulation(CONTENT_TYPE_LIMIT_MAX);\n }\n\n /**\n * Populate the content type cache with _all_ available content types.\n * <p>\n * This method will run through all the content types, saving them in the process and also takes\n * care of paging.\n * <p>\n * This method is asynchronous and needs to be subscribed to.\n *\n * @param limit the number of content types per page.\n * @return the flowable representing the asynchronous call.\n * @throws IllegalArgumentException if limit is less or equal to 0.\n * @throws IllegalArgumentException if limit is more then 1_000.\n */\n public Flowable<Integer> observeContentTypeCachePopulation(final int limit) {\n if (limit > CONTENT_TYPE_LIMIT_MAX) {\n throw new IllegalArgumentException(\"Content types per page limit cannot be more then 1000.\");\n }\n if (limit <= 0) {\n throw new IllegalArgumentException(\"Content types per page limit cannot be \"\n + \"less or equal to 0.\");\n }\n\n return\n observe(CDAContentType.class)\n .orderBy(\"sys.id\")\n .limit(limit)\n .all()\n .map(\n new Function<CDAArray, CDAArray>() {\n @Override\n public CDAArray apply(CDAArray array) {\n if (array.skip() + array.limit() < array.total()) {\n return nextPage(array);\n } else {\n return array;\n }\n }\n\n private CDAArray nextPage(CDAArray array) {\n final CDAArray nextArray = observe(CDAContentType.class)\n .orderBy(\"sys.id\")\n .limit(limit)\n .skip(array.skip + limit)\n .all()\n .map(this)\n .blockingFirst();\n\n array.skip = nextArray.skip;\n array.items.addAll(nextArray.items);\n array.assets.putAll(nextArray.assets);\n array.entries.putAll(nextArray.entries);\n\n return array;\n }\n }\n )\n .map(new Function<CDAArray, Integer>() {\n @Override\n public Integer apply(CDAArray array) {\n for (CDAResource resource : array.items) {\n if (resource instanceof CDAContentType) {\n cache.types().put(resource.id(), (CDAContentType) resource);\n } else {\n throw new IllegalStateException(\n \"Requesting a list of content types should not return \"\n + \"any other type.\");\n }\n }\n return array.total;\n }\n }\n );\n }\n\n /**\n * Returns a {@link SyncQuery} for initial synchronization via the Sync API.\n *\n * @return query instance.\n */\n\n public SyncQuery sync() {\n return sync(null, null);\n }\n\n /**\n * Returns a {@link SyncQuery} for synchronization with the provided {@code syncToken} via\n * the Sync API.\n * <p>\n * If called from a {@link #preview} client, this will always do an initial sync.\n *\n * @param type the type to be sync'ed.\n * @return query instance.\n */\n public SyncQuery sync(SyncType type) {\n return sync(null, null, type);\n }\n\n /**\n * Returns a {@link SyncQuery} for synchronization with the provided {@code syncToken} via\n * the Sync API.\n * <p>\n * If called from a {@link #preview} client, this will always do an initial sync.\n *\n * @param syncToken sync token.\n * @return query instance.\n */\n public SyncQuery sync(String syncToken) {\n return sync(syncToken, null);\n }\n\n /**\n * Returns a {@link SyncQuery} for synchronization with an existing space.\n * <p>\n * If called from a {@link #preview} client, this will always do an initial sync.\n *\n * @param synchronizedSpace space to sync.\n * @return query instance.\n */\n public SyncQuery sync(SynchronizedSpace synchronizedSpace) {\n return sync(null, synchronizedSpace);\n }\n\n private SyncQuery sync(String syncToken, SynchronizedSpace synchronizedSpace) {\n return sync(syncToken, synchronizedSpace, null);\n }\n\n private SyncQuery sync(String syncToken, SynchronizedSpace synchronizedSpace,\n SyncType type) {\n if (preview) {\n syncToken = null;\n synchronizedSpace = null;\n }\n\n SyncQuery.Builder builder = SyncQuery.builder().setClient(this);\n if (synchronizedSpace != null) {\n builder.setSpace(synchronizedSpace);\n }\n if (syncToken != null) {\n builder.setSyncToken(syncToken);\n }\n if (type != null) {\n builder.setType(type);\n }\n return builder.build();\n }\n\n /**\n * @return the space for this client (synchronously).\n */\n public CDASpace fetchSpace() {\n return observeSpace().blockingFirst();\n }\n\n /**\n * Asynchronously fetch the space.\n *\n * @param <C> the type of the callback to be used.\n * @param callback the value of the callback to be called back.\n * @return the space for this client (asynchronously).\n */\n @SuppressWarnings(\"unchecked\")\n public <C extends CDACallback<CDASpace>> C fetchSpace(C callback) {\n return (C) Callbacks.subscribeAsync(observeSpace(), callback, this);\n }\n\n /**\n * @return an {@link Flowable} that fetches the space for this client.\n */\n public Flowable<CDASpace> observeSpace() {\n return service.space(spaceId).map(new Function<Response<CDASpace>, CDASpace>() {\n @Override\n public CDASpace apply(Response<CDASpace> response) throws Exception {\n return ResourceFactory.fromResponse(response);\n }\n });\n }\n\n /**\n * Caching\n */\n Flowable<Cache> cacheAll(final boolean invalidate) {\n return cacheLocales(invalidate)\n .flatMap(new Function<List<CDALocale>, Publisher<? extends Map<String, CDAContentType>>>() {\n @Override\n public Publisher<? extends Map<String, CDAContentType>> apply(List<CDALocale> locales) {\n return CDAClient.this.cacheTypes(invalidate);\n }\n })\n .map(new Function<Map<String, CDAContentType>, Cache>() {\n @Override\n public Cache apply(Map<String, CDAContentType> stringCDAContentTypeMap) {\n return cache;\n }\n });\n }\n\n Flowable<List<CDALocale>> cacheLocales(boolean invalidate) {\n List<CDALocale> locales = invalidate ? null : cache.locales();\n if (locales == null) {\n return service.array(spaceId, environmentId, PATH_LOCALES, new HashMap<>())\n .map(new Function<Response<CDAArray>, List<CDALocale>>() {\n @Override\n public List<CDALocale> apply(Response<CDAArray> localesResponse) {\n final List<CDALocale> locales1 = fromArrayToItems(fromResponse(localesResponse));\n cache.setLocales(locales1);\n return locales1;\n }\n }\n );\n }\n return Flowable.just(locales);\n }\n\n Flowable<Map<String, CDAContentType>> cacheTypes(boolean invalidate) {\n Map<String, CDAContentType> types = invalidate ? null : cache.types();\n if (types == null) {\n return service.array(\n spaceId,\n environmentId,\n PATH_CONTENT_TYPES,\n new HashMap<>()\n ).map(new Function<Response<CDAArray>, Map<String, CDAContentType>>() {\n @Override\n public Map<String, CDAContentType> apply(Response<CDAArray> arrayResponse) {\n CDAArray array = ResourceFactory.array(arrayResponse, CDAClient.this);\n Map<String, CDAContentType> tmp = new ConcurrentHashMap<>();\n for (CDAResource resource : array.items()) {\n tmp.put(resource.id(), (CDAContentType) resource);\n }\n cache.setTypes(tmp);\n return tmp;\n }\n }\n );\n }\n return Flowable.just(types);\n }\n\n Flowable<CDAContentType> cacheTypeWithId(String id) {\n CDAContentType contentType = cache.types().get(id);\n if (contentType == null) {\n return observe(CDAContentType.class)\n .one(id)\n .map(new Function<CDAContentType, CDAContentType>() {\n @Override\n public CDAContentType apply(CDAContentType resource) {\n if (resource != null) {\n cache.types().put(resource.id(), resource);\n }\n return resource;\n }\n }\n );\n }\n return Flowable.just(contentType);\n }\n\n /**\n * Clear the java internal cache.\n *\n * @return this client for chaining.\n */\n public CDAClient clearCache() {\n cache.clear();\n return this;\n }\n\n static String createUserAgent() {\n final Properties properties = System.getProperties();\n return String.format(\"contentful.java/%s(%s %s) %s/%s\",\n PROJECT_VERSION,\n properties.getProperty(\"java.runtime.name\"),\n properties.getProperty(\"java.runtime.version\"),\n properties.getProperty(\"os.name\"),\n properties.getProperty(\"os.version\")\n );\n }\n\n static Section[] createCustomHeaderSections(Section application, Section integration) {\n final Properties properties = System.getProperties();\n\n final Platform platform = Platform.get();\n return new Section[]{\n sdk(\n \"contentful.java\",\n Version.parse(PROJECT_VERSION)),\n platform(\n \"java\",\n Version.parse(properties.getProperty(\"java.runtime.version\"))\n ),\n os(\n OperatingSystem.parse(platform.name()),\n Version.parse(platform.version())\n ),\n application,\n integration\n };\n }\n\n /**\n * @return a {@link CDAClient} builder.\n */\n\n public static Builder builder() {\n return new Builder();\n }\n\n /**\n * This builder will be used to configure and then create a {@link CDAClient}.\n */\n public static class Builder {\n String space;\n String environment = Constants.DEFAULT_ENVIRONMENT;\n String token;\n String endpoint;\n\n Logger logger;\n Logger.Level logLevel = Logger.Level.NONE;\n\n Call.Factory callFactory;\n\n boolean preview;\n Tls12Implementation tls12Implementation = useRecommendation;\n\n Section application;\n Section integration;\n\n private static final OkHttpClient OK_HTTP_CLIENT = new OkHttpClient();\n\n Builder() {\n }\n\n /**\n * Sets the space ID.\n *\n * @param space the space id to be set.\n * @return this builder for chaining.\n */\n public Builder setSpace(String space) {\n this.space = space;\n return this;\n }\n\n /**\n * Sets the environment ID.\n *\n * @param environment the space id to be set.\n * @return this builder for chaining.\n */\n public Builder setEnvironment(String environment) {\n this.environment = environment;\n return this;\n }\n\n /**\n * Sets the space access token.\n *\n * @param token the access token, sometimes called authorization token.\n * @return this builder for chaining.\n */\n public Builder setToken(String token) {\n this.token = token;\n return this;\n }\n\n /**\n * Sets a custom endpoint.\n *\n * @param endpoint the url to be calling to (i.e. https://cdn.contentful.com).\n * @return this builder for chaining.\n */\n public Builder setEndpoint(String endpoint) {\n this.endpoint = endpoint;\n return this;\n }\n\n /**\n * Sets a custom logger level.\n * <p>\n * If set to {@link Logger.Level}.NONE any custom logger will get ignored.\n *\n * @param logLevel the amount/level of logging to be used.\n * @return this builder for chaining.\n */\n public Builder setLogLevel(Logger.Level logLevel) {\n this.logLevel = logLevel;\n return this;\n }\n\n /**\n * Sets a custom logger.\n *\n * @param logger the logger to be set.\n * @return this builder for chaining.\n */\n public Builder setLogger(Logger logger) {\n this.logger = logger;\n return this;\n }\n\n /**\n * Sets the endpoint to point the Preview API.\n *\n * @return this builder for chaining.\n */\n public Builder preview() {\n preview = true;\n return this.setEndpoint(Constants.ENDPOINT_PREVIEW);\n }\n\n /**\n * Sets a custom HTTP call factory.\n *\n * @param callFactory the factory to be used to create a call.\n * @return this builder for chaining.\n */\n public Builder setCallFactory(Call.Factory callFactory) {\n this.callFactory = callFactory;\n return this;\n }\n\n Call.Factory createOrGetCallFactory(Builder clientBuilder) {\n final Call.Factory callFactory;\n\n if (clientBuilder.callFactory == null) {\n callFactory = defaultCallFactoryBuilder().build();\n } else {\n callFactory = clientBuilder.callFactory;\n }\n\n return callFactory;\n }\n\n private OkHttpClient.Builder setLogger(OkHttpClient.Builder okBuilder) {\n if (logger != null) {\n switch (logLevel) {\n case BASIC:\n return okBuilder.addInterceptor(new LogInterceptor(logger));\n case FULL:\n return okBuilder.addNetworkInterceptor(new LogInterceptor(logger));\n case NONE:\n break;\n default:\n break;\n }\n } else {\n if (logLevel != Logger.Level.NONE) {\n throw new IllegalArgumentException(\n \"Cannot log to a null logger. Please set either logLevel to None, or do set a Logger\"\n );\n }\n }\n return okBuilder;\n }\n\n private OkHttpClient.Builder useTls12IfWanted(OkHttpClient.Builder okBuilder) {\n if (isSdkTlsSocketFactoryWanted()) {\n try {\n okBuilder.sslSocketFactory(new TlsSocketFactory(), getX509TrustManager());\n } catch (GeneralSecurityException exception) {\n throw new IllegalArgumentException(\n \"Cannot create TlsSocketFactory for TLS 1.2. \"\n + \"Please consider using 'setTls12Implementation(systemProvided)', \"\n + \"or update to a system providing TLS 1.2 support.\",\n exception);\n }\n }\n\n return okBuilder;\n }\n\n X509TrustManager getX509TrustManager() throws NoSuchAlgorithmException, KeyStoreException {\n final TrustManagerFactory trustManagerFactory =\n TrustManagerFactory.getInstance(getDefaultAlgorithm());\n trustManagerFactory.init((KeyStore) null);\n\n return extractX509TrustManager(trustManagerFactory.getTrustManagers());\n }\n\n X509TrustManager extractX509TrustManager(TrustManager[] trustManagers)\n throws NoSuchAlgorithmException {\n if (trustManagers != null) {\n for (final TrustManager manager : trustManagers) {\n if (manager instanceof X509TrustManager) {\n return (X509TrustManager) manager;\n }\n }\n }\n\n throw new NoSuchAlgorithmException(\n \"Cannot find a 'X509TrustManager' in system provided managers: '\"\n + Arrays.toString(trustManagers) + \"'.\");\n }\n\n boolean isSdkTlsSocketFactoryWanted() {\n switch (tls12Implementation) {\n case sdkProvided:\n return true;\n case systemProvided:\n return false;\n default:\n case useRecommendation:\n return Platform.get().needsCustomTLSSocketFactory();\n }\n }\n\n /**\n * Returns the default Call.Factory.Builder used throughout this SDK.\n * <p>\n * Please use this method last in the building step, since changing settings as in the\n * {@link #token} or others afterwards will not be reflected by this factory.\n * <p>\n * This might be useful if you want to augment the default client, without needing to rely on\n * replicating the current sdk behaviour.\n *\n * @return A {@link Call.Factory} used through out SDK, as if no custom call factory was used.\n */\n public OkHttpClient.Builder defaultCallFactoryBuilder() {\n final Section[] sections = createCustomHeaderSections(application, integration);\n\n OkHttpClient.Builder okBuilder = new OkHttpClient.Builder()\n .connectionPool(OK_HTTP_CLIENT.connectionPool())\n .addInterceptor(new AuthorizationHeaderInterceptor(token))\n .addInterceptor(new UserAgentHeaderInterceptor(createUserAgent()))\n .addInterceptor(new ContentfulUserAgentHeaderInterceptor(sections))\n .addInterceptor(new ErrorInterceptor());\n\n setLogger(okBuilder);\n useTls12IfWanted(okBuilder);\n\n return okBuilder;\n }\n\n /**\n * Overwrite the recommendation from the SDK for using a custom TLS12 socket factory.\n * <p>\n * This SDK recommends a TLS12 socket factory to be used: Either the system one, or an SDK owned\n * implementation. If this recommendation does not fit your needs, feel free to overwrite the\n * recommendation here.\n * <p>\n * Some operation systems and frameworks, esp. Android and Java 1.6, might opt for implementing\n * TLS12 (enforced by Contentful) but do not enable it. The SDK tries to find those situations\n * and recommends to either use the system TLSSocketFactory or a SDK provided one.\n *\n * @param implementation which implementation to be used.\n * @return this builder for ease of chaining.\n */\n public Builder setTls12Implementation(Tls12Implementation implementation) {\n this.tls12Implementation = implementation;\n return this;\n }\n\n /**\n * Tell the client which application this is.\n * <p>\n * It might be used for internal tracking of Contentfuls tools.\n *\n * @param name the name of the app.\n * @param version the version in semver of the app.\n * @return this builder for chaining.\n */\n public Builder setApplication(String name, String version) {\n this.application = Section.app(name, Version.parse(version));\n return this;\n }\n\n /**\n * Set the name of the integration.\n * <p>\n * This custom user agent header will be used for libraries build on top of this library.\n *\n * @param name of the integration.\n * @param version version of the integration.\n * @return this builder for chaining.\n */\n public Builder setIntegration(String name, String version) {\n this.integration = Section.integration(name, Version.parse(version));\n return this;\n }\n\n /**\n * Create CDAClient, using the specified configuration options.\n *\n * @return a build CDAClient.\n */\n public CDAClient build() {\n return new CDAClient(this);\n }\n }\n}",
"public class CDAEntry extends LocalizedResource {\n private static final long serialVersionUID = 5902790363045498307L;\n private CDAContentType contentType;\n\n /**\n * @return the contentType set.\n */\n public CDAContentType contentType() {\n return contentType;\n }\n\n /**\n * Set the contentType of this entry.\n * @param contentType the type to be set.\n */\n void setContentType(CDAContentType contentType) {\n this.contentType = contentType;\n }\n\n /**\n * Create a human readable string of this object.\n * @return a string, containing the id of this content type.\n */\n @Override public String toString() {\n return \"CDAEntry{\"\n + \"id='\" + id() + '\\''\n + '}';\n }\n}",
"public class CDALocale extends CDAResource {\n private static final long serialVersionUID = -5710267672379169621L;\n String code;\n\n String name;\n\n @SerializedName(\"fallbackCode\")\n String fallbackLocaleCode;\n\n @SerializedName(\"default\")\n boolean defaultLocale;\n\n /**\n * @return code of this locale. ('en-US' or similar).\n */\n public String code() {\n return code;\n }\n\n /**\n * @return human readable name of this locale.\n */\n public String name() {\n return name;\n }\n\n /**\n * @return the code of a locale to be used for falling back.\n */\n public String fallbackLocaleCode() {\n return fallbackLocaleCode;\n }\n\n /**\n * @return true if this is the default locale.\n */\n public boolean isDefaultLocale() {\n return defaultLocale;\n }\n\n /**\n * @return a human readable string, representing the object.\n */\n @Override public String toString() {\n return \"CDALocale { \" + super.toString() + \" \"\n + \"code = \" + code() + \", \"\n + \"defaultLocale = \" + isDefaultLocale() + \", \"\n + \"fallbackLocaleCode = \" + fallbackLocaleCode() + \", \"\n + \"name = \" + name() + \" \"\n + \"}\";\n }\n}",
"public class CDASpace extends CDAResource {\n private static final long serialVersionUID = 8920494351623297673L;\n String name;\n\n /**\n * @return name of this space.\n */\n public String name() {\n return name;\n }\n\n /**\n * Create a String from this object.\n *\n * @return a String containing the id and name of this space\n */\n @Override public String toString() {\n return \"CDASpace{\"\n + \"id='\" + id() + '\\''\n + \", name='\" + name + '\\''\n + '}';\n }\n}",
"public abstract class LocalizedResource extends CDAResource {\n private static final long serialVersionUID = 5713028146014748949L;\n\n public class Localizer {\n private final String locale;\n\n Localizer(String locale) {\n this.locale = locale;\n }\n\n /**\n * Extracts a field from the fields set of the active locale, result type is inferred.\n *\n * @param key field key.\n * @param <T> type.\n * @return field value, null if it doesn't exist.\n */\n @SuppressWarnings(\"unchecked\")\n public <T> T getField(String key) {\n final Map<String, T> value = (Map<String, T>) fields.get(key);\n if (value == null) {\n return null;\n }\n\n return getFieldForFallbackLocale(value, locale);\n }\n\n <T> T getFieldForFallbackLocale(Map<String, T> value, String locale) {\n if (locale == null) {\n return null;\n }\n\n final T localized = value.get(locale);\n if (localized != null) {\n return localized;\n } else {\n return getFieldForFallbackLocale(value, fallbackLocaleMap.get(locale));\n }\n }\n }\n\n String defaultLocale;\n\n Map<String, String> fallbackLocaleMap;\n\n Map<String, Object> fields;\n\n Map<String, Object> rawFields;\n\n /**\n * Creates an object to be used for returning different field in one locale.\n *\n * @param locale pointing to a locale in the environment.\n * @return localizer to localize the fields.\n */\n public Localizer localize(String locale) {\n return new Localizer(locale);\n }\n\n /**\n * Get a field using the environments default locale.\n *\n * @param key field key.\n * @param <T> type.\n * @return field value, null if it doesn't exist.\n * @see #localize(String)\n */\n public <T> T getField(String key) {\n return localize(defaultLocale).getField(key);\n }\n\n /**\n * Extracts a field from the fields set of the active locale, result type is inferred.\n *\n * @param locale locale to be used.\n * @param key field key.\n * @param <T> type.\n * @return field value, null if it doesn't exist.\n */\n public <T> T getField(String locale, String key) {\n return localize(locale).getField(key);\n }\n\n /**\n * Internal method for updating contents of a field.\n * <p>\n * This method is used by the SDK to generate objects based on raw fields.\n *\n * <b>Do not use this field to update data on Contentful. Take a look at the CMA-SDK for that.</b>\n *\n * @param locale locale to be updated.\n * @param key the key of the field to be updated.\n * @param value the value of the field to be used.\n */\n @SuppressWarnings(\"unchecked\")\n public void setField(String locale, String key, Object value) {\n ((Map<String, Object>) fields.get(key)).put(locale, value);\n }\n\n /**\n * @return raw unprocessed fields.\n */\n public Map<String, Object> rawFields() {\n return rawFields;\n }\n}",
"public class SynchronizedSpace extends ArrayResource {\n private static final long serialVersionUID = 8618757744312417604L;\n String nextPageUrl;\n\n String nextSyncUrl;\n\n Set<String> deletedAssets;\n\n Set<String> deletedEntries;\n\n /**\n * @return url to the next sync.\n */\n public String nextSyncUrl() {\n return nextSyncUrl;\n }\n\n /**\n * @return url of next page, containing more data.\n */\n String nextPageUrl() {\n return nextPageUrl;\n }\n\n /**\n * @return deleted asset ids.\n */\n public Set<String> deletedAssets() {\n return deletedAssets;\n }\n\n /**\n * @return deleted entry ids.\n */\n public Set<String> deletedEntries() {\n return deletedEntries;\n }\n}",
"public static SyncType onlyDeletedAssets() {\n return new SyncType(DeletedAsset, null);\n}"
] | import com.contentful.java.cda.CDAAsset;
import com.contentful.java.cda.CDAClient;
import com.contentful.java.cda.CDAEntry;
import com.contentful.java.cda.CDALocale;
import com.contentful.java.cda.CDASpace;
import com.contentful.java.cda.LocalizedResource;
import com.contentful.java.cda.SynchronizedSpace;
import java.util.List;
import static com.contentful.java.cda.CDAType.SPACE;
import static com.contentful.java.cda.SyncType.onlyDeletedAssets;
import static com.google.common.truth.Truth.assertThat; | package com.contentful.java.cda.integration;
public class IntegrationWithMasterEnvironment extends Integration {
@Override public void setUp() {
client = CDAClient.builder()
.setSpace("5s4tdjmyjfpl")
.setToken("84017d3a5da6d3ae9c733c6c210c55eebc3da033730b4e5093a6e6aa099b4995")
.setEnvironment("master")
.build();
}
// space id and so on changed on master
@Override public void fetchSpace() {
CDASpace space = client.fetchSpace();
assertThat(space.name()).isEqualTo("Contentful Example API with En");
assertThat(space.id()).isEqualTo("5s4tdjmyjfpl");
assertThat(space.type()).isEqualTo(SPACE);
}
// asset url changed between master and staging
@Override public void fetchSpecificAsset() {
CDAAsset entry = client.fetch(CDAAsset.class).one("nyancat");
assertThat(entry.url()).isEqualTo("//images.ctfassets.net/5s4tdjmyjfpl/nyancat/" +
"28850673d35cacb94192832b5f5c1960/Nyan_cat_250px_frame.png");
}
// locales have different ids
@Override public void fetchOneLocale() {
final CDALocale found = client.fetch(CDALocale.class).one("4pPeIa89F7KD3G1q47eViY");
assertThat(found.code()).isEqualTo("en-US");
assertThat(found.name()).isEqualTo("English");
assertThat(found.fallbackLocaleCode()).isNull();
assertThat(found.isDefaultLocale()).isTrue();
}
@Override void assertNyanCat(CDAEntry entry) {
assertThat(entry.id()).isEqualTo("nyancat");
assertThat(entry.<String>getField("name")).isEqualTo("Nyan Cat");
assertThat(entry.<String>getField("color")).isEqualTo("rainbow");
assertThat(entry.<String>getField("birthday")).isEqualTo("2011-04-04T22:00+00:00");
assertThat(entry.<Double>getField("lives")).isEqualTo(1337.0);
List<String> likes = entry.getField("likes");
assertThat(likes).containsExactly("rainbows", "fish");
Object bestFriend = entry.getField("bestFriend");
assertThat(bestFriend).isInstanceOf(CDAEntry.class);
assertThat(entry).isSameAs(((CDAEntry) bestFriend).getField("bestFriend"));
// Localization
final LocalizedResource.Localizer localized = entry.localize("tlh");
assertThat(localized.<String>getField("color")).isEqualTo("rainbow");
assertThat(localized.<Object>getField("non-existing-does-not-throw")).isNull();
}
@Override public void syncTypeOfDeletedAssets() { | final SynchronizedSpace space = client.sync(onlyDeletedAssets()).fetch(); | 6 |
jenkinsci/priority-sorter-plugin | src/main/java/jenkins/advancedqueue/PrioritySorterConfiguration.java | [
"public static class PriorityStrategyHolder {\n\tprivate int id = 0;\n\tprivate PriorityStrategy priorityStrategy;\n\n\tpublic PriorityStrategyHolder() {\n\t}\n\n\t@DataBoundConstructor\n\tpublic PriorityStrategyHolder(int id, PriorityStrategy priorityStrategy) {\n\t\tthis.id = id;\n\t\tthis.priorityStrategy = priorityStrategy;\n\t}\n\n\tpublic int getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(int id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic PriorityStrategy getPriorityStrategy() {\n\t\treturn priorityStrategy;\n\t}\n\n\tpublic void setPriorityStrategy(PriorityStrategy priorityStrategy) {\n\t\tthis.priorityStrategy = priorityStrategy;\n\t}\n\n}",
"public class PriorityJobProperty extends JobProperty<Job<?, ?>> {\n\n\tprivate final static Logger LOGGER = Logger.getLogger(PriorityJobProperty.class.getName());\n\n\tpublic final boolean useJobPriority;\n\tpublic final int priority;\n\n\t@Override\n\tpublic JobProperty<?> reconfigure(StaplerRequest req, JSONObject form) throws FormException {\n\t\treturn super.reconfigure(req, form);\n\t}\n\n\t@DataBoundConstructor\n\tpublic PriorityJobProperty(boolean useJobPriority, int priority) {\n\t\tthis.useJobPriority = useJobPriority;\n\t\tthis.priority = priority;\n\t}\n\n\tpublic int getPriority() {\n\t\treturn priority;\n\t}\n\n\tpublic boolean getUseJobPriority() {\n\t\treturn useJobPriority;\n\t}\n\n\t@Override\n\tpublic DescriptorImpl getDescriptor() {\n\t\treturn (DescriptorImpl) super.getDescriptor();\n\t}\n\n\t@Extension\n\tpublic static final class DescriptorImpl extends JobPropertyDescriptor {\n\t\t@SuppressFBWarnings(value=\"SIC_INNER_SHOULD_BE_STATIC_ANON\", justification=\"Commont pattern in Jenkins\")\n\t\tprivate PriorityConfigurationCallback dummyCallback = new PriorityConfigurationCallback() {\n\t\t\t\n @Override\n\t\t\tpublic PriorityConfigurationCallback setPrioritySelection(int priority, int jobGroupId, PriorityStrategy reason) {\n\t\t\t\treturn this;\n\t\t\t}\n\t\t\t\n @Override\n\t\t\tpublic PriorityConfigurationCallback setPrioritySelection(int priority) {\n\t\t\t\treturn this;\n\t\t\t}\n\t\t\t\n @Override\n\t\t\tpublic PriorityConfigurationCallback addDecisionLog(int indent, String log) {\n\t\t\t\treturn this;\n\t\t\t}\n\n @Override\n\t\t\tpublic PriorityConfigurationCallback setPrioritySelection(int priority, long sortAsInQueueSince,\n\t\t\t\t\tint jobGroupId, PriorityStrategy reason) {\n\t\t\t\treturn this;\n\t\t\t}\n\t\t};\n\t\t\n\t\t@Override\n\t\tpublic String getDisplayName() {\n\t\t\treturn Messages.AdvancedQueueSorterJobProperty_displayName();\n\t\t}\n\n\t\tpublic int getDefault() {\n\t\t\treturn PrioritySorterConfiguration.get().getStrategy().getDefaultPriority();\n\t\t}\n\n\t\tpublic ListBoxModel getPriorities() {\n\t\t\tListBoxModel items = PrioritySorterConfiguration.get().doGetPriorityItems();\n\t\t\treturn items;\n\t\t}\n\n\t\tpublic boolean isUsed(Job<?,?> owner) {\n\t\t\tPriorityConfiguration configuration = PriorityConfiguration.get();\n\t\t\tJobGroup jobGroup = configuration.getJobGroup(dummyCallback, owner);\n\t\t\tif(jobGroup != null && jobGroup.isUsePriorityStrategies()) {\n\t\t\t\tList<PriorityStrategyHolder> priorityStrategies = jobGroup.getPriorityStrategies();\n\t\t\t\tfor (PriorityStrategyHolder priorityStrategyHolder : priorityStrategies) {\n\t\t\t\t\tif(priorityStrategyHolder.getPriorityStrategy() instanceof JobPropertyStrategy) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t}\n}",
"public abstract class SorterStrategy implements ExtensionPoint, Describable<SorterStrategy> {\n\n\tpublic SorterStrategyDescriptor getDescriptor() {\n\t\treturn (SorterStrategyDescriptor) Jenkins.get().getDescriptorOrDie(getClass());\n\t}\n\n\t/**\n\t * Called when a new {@link hudson.model.Item} enters the queue.\n\t * \n\t * @param item the {@link hudson.model.Queue.WaitingItem} or {@link hudson.model.BuildableItem} that\n\t * enters the queue\n\t * @param weightCallback the callback holds the priority to use anded the called method must set\n\t * the weight before returning\n\t * @return the {@link SorterStrategyCallback} provided to the call must be returned\n\t */\n\tpublic abstract SorterStrategyCallback onNewItem(@NonNull Queue.Item item, SorterStrategyCallback weightCallback);\n\n\t/**\n\t * Called when a {@link hudson.model.Item} leaves the queue and it is started.\n\t * \n\t * @param item the {@link hudson.model.Queue.LeftItem}\n\t * @param weight the weight assigned when the item entered the queue\n\t */\n\tpublic void onStartedItem(@NonNull LeftItem item, float weight) {\n\t}\n\n\t/**\n\t * Called when a {@link hudson.model.Item} leaves the queue and it is canceled.\n\t */\n\tpublic void onCanceledItem(@NonNull LeftItem item) {\n\t};\n\n\t/**\n\t * Gets number of priority buckets to be used.\n\t * \n\t */\n\tpublic abstract int getNumberOfPriorities();\n\n\t/**\n\t * Gets a default priority bucket to be used.\n\t * \n\t */\n\tpublic abstract int getDefaultPriority();\n\n\tpublic static List<SorterStrategyDescriptor> getAllSorterStrategies() {\n\t\tExtensionList<SorterStrategy> all = all();\n\t\tArrayList<SorterStrategyDescriptor> strategies = new ArrayList<SorterStrategyDescriptor>(all.size());\n\t\tfor (SorterStrategy prioritySorterStrategy : all) {\n\t\t\tstrategies.add(prioritySorterStrategy.getDescriptor());\n\t\t}\n\t\treturn strategies;\n\t}\n\n\t@CheckForNull\n\tpublic static SorterStrategyDescriptor getSorterStrategy(String key) {\n\t\tList<SorterStrategyDescriptor> allSorterStrategies = getAllSorterStrategies();\n\t\tfor (SorterStrategyDescriptor sorterStrategy : allSorterStrategies) {\n\t\t\tif (key.equals(sorterStrategy.getKey())) {\n\t\t\t\treturn sorterStrategy;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\t@CheckForNull\n\tpublic static SorterStrategy getPrioritySorterStrategy(SorterStrategyDescriptor sorterStrategy) {\n\t\tExtensionList<SorterStrategy> all = all();\n\t\tfor (SorterStrategy prioritySorterStrategy : all) {\n\t\t\tif (prioritySorterStrategy.getDescriptor().getKey().equals(sorterStrategy.getKey())) {\n\t\t\t\treturn prioritySorterStrategy;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\t/**\n\t * All registered {@link SorterStrategy}s.\n\t */\n\tpublic static ExtensionList<SorterStrategy> all() {\n\t\treturn Jenkins.get().getExtensionList(SorterStrategy.class);\n\t}\n}",
"public abstract class SorterStrategyDescriptor extends Descriptor<SorterStrategy> {\n\t/**\n\t * Returns a short name of strategy, which can be used as a unique id.\n\t * \n\t * @return Short name of the sorter strategy.\n\t */\n\tpublic abstract String getShortName();\n\n\tpublic String getKey() {\n\t\treturn getShortName();\n\t}\n}",
"public class AbsoluteStrategy extends MultiBucketStrategy {\n\n\tpublic AbsoluteStrategy() {\n\t}\n\n\t@DataBoundConstructor\n\tpublic AbsoluteStrategy(int numberOfPriorities, int defaultPriority) {\n\t\tsuper(numberOfPriorities, defaultPriority);\n\t}\n\n\t@Override\n\tpublic SorterStrategyCallback onNewItem(Queue.Item item, SorterStrategyCallback weightCallback) {\n\t\treturn weightCallback.setWeightSelection(weightCallback.getPriority());\n\t}\n\n\t@Extension\n\tpublic static class DescriptorImpl extends MultiBucketStrategyDescriptor {\n\n\t\t@Override\n\t\tpublic String getDisplayName() {\n\t\t\treturn Messages.SorterStrategy_ABSOLUTE_displayName();\n\t\t}\n\n\t\t@Override\n\t\tpublic String getShortName() {\n\t\t\treturn Messages.SorterStrategy_ABSOLUTE_shortName();\n\t\t}\n\t}\n}",
"public abstract class MultiBucketStrategy extends SorterStrategy {\n\tpublic static final int DEFAULT_PRIORITIES_NUMBER = 5;\n\tpublic static final int DEFAULT_PRIORITY = 3;\n\n\tprivate final int numberOfPriorities;\n\tprivate final int defaultPriority;\n\n\tpublic MultiBucketStrategy() {\n\t\tthis(DEFAULT_PRIORITIES_NUMBER, DEFAULT_PRIORITY);\n\t}\n\n\tpublic MultiBucketStrategy(int numberOfPriorities, int defaultPriority) {\n\t\tthis.numberOfPriorities = numberOfPriorities;\n\t\tthis.defaultPriority = defaultPriority;\n\t}\n\n\t@Override\n\tpublic final int getNumberOfPriorities() {\n\t\treturn numberOfPriorities;\n\t}\n\n\t@Override\n\tpublic final int getDefaultPriority() {\n\t\treturn defaultPriority;\n\t}\n\n\tpublic ListBoxModel doFillDefaultPriorityItems() {\n\t\t// TODO: replace by dynamic retrieval\n\t\tthrow new RuntimeException();\n\t}\n\n\tpublic abstract static class MultiBucketStrategyDescriptor extends SorterStrategyDescriptor {\n\n\t\tpublic ListBoxModel doUpdateDefaultPriorityItems(@QueryParameter(\"value\") String strValue) {\n\t\t\tint value = DEFAULT_PRIORITY;\n\t\t\ttry {\n\t\t\t\tvalue = Integer.parseInt(strValue);\n\t\t\t} catch (NumberFormatException e) {\n\t\t\t\t// Use default value\n\t\t\t}\n\t\t\tListBoxModel items = internalFillDefaultPriorityItems(value);\n\t\t\treturn items;\n\t\t}\n\n\t\tpublic ListBoxModel doDefaultPriority(@QueryParameter(\"value\") String value) throws IOException,\n\t\t\t\tServletException {\n\t\t\treturn doUpdateDefaultPriorityItems(value);\n\t\t}\n\n\t\tprivate ListBoxModel internalFillDefaultPriorityItems(int value) {\n\t\t\tListBoxModel items = new ListBoxModel();\n\t\t\tfor (int i = 1; i <= value; i++) {\n\t\t\t\titems.add(String.valueOf(i));\n\t\t\t}\n\t\t\treturn items;\n\t\t}\n\n\t\t@CheckForNull\n\t\tprivate MultiBucketStrategy getStrategy() {\n\t\t\tSorterStrategy strategy = PrioritySorterConfiguration.get().getStrategy();\n\t\t\tif (strategy == null || !(strategy instanceof MultiBucketStrategy)) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\treturn (MultiBucketStrategy) strategy;\n\t\t}\n\n\t\tpublic ListBoxModel doFillDefaultPriorityItems() {\n\t\t\tMultiBucketStrategy strategy = getStrategy();\n\t\t\tif (strategy == null) {\n\t\t\t\treturn internalFillDefaultPriorityItems(DEFAULT_PRIORITIES_NUMBER);\n\t\t\t}\n\t\t\treturn internalFillDefaultPriorityItems(strategy.getNumberOfPriorities());\n\t\t}\n\n\t\tpublic int getDefaultPrioritiesNumber() {\n\t\t\tMultiBucketStrategy strategy = getStrategy();\n\t\t\tif (strategy == null) {\n\t\t\t\treturn DEFAULT_PRIORITIES_NUMBER;\n\t\t\t}\n\t\t\treturn strategy.getNumberOfPriorities();\n\t\t}\n\n\t\tpublic int getDefaultPriority() {\n\t\t\tMultiBucketStrategy strategy = getStrategy();\n\t\t\tif (strategy == null) {\n\t\t\t\treturn DEFAULT_PRIORITY;\n\t\t\t}\n\t\t\treturn strategy.getDefaultPriority();\n\t\t}\n\t}\n}",
"public class PrioritySorterUtil {\n\t\n\tstatic public ListBoxModel fillPriorityItems(int to) {\n\t\treturn fillPriorityItems(1, to);\n\t}\n\n\tstatic public ListBoxModel fillPriorityItems(int from, int to) {\n\t\tListBoxModel items = new ListBoxModel();\n\t\tfor (int i = from; i <= to; i++) {\n\t\t\titems.add(String.valueOf(i));\n\t\t}\n\t\treturn items;\n\t}\n\n}"
] | import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.Extension;
import hudson.model.Job;
import hudson.security.ACL;
import hudson.security.ACLContext;
import hudson.util.FormValidation;
import hudson.util.ListBoxModel;
import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import jenkins.advancedqueue.JobGroup.PriorityStrategyHolder;
import jenkins.advancedqueue.priority.strategy.PriorityJobProperty;
import jenkins.advancedqueue.sorter.SorterStrategy;
import jenkins.advancedqueue.sorter.SorterStrategyDescriptor;
import jenkins.advancedqueue.sorter.strategy.AbsoluteStrategy;
import jenkins.advancedqueue.sorter.strategy.MultiBucketStrategy;
import jenkins.advancedqueue.util.PrioritySorterUtil;
import jenkins.model.GlobalConfiguration;
import jenkins.model.Jenkins;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest; | /*
* The MIT License
*
* Copyright (c) 2013, Magnus Sandberg
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package jenkins.advancedqueue;
/**
* @author Magnus Sandberg
* @since 2.0
*/
@Extension
public class PrioritySorterConfiguration extends GlobalConfiguration {
private final static Logger LOGGER = Logger.getLogger(PrioritySorterConfiguration.class.getName());
private final static SorterStrategy DEFAULT_STRATEGY = new AbsoluteStrategy(
MultiBucketStrategy.DEFAULT_PRIORITIES_NUMBER, MultiBucketStrategy.DEFAULT_PRIORITY);
/**
* @deprecated used in 2.x - replaces with XXX
*/
@Deprecated
private boolean allowPriorityOnJobs;
private boolean onlyAdminsMayEditPriorityConfiguration = false;
private SorterStrategy strategy;
public PrioritySorterConfiguration() {
}
public static void init() {
PrioritySorterConfiguration prioritySorterConfiguration = PrioritySorterConfiguration.get();
// Make sure default is good for updating from legacy
prioritySorterConfiguration.strategy = DEFAULT_STRATEGY; // TODO: replace with class ref
prioritySorterConfiguration.allowPriorityOnJobs = false;
prioritySorterConfiguration.load();
}
@Override
public boolean configure(StaplerRequest req, JSONObject json) throws FormException {
int prevNumberOfPriorities = strategy.getNumberOfPriorities();
strategy = req.bindJSON(SorterStrategy.class, json.getJSONObject("strategy"));
int newNumberOfPriorities = strategy.getNumberOfPriorities();
FormValidation numberOfPrioritiesCheck = doCheckNumberOfPriorities(String.valueOf(newNumberOfPriorities));
if (numberOfPrioritiesCheck.kind != FormValidation.Kind.OK) {
throw new FormException(numberOfPrioritiesCheck.getMessage(), "numberOfPriorities");
}
//
onlyAdminsMayEditPriorityConfiguration = json.getBoolean("onlyAdminsMayEditPriorityConfiguration");
//
updatePriorities(prevNumberOfPriorities);
//
save();
return true;
}
public boolean getOnlyAdminsMayEditPriorityConfiguration() {
return onlyAdminsMayEditPriorityConfiguration;
}
public SorterStrategy getStrategy() {
return strategy;
}
public ListBoxModel doFillStrategyItems() {
ListBoxModel strategies = new ListBoxModel(); | List<SorterStrategyDescriptor> values = SorterStrategy.getAllSorterStrategies(); | 3 |
ni3po42/traction.mvc | traction/src/main/java/traction/mvc/implementations/ui/menubinding/MenuBinding.java | [
"public class BindingInventory\n extends ObservableObject\n{\n\t/**\n\t * patterns for parsing property chains\n\t */\n\tprivate final static Pattern pathPattern = Pattern.compile(\"(\\\\\\\\|[\\\\.]*)(.+)\");\n\tprivate final static Pattern split = Pattern.compile(\"\\\\.\");\n\n\t//used for determining a range of paths to get from the inventory. Useful for getting all properties down a \n\t//specific branch\n\tprivate final static String pathTerminator = \"{\";\n\t\n\t//current context object, may be the view model or model\n\tprivate IProxyObservableObject context;\n\tprivate Object nonObservableContext;\n\n\t//there may be many levels of inventories, this points to the parent inventory. will be null if it is the root\n\tprivate BindingInventory parentInventory;\n\n\tprivate final TreeMap<String, PathBinding> map = new TreeMap<String, PathBinding>();\n\n @Override\n public void onEvent(String propagationId)\n {\n onContextSignaled(propagationId);\n }\n\n private String[] tempStringArray = new String[0];\n\n\tpublic void onContextSignaled(String path)\n\t{\n\t\tObject value = null;\n\n if (path != null && map.containsKey(path))\n value = dereferenceValue(path);\n\n\t\tif (path == null || !map.containsKey(path))\n\t\t{\n path = (path == null) ? \"\" : path + \".\";\n\t\t\t\n\t\t\tNavigableMap<String, PathBinding> subMap = map.subMap(path, false, path+pathTerminator, true);\n\n\t\t\tSet<String> keys = subMap.keySet();\n\t\t\ttempStringArray = keys.toArray(tempStringArray);\n\t\t\t\n\t\t\tfor(int i = 0;i< keys.size();i++)\n\t\t\t{\n\t\t\t\tString subPath = tempStringArray[i];\n\t\t\t\tArrayList<IUIElement<?>> elements = subMap.get(subPath).getUIElements();\n\t\t\t\tObject subValue = dereferenceValue(subPath);\n\t\t\t\t\t\t\t\t\t\n\t\t\t\tfor(int j=0;j<elements.size();j++)\n\t\t\t\t{\n\t\t\t\t\telements.get(j).receiveUpdate(subValue);\n\t\t\t\t}\n\t\t\t}\t\t\t\n\t\t}\n\t\telse\n\t\t{\n\t\t\tArrayList<IUIElement<?>> elements = map.get(path).getUIElements();\n\t\t\tfor(int i=0;i<elements.size();i++)\n\t\t\t{\n\t\t\t\telements.get(i).receiveUpdate(value);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic BindingInventory()\n\t{\n\n\t}\n\t\n\tpublic BindingInventory(BindingInventory parentInventory)\n\t{\n\t\tsetParentInventory(parentInventory);\n\t}\n\t\n\tpublic BindingInventory getParentInventory()\n\t{\n\t\treturn parentInventory;\n\t}\n\n public void merge(BindingInventory inventoryToMerge)\n {\n Iterator<PathBinding> collection = inventoryToMerge.map.values().iterator();\n\n while(collection.hasNext())\n {\n PathBinding current = collection.next();\n ArrayList<IUIElement<?>> elements = current.getUIElements();\n if (elements != null)\n {\n int size = elements.size();\n for(int i=0;i<size;i++)\n {\n elements.get(i).track(this);\n }\n }\n }\n\n inventoryToMerge.map.clear();\n inventoryToMerge.setContextObject(null);\n }\n\n\t@SuppressWarnings({ \"unchecked\", \"rawtypes\" })\n\tpublic void fireCommand(String commandPath, CommandArgument commandArg)\n\t{\n\t\tObject command = dereferenceValue(commandPath);\n\t\tif (command instanceof IObservableCommand)\n\t\t{\n IObservableCommand c = (IObservableCommand)command;\n\t\t\tc.execute(commandArg);\n\t\t}\n else\n {\n if (commandArg != null)\n commandArg.setEventCancelled(true);\n }\n\t}\n\n\tpublic void setParentInventory(BindingInventory parentInventory)\n\t{\n\t\tthis.parentInventory = parentInventory;\n\t}\n\t\n\tpublic BindingInventory getRootInventory()\n\t{\n\t\tBindingInventory parentInventory = this;\t\t\n\t\twhile(parentInventory.getParentInventory() != null)\n\t\t{\n\t\t\tparentInventory = parentInventory.getParentInventory();\n\t\t}\n\t\treturn parentInventory;\n\t}\n\t\n\tpublic BindingInventory getInventoryByLevel(int level)\n\t{\n\t\tBindingInventory parentInventory = this;\t\n\t\tfor(int i = 0;i < level; i++)\n\t\t{\n\t\t\tif (parentInventory.getParentInventory() == null)\n\t\t\t\treturn null;\n\t\t\t\n\t\t\tparentInventory = parentInventory.getParentInventory();\n\t\t}\n\t\treturn parentInventory;\n\t}\n\t\n\tpublic void setContextObject(Object object)\n\t{\n\t\tif (context != null)\n\t\t\tcontext.getProxyObservableObject().getObservable().unregisterListener(\"\", this);\n if (object instanceof IProxyObservableObject)\n\t\t context = (IProxyObservableObject)object;\n else\n nonObservableContext = object;\n\n\t\tif (context != null)\n\t\t\tcontext.getProxyObservableObject().getObservable().registerListener(\"\", this);\n\t}\n\n public Object getContextObject()\n {\n if (context == null && nonObservableContext != null)\n return nonObservableContext;\n else\n return context;\n }\n\n private Object extractSource()\n {\n if (nonObservableContext != null)\n return nonObservableContext;\n else\n return context.getProxyObservableObject().getSource();\n }\n\n\tpublic void track (IUIElement<?> element, String path)\n\t{\n\t\tif (path == null)\n\t\t\treturn;//no path, no track.\n\t\t\n\t\tif (!map.containsKey(path))\n\t\t{\n\t\t\tmap.put(path, new PathBinding());\n\t\t}\n\t\tPathBinding p = map.get(path);\n\t\tp.addUIElement(element);\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tpublic void sendUpdate(String path, Object value)\n\t{\n\t\tif (path == null || path.equals(\".\"))\n\t\t\treturn;\n\t\t\n\t\tMatcher matches = pathPattern.matcher(path);\n\t\tif (!matches.find())\n\t\t\treturn;\n\t\t\n\t\tBindingInventory currentInventory = getInventoryByMatchedPattern(matches);\n\t\tObject currentContext = currentInventory.extractSource();\n\t\tString[] chains = split.split(matches.group(2));\n\t\tProperty<Object,Object> prop = null;\n\t\t\n\t\t for(int i=0;i<chains.length;i++)\n\t\t { \t\t\n\t\t\t if (currentContext == null)\n\t\t\t\t return;\n\n\t\t\t String member =chains[i];\n\n if (currentContext instanceof IPOJO)\n {\n prop = ((IPOJO)currentContext).getProperty(member);\n }\n else\n {\n\t\t\t prop = (Property<Object, Object>) PropertyStore.find(currentContext.getClass(), member);\n }\n\n\t\t\tif (i + 1 < chains.length)\n\t\t\t{\n\t\t\t\tcurrentContext = extractByProxy(prop.get(currentContext));\n\t\t\t}\n\t\t }\n\t\t\t\n\t\t if (currentContext == null)\n\t\t\t return;//throw new NullPointerException(\"Cannot send value update to null object.\");\n\t\t if (prop == null)\n\t\t\t throw new InvalidParameterException(\"invalid path supplied: \"+path);\n\t\t \n\t\t Object propertyCurrentValue = extractByProxy(prop.get(currentContext));\n\t\t\t\t \n\t\t if ((propertyCurrentValue != null && !propertyCurrentValue.equals(value))\t\t\t\t \n\t\t\t\t || (propertyCurrentValue == null && value != null))\n prop.set(currentContext,value);\n\t}\n\n\tprivate BindingInventory getInventoryByMatchedPattern(Matcher matches)\n\t{\n\t\tBindingInventory currentInventory = this;\n\t\tString up = matches.group(1);\n\t\t\n\t\tif (up != null && up.length() == 1 && up.equals(\"\\\\\"))\n\t\t{\n\t\t\tcurrentInventory = getRootInventory();\t\t\t\t\n\t\t}\n\t\telse if (up != null && up.length() > 0)\n\t\t{\n\t\t\tcurrentInventory = getInventoryByLevel(up.length());\n\t\t}\n\t\treturn currentInventory;\n\t}\n\n public static Object generalDereferencedValue(Object source, String path)\n {\n if (path == null)\n return null;\n\n Matcher matches = pathPattern.matcher(path);\n\n if (!matches.find())\n return null;\n\n String[] chains = split.split(matches.group(2));\n\n for(int i=0;i<chains.length;i++)\n {\n if (source == null)\n return null;\n\n String member = chains[i];\n Property<Object,Object> prop;\n if (source instanceof IPOJO)\n prop = ((IPOJO)source).getProperty(member);\n else\n prop = (Property<Object, Object>) PropertyStore.find(source.getClass(), member);\n\n if (prop == null)\n return null;\n\n source = extractByProxy(prop.get(source));\n }\n return source;\n }\n\n\t@SuppressWarnings(\"unchecked\")\n public Object dereferenceValue(String path)\n {\n\t\tif (path == null)\n\t\t\treturn null;\n\t\t\n\t\tif (path.equals(\".\"))\n {\n if (context == null)\n return nonObservableContext;\n else\n return context;\n }\n\t\t\n\t\tMatcher matches = pathPattern.matcher(path);\n\t\t\n\t\tif (!matches.find())\n\t\t\treturn null;\n\t\t\n\t\tBindingInventory currentInventory = getInventoryByMatchedPattern(matches);\n\t\t\t\n\t\tObject currentContext = currentInventory.extractSource();\n\t\treturn generalDereferencedValue(currentContext, path);\n\t}\t\n\t\n\tprivate static Object extractByProxy(Object obj)\n\t{\n\t\tif (obj instanceof IProxyObservableObject)\n\t\t\t return((IProxyObservableObject)obj).getProxyObservableObject().getSource();\n\t\treturn obj;\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n public Class<?> dereferencePropertyType(String path)\n\t{\n if (path == null)\n return null;\n\n\t\tif (path != null && path.equals(\".\"))\n\t\t\treturn context.getProxyObservableObject().getSource() == null ? null : context.getProxyObservableObject().getSource().getClass();\n\t\t\n\t\tMatcher matches = pathPattern.matcher(path);\n\t\tif (!matches.find())\n\t\t\treturn null;\n\t\t\n\t\tBindingInventory currentInventory = getInventoryByMatchedPattern(matches);\n\t\t\t\t\n\t\tObject currentContext = currentInventory.extractSource();\n\n\t\tString[] chains = split.split(matches.group(2));\n\t\t\n\t\tProperty<Object,Object> prop = null;\n\t\t\n\t\t for(int i=0;i<chains.length;i++)\n\t\t { \t\t\n\t\t\t if (currentContext == null)\n\t\t\t\t return null;\n\t\t\t String member = chains[i];\n\n if (currentContext instanceof IPOJO)\n prop = ((IPOJO)currentContext).getProperty(member);\n else\n\t\t\t prop = (Property<Object, Object>) PropertyStore.find(currentContext.getClass(), member);\n\n\t\t\tif (i + 1 < chains.length)\n\t\t\t{\n\t\t\t\tcurrentContext = extractByProxy(prop.get(currentContext));\n\t\t\t}\n\t\t }\n\t\t\t\n\t\t if (prop == null)\n\t\t\t throw new InvalidParameterException(\"invalid path supplied: \"+path);\n\t\t \n\t\t return prop.getType();\n\t}\n\n public void clearAll()\n {\n map.clear();\n }\n\n //will not support property store!\n @Override\n protected IPropertyStore getPropertyStore() {\n return null;\n }\n}",
"public class UIEvent\nimplements IUIElement<CommandArgument>\n{\n protected String[] paths;\n\n private IUIElement.IUIUpdateListener<CommandArgument> updateListener;\n\n private boolean _isUpdating;\n\n protected String pathAttribute = null;\n protected final IViewBinding parentViewBinding;\n\n @SuppressWarnings(\"unused\")\n private UIEvent(){parentViewBinding = null;}\n\n public UIEvent(IProxyViewBinding viewBinding, String pathAttribute)\n {\n this.parentViewBinding = viewBinding.getProxyViewBinding();\n this.pathAttribute = pathAttribute;\n this.parentViewBinding.registerUIElement(this);\n }\n\n /**\n * @return : true when element is currently sending an update back to the model or view-model\n */\n public boolean isUpdating()\n {\n return _isUpdating;\n }\n\n /**\n * Initiates the BindingInventory to send data to the model/view-model\n */\n public void sendUpdate(CommandArgument value)\n {\n if (paths == null)\n return;\n\n disableReceiveUpdates();\n for(int i=0;i< paths.length; i++)\n getBindingInventory().sendUpdate(paths[i], value);\n enableReceiveUpdates();\n }\n\n @Override\n public void setUIUpdateListener(IUIElement.IUIUpdateListener<CommandArgument> listener)\n {\n this.updateListener = listener;\n }\n\n @Override\n public void receiveUpdate(final Object value)\n {\n if (updateListener == null)\n return;\n\n synchronized(this)\n {\n //is true is 'disableReceiveUpdates' has been called before 'enablRecieveUpdates'\n //This is also the case if UIProperty has called the 'sendUpdate' method\n if (isUpdating())\n return;\n\n //if no handler, then just run on current thread\n if (getUIHandler() == null)\n {\n updateListener.onUpdate((CommandArgument)value);\n }\n else\n {\n //call the update listener on the UI thread. Needs to be on the UI thread because it is most\n //certainly updating something on the UI\n getUIHandler().tryPostImmediatelyToUIThread(new Runnable()\n {\n @Override\n public void run()\n {\n updateListener.onUpdate((CommandArgument) value);\n }\n });\n }\n }\n }\n\n @Override\n public void initialize() throws Exception\n {\n if (pathAttribute == null)\n return;\n\n JSONObject tagProperties =parentViewBinding.getTagProperties();\n JSONArray tempPaths = tagProperties.has(pathAttribute) ? tagProperties.getJSONArray(pathAttribute) : null;\n\n if (tempPaths == null)\n return;\n\n this.paths = new String[tempPaths.length()];\n for(int i=0;i<paths.length;i++)\n {\n if (parentViewBinding.getPathPrefix() != null)\n this.paths[i] = parentViewBinding.getPathPrefix() + \".\" + tempPaths.getString(i);\n else\n this.paths[i] = tempPaths.getString(i);\n getBindingInventory().track(this, this.paths[i]);\n }\n }\n\n protected void disableReceiveUpdates()\n {\n synchronized(this)\n {\n _isUpdating = true;\n }\n }\n\n protected void enableReceiveUpdates()\n {\n synchronized(this)\n {\n _isUpdating = false;\n }\n }\n\n protected String getPropertyName(int index)\n {\n if (paths == null || paths.length <= index)\n return null;\n if (\".\".equals(paths[index]))\n return null;\n\n int dotIndex = paths[index].lastIndexOf(\".\");\n return paths[index].substring(dotIndex+1);\n }\n\n @Override\n public BindingInventory getBindingInventory()\n {\n return parentViewBinding.getBindingInventory();\n }\n\n @Override\n public boolean isDefined()\n {\n return paths != null;\n }\n\n @Override\n public void track(BindingInventory differentBindingInventory)\n {\n if (paths == null || paths.length ==0)\n return;\n for(int i=0;i<paths.length;i++)\n {\n differentBindingInventory.track(this, this.paths[i]);\n }\n }\n\n protected UIHandler getUIHandler()\n {\n return parentViewBinding.getUIHandler();\n }\n\n\t/**\n\t * Lets a UIEvent signal a bounded command\n\t * @param arg\n\t */\n\tpublic boolean execute(CommandArgument arg)\n\t{\n if (paths == null || paths.length == 0)\n return true;\n\n for(int i=0;i<paths.length;i++)\n {\n CommandArgument baseArg = arg;\n if (baseArg == null && parentViewBinding != null)\n baseArg = new CommandArgument(getPropertyName(i), parentViewBinding.getTagProperties());\n else if (parentViewBinding == null)\n baseArg = new CommandArgument(getPropertyName(i));\n\n getBindingInventory().fireCommand(paths[i], baseArg);\n if (baseArg.isEventCancelled())\n return false;\n }\n return true;\n\t}\t\t\t\n}",
"public class UIHandler extends Handler\n{\n\tprivate Thread uiThread;\n\tpublic UIHandler()\n\t{\n\t\t//save an instance of the current thread, where it was created.\n\t\tuiThread = Thread.currentThread();\n\t}\n\n\tpublic void tryPostImmediatelyToUIThread(Runnable action)\n\t{\n\t\t//if the current thread is same as the one where handler was, just run it, otherwise, post it.\n\t\t//this is very similar to how the activity can runOnUiThread.\n\t\t if (Thread.currentThread() != uiThread) {\n\t post(action);\n\t } else {\n\t action.run();\n\t }\n\t}\n}",
"public class UIProperty<T>\nimplements IUIElement<T>\n{\t\t\t\t\n\tprotected String path;\n protected T tempValue;\n\n\tprivate IUIElement.IUIUpdateListener<T> updateListener;\t\t\n\t\n\tprivate boolean _isUpdating;\n\t\n\tprotected String pathAttribute = null;\n\tprotected final IViewBinding parentViewBinding;\n\n @SuppressWarnings(\"unused\")\n private UIProperty(){parentViewBinding = null;}\n\n\tpublic UIProperty(IProxyViewBinding viewBinding, String pathAttribute)\n\t{\n this.parentViewBinding = viewBinding.getProxyViewBinding();\n\t\tthis.pathAttribute = pathAttribute;\n this.parentViewBinding.registerUIElement(this);\n\t}\n\t\n\tpublic UIProperty(IProxyViewBinding viewBinding)\n\t{\n this.parentViewBinding = viewBinding.getProxyViewBinding();\n this.parentViewBinding.registerUIElement(this);\n\t}\n\t\n\t/**\n\t * @return : true when element is currently sending an update back to the model or view-model\n\t */\n\tpublic boolean isUpdating()\n\t{\n\t\treturn _isUpdating;\n\t}\n\n\t/**\n\t * Initiates the BindingInventory to send data to the model/view-model\n\t */\n\tpublic void sendUpdate(T value)\n\t{\t\n\t\tif (path == null)\n\t\t\treturn;\n\t\t\n\t\tdisableReceiveUpdates();\n getBindingInventory().sendUpdate(path, value);\n\t\tenableReceiveUpdates();\n\t}\n\n public T dereferenceValue()\n {\n return (T) getBindingInventory().dereferenceValue(path);\n }\n\n public T getTempValue()\n {\n return tempValue;\n }\n\n public void setTempValue(T value)\n {\n this.tempValue = value;\n }\n\n @Override\n\tpublic void setUIUpdateListener(IUIElement.IUIUpdateListener<T> listener)\n\t{\n\t\tthis.updateListener = listener;\n\t}\n\n @Override\n public void receiveUpdate(final Object value)\n {\n if (updateListener == null)\n return;\n\n synchronized(this)\n {\n //is true is 'disableReceiveUpdates' has been called before 'enablRecieveUpdates'\n //This is also the case if UIProperty has called the 'sendUpdate' method\n if (isUpdating())\n return;\n\n //if no handler, then just run on current thread\n if (getUIHandler() == null)\n {\n updateListener.onUpdate((T)value);\n }\n else\n {\n //call the update listener on the UI thread. Needs to be on the UI thread because it is most\n //certainly updating something on the UI\n getUIHandler().tryPostImmediatelyToUIThread(new Runnable()\n {\n @Override\n public void run()\n {\n updateListener.onUpdate((T) value);\n }\n });\n }\n }\n }\n\n\t@Override\n\tpublic void initialize() throws Exception\n\t{\n JSONObject tagProperties =parentViewBinding.getTagProperties();\n if (tagProperties != null)\n {\n String tempPath = tagProperties.has(pathAttribute) ? tagProperties.getString(pathAttribute) : null;\n\n if (pathAttribute != null) {\n if (parentViewBinding.getPathPrefix() == null)\n path = tempPath;\n else if (tempPath != null)\n path = parentViewBinding.getPathPrefix() + \".\" + tempPath;\n else\n path = null;\n }\n }\n getBindingInventory().track(this, path);\n\t}\n\n protected void disableReceiveUpdates()\n {\n synchronized(this)\n {\n _isUpdating = true;\n }\n }\n\n protected void enableReceiveUpdates()\n {\n synchronized(this)\n {\n _isUpdating = false;\n }\n }\n\n @Override\n\tpublic BindingInventory getBindingInventory()\n\t{\n\t\treturn parentViewBinding.getBindingInventory();\n\t}\n\n public Class<?> getDereferencedPathType()\n {\n return parentViewBinding.getBindingInventory().dereferencePropertyType(this.path);\n }\n\n @Override\n public boolean isDefined()\n {\n return path != null;\n }\n\n @Override\n public void track(BindingInventory differentBindingInventory)\n {\n if (this.path == null)\n return;\n differentBindingInventory.track(this, this.path);\n }\n\n protected UIHandler getUIHandler()\n {\n return parentViewBinding.getUIHandler();\n }\n}",
"public abstract class ViewBindingHelper<V>\n implements IViewBinding\n{\n protected ArrayList<GenericUIBindedEvent> genericBindedEvents = new ArrayList<GenericUIBindedEvent>();\n\n private ArrayList<IUIElement<?>> registeredUIElements = new ArrayList<IUIElement<?>>();\n private BindingInventory bindingInventory;\n private UIHandler uiHandler;\n private JSONObject tagProperties;\n\n private String prefix;\n\n private int bindingFlags = IViewBinding.Flags.NO_FLAGS;\n\n private boolean synthetic;\n\n public JSONObject getMetaData()\n {\n try\n {\n if (tagProperties != null && tagProperties.has(\"@meta\"))\n {\n return tagProperties.getJSONObject(\"@meta\");\n }\n }\n catch(JSONException ex)\n {\n\n }\n return null;\n }\n\n public void registerUIElement(IUIElement<?> element)\n {\n registeredUIElements.add(element);\n }\n\n protected Object getGenericBindingSource()\n {\n return getWidget();\n }\n\n /**\n * defines a generic property. These handle general properties on a view that are not explicitly defined.\n * The work very similar to the regular ui element, however with the disadvantage of not being able to signal the\n * model/view-model directly\n * @author Tim Stratton\n *\n */\n public class GenericUIBindedProperty\n extends UIProperty<Object>\n {\n //the property on the view to set and get values from\n private Property<Object, Object> viewProperty;\n\n public GenericUIBindedProperty(IViewBinding viewBinding, String pathAttribute, String path)\n {\n super(viewBinding, pathAttribute);\n this.path = path;\n setUIUpdateListener(new IUIElement.IUIUpdateListener<Object>()\n {\n @Override\n public void onUpdate(Object value)\n {\n if (viewProperty == null || viewProperty.isReadOnly() || getWidget() == null)\n return;\n if (viewProperty.getType().isPrimitive() && value == null)\n return;\n\n viewProperty.set(getGenericBindingSource(), value);\n }\n });\n }\n\n @Override\n public void initialize()\n {\n //let the property store find the property for me...\n viewProperty = (Property<Object, Object>) PropertyStore.find(getGenericBindingSource().getClass(), this.pathAttribute.trim());\n\n getBindingInventory().track(this, this.path);\n }\n\n }\n\n /**\n * defines a generic event. These handle binding commands to different types of listeners on a view. This fills the gap\n * missing from the generic properties by reacting to listener events.\n * @author Tim Stratton\n *\n */\n class GenericUIBindedEvent\n extends UIEvent\n {\n private static final int prefixWidth = 3;\n private Method setMethod;\n\n public GenericUIBindedEvent(IProxyViewBinding viewBinding, String pathAttribute) {\n super(viewBinding, pathAttribute);\n }\n\n @Override\n public void initialize() throws Exception\n {\n if (this.pathAttribute == null)\n return;\n\n JSONObject tagProperties =parentViewBinding.getTagProperties();\n JSONArray tempPaths = tagProperties.has(pathAttribute) ? tagProperties.getJSONArray(pathAttribute) : null;\n\n if (tempPaths == null)\n return;\n\n this.paths = new String[tempPaths.length()];\n /////\n Class<?> sourceClass = getGenericBindingSource().getClass();\n Method[] methods = sourceClass.getMethods();\n\n //try to find the set method for the listener. It assumes the prefix is 3 characters, like 'set' or 'add'\n try\n {\n for(int j = 0; j< methods.length;j++)\n {\n if (methods[j].getName().indexOf(this.pathAttribute) != prefixWidth)\n continue;\n setMethod = methods[j];\n break;\n }\n if (setMethod == null || setMethod.getParameterTypes().length != 1)\n throw new NoSuchMethodException();\n }\n catch(NoSuchMethodException ex)\n {\n throw new RuntimeException(\"No set/add method for listener\");\n }\n ////\n\n for(int i=0;i<paths.length;i++)\n {\n if (parentViewBinding.getPathPrefix() != null)\n this.paths[i] = parentViewBinding.getPathPrefix() + \".\" + tempPaths.getString(i);\n else\n this.paths[i] = tempPaths.getString(i);\n\n //get the first and only parameter of the method, get the type\n Class<?> listenerType = setMethod.getParameterTypes()[0];\n\n try\n {\n final int pathIndex = i;\n //try to proxy the interface, if it the interface, using a invocation handler\n Object proxy = Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{listenerType}, new InvocationHandler() {\n @Override\n public Object invoke(Object proxy, Method method, Object[] args)\n throws Throwable {\n //create generic argument with name of method call and arguments\n GenericArgument arg = new GenericArgument(GenericUIBindedEvent.this.getPropertyName(pathIndex), method.getName(), args);\n\n GenericUIBindedEvent.this.execute(arg);\n\n if (method.getReturnType().equals(Void.class))\n return null;\n\n return arg.getReturnObj();\n }\n });\n\n //add proxy listener to the method\n setMethod.invoke(getGenericBindingSource(), proxy);\n }\n catch (Exception e)\n {\n //Log.\n }\n //////\n getBindingInventory().track(this, this.paths[i]);\n }\n }\n\n /**\n * try to clear the proxy listener\n */\n public void clearProxyListener()\n {\n if (setMethod == null || getGenericBindingSource() == null)\n return;\n try\n {\n setMethod.invoke(getGenericBindingSource(), (Object[])null);\n }\n catch (Exception e)\n {\n }\n }\n\n }\n\n @Override\n public void initialise(View v, UIHandler uiHandler, BindingInventory inventory, int bindingFlags)\n {\n setBindingFlags(bindingFlags);\n setBindingInventory(inventory);\n setUiHandler(uiHandler);\n\n try\n {\n\n if (v != null && v.getTag() != null)\n {\n JSONObject tagProperties = new JSONObject(v.getTag().toString());\n setTagProperties(tagProperties);\n }\n\n for (int i = 0;i<registeredUIElements.size();i++)\n {\n registeredUIElements.get(i).initialize();\n }\n\n if (tagProperties != null && tagProperties.has(\"@Events\"))\n {\n JSONObject events = tagProperties.getJSONObject(\"@Events\");\n Iterator keys = events.keys();\n\n while (keys.hasNext())\n {\n String key = (String)keys.next();\n JSONArray values = events.getJSONArray(key);\n for(int i=0;i<values.length();i++)\n {\n GenericUIBindedEvent evnt = new GenericUIBindedEvent(this, values.getString(i).trim());\n evnt.initialize();\n }\n }\n }\n\n if (tagProperties != null && tagProperties.has(\"@Properties\"))\n {\n JSONObject props = tagProperties.getJSONObject(\"@Properties\");\n Iterator keys = props.keys();\n\n while (keys.hasNext())\n {\n String key = (String)keys.next();\n String value = props.getString(key);\n GenericUIBindedProperty prop = new GenericUIBindedProperty(this, key, value.trim());\n prop.initialize();\n }\n }\n\n\n }\n catch (Exception exception)\n {\n\n }\n }\n\n @Override\n public void detachBindings()\n {\n for(int i=0;i<genericBindedEvents.size();i++)\n {\n genericBindedEvents.get(i).clearProxyListener();\n }\n if (getBindingInventory() != null)\n getBindingInventory().clearAll();\n }\n\n @Override\n public void updateBindingInventory(BindingInventory inventory)\n {\n inventory.merge(getBindingInventory());\n bindingInventory = inventory;\n }\n\n public abstract V getWidget();\n\n public JSONObject getTagProperties()\n {\n return this.tagProperties;\n }\n\n @Override\n public BindingInventory getBindingInventory()\n {\n return bindingInventory;\n }\n\n @Override\n public UIHandler getUIHandler()\n {\n return uiHandler;\n }\n\n @Override\n public boolean isSynthetic()\n {\n return synthetic;\n }\n\n @Override\n public void markAsSynthetic(BindingInventory inventory)\n {\n synthetic = true;\n bindingFlags |= IViewBinding.Flags.IS_ROOT;\n setBindingInventory(inventory);\n uiHandler = new UIHandler();\n }\n\n public void setUiHandler(UIHandler uiHandler)\n {\n this.uiHandler = uiHandler;\n }\n\n public void setTagProperties(JSONObject tagProperties){ this.tagProperties = tagProperties;}\n\n public void setBindingInventory(BindingInventory bindingInventory)\n {\n this.bindingInventory = bindingInventory;\n }\n\n public int getBindingFlags() {\n return bindingFlags;\n }\n\n public void setBindingFlags(int bindingFlags) {\n this.bindingFlags = bindingFlags;\n }\n\n @Override\n public String getPathPrefix() {\n return prefix;\n }\n\n @Override\n public void setPathPrefix(String prefix) {\n this.prefix = prefix;\n }\n\n @Override\n public IViewBinding getProxyViewBinding()\n {\n return this;\n }\n}",
"public interface IProxyViewBinding\n{\n IViewBinding getProxyViewBinding();\n}",
"public interface IUIElement<T>\n{\n\t/**\n\t * sets a handler for when the ui recieves data from the model/view-model\n\t * @param listener\n\t */\n\tpublic void setUIUpdateListener(IUIUpdateListener<T> listener);\n\n\t/**\n\t * Sends data to the ui element. Expects the IUIUpdateListener to be called \n\t * @param value\n\t */\n\tpublic void receiveUpdate(final Object value);\n\t\n\t/**\n\t * Sends data from ui back to model/view-model\n\t * @param value\n\t */\n\tpublic void sendUpdate(T value);\n\n\t/**\n\t * Initializes data for ui element during inflation\n\t */\n\tpublic void initialize() throws Exception;\n\n\t/**\n\t * gets the binding inventory the ui element is associated to\n\t * @return\n\t */\n\tpublic BindingInventory getBindingInventory();\n\n\t/**\n\t * listener to handle updates to the ui element\n\t * @author Tim Stratton\n\t *\n\t * @param <S> : type of data sent to ui element\n\t */\n\tpublic interface IUIUpdateListener<S>\n\t{\n\t\tpublic void onUpdate(S value);\n\t}\n\n public boolean isDefined();\n\n public void track(BindingInventory differentBindingInventory);\n}",
"public interface IViewBinding\n extends IProxyViewBinding\n{\t\t\n\t/**\n\t * Initialise the ViewBinding. It is here you will read properties defined in the layout files\n\t * @param v : the view to init against\n\t * @param uiHandler : a handler for accessing the ui thread\n\t * @param inventory : inventory to register ui elements and paths\n\t */\n\tvoid initialise(View v, UIHandler uiHandler, BindingInventory inventory, int bindingFlags);\n\n void registerUIElement(IUIElement<?> element);\n\n public static class Flags\n {\n private Flags(){}\n\n public static int NO_FLAGS = 0;\n public static int IS_ROOT = 1;\n public static int IGNORE_CHILDREN = 2;\n public static int HAS_RELATIVE_CONTEXT = 4;\n public static int SCOPE_PRESENT = 8;\n\n public static boolean hasFlags(int flags, int flagsToTest)\n {\n return (flags & flagsToTest) == flagsToTest;\n }\n }\n\n\t/**\n\t * Here, you will want to unhook stuff, general clean up\n\t */\n\tvoid detachBindings();\n\n /**\n * returns the inventory passed in from the initialise method\n * @return\n */\n BindingInventory getBindingInventory();\n\n JSONObject getTagProperties();\n\n /**\n * Gets a handler to run tasks on the UI thread; whatever was passed to initialise method\n * @return\n */\n UIHandler getUIHandler();\n\n /**\n * Gets flags\n * @return\n */\n int getBindingFlags();\n\n /**\n *\n * @return\n */\n boolean isSynthetic();\n\n /**\n * marks view binding as synthetic. makes isSynthetic return true; ounce set, cannot be undone.\n */\n void markAsSynthetic(BindingInventory inventory);\n\n void updateBindingInventory(BindingInventory inventory);\n\n String getPathPrefix();\n void setPathPrefix(String prefix);\n\n}"
] | import android.view.MenuItem;
import android.view.View;
import org.json.JSONException;
import org.json.JSONObject;
import traction.mvc.observables.BindingInventory;
import traction.mvc.implementations.ui.UIEvent;
import traction.mvc.implementations.ui.UIHandler;
import traction.mvc.implementations.ui.UIProperty;
import traction.mvc.implementations.ui.viewbinding.ViewBindingHelper;
import traction.mvc.interfaces.IProxyViewBinding;
import traction.mvc.interfaces.IUIElement;
import traction.mvc.interfaces.IViewBinding; | /* Copyright 2013 Tim Stratton
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package traction.mvc.implementations.ui.menubinding;
/**
* Defines the ui elements that can bind a model/view-model to a menu item
* @author Tim Stratton
*
*/
public class MenuBinding
implements MenuItem.OnMenuItemClickListener, IProxyViewBinding
{
public final UIProperty<Boolean> IsVisible;
public final UIEvent OnClick;
private final MenuItem menuItem;
private JSONObject tagProperties;
private final ViewBindingHelper<View> helper;
public MenuBinding(MenuItem item, String tag)
{
this.menuItem = item;
try
{
this.tagProperties = new JSONObject(tag);
}
catch (JSONException ex)
{
}
helper = new ViewBindingHelper<View>()
{
@Override
public View getWidget()
{
return menuItem.getActionView();
}
@Override
public void detachBindings() {
super.detachBindings();
MenuBinding.this.detachBindings();
}
@Override | public void initialise(View notUsed, UIHandler uiHandler, BindingInventory inventory, int bindingFlags) | 2 |
achellies/AtlasForAndroid | src/android/taobao/atlas/hack/AtlasHacks.java | [
"public static interface AssertionFailureHandler {\n boolean onAssertionFailure(HackAssertionException hackAssertionException);\n}",
"public static abstract class HackDeclaration {\n\n public static class HackAssertionException extends Throwable {\n private static final long serialVersionUID = 1;\n private Class<?> mHackedClass;\n private String mHackedFieldName;\n private String mHackedMethodName;\n\n public HackAssertionException(String str) {\n super(str);\n }\n\n public HackAssertionException(Exception exception) {\n super(exception);\n }\n\n public String toString() {\n return getCause() != null ? getClass().getName() + \": \" + getCause() : super.toString();\n }\n\n public Class<?> getHackedClass() {\n return this.mHackedClass;\n }\n\n public void setHackedClass(Class<?> cls) {\n this.mHackedClass = cls;\n }\n\n public String getHackedMethodName() {\n return this.mHackedMethodName;\n }\n\n public void setHackedMethodName(String str) {\n this.mHackedMethodName = str;\n }\n\n public String getHackedFieldName() {\n return this.mHackedFieldName;\n }\n\n public void setHackedFieldName(String str) {\n this.mHackedFieldName = str;\n }\n }\n}",
"public static class HackAssertionException extends Throwable {\n private static final long serialVersionUID = 1;\n private Class<?> mHackedClass;\n private String mHackedFieldName;\n private String mHackedMethodName;\n\n public HackAssertionException(String str) {\n super(str);\n }\n\n public HackAssertionException(Exception exception) {\n super(exception);\n }\n\n public String toString() {\n return getCause() != null ? getClass().getName() + \": \" + getCause() : super.toString();\n }\n\n public Class<?> getHackedClass() {\n return this.mHackedClass;\n }\n\n public void setHackedClass(Class<?> cls) {\n this.mHackedClass = cls;\n }\n\n public String getHackedMethodName() {\n return this.mHackedMethodName;\n }\n\n public void setHackedMethodName(String str) {\n this.mHackedMethodName = str;\n }\n\n public String getHackedFieldName() {\n return this.mHackedFieldName;\n }\n\n public void setHackedFieldName(String str) {\n this.mHackedFieldName = str;\n }\n}",
"public static class HackedClass<C> {\n protected Class<C> mClass;\n\n public HackedField<C, Object> staticField(String str) throws HackAssertionException {\n return new HackedField(this.mClass, str, 8);\n }\n\n public HackedField<C, Object> field(String str) throws HackAssertionException {\n return new HackedField(this.mClass, str, 0);\n }\n\n public HackedMethod staticMethod(String str, Class<?>... clsArr) throws HackAssertionException {\n return new HackedMethod(this.mClass, str, clsArr, 8);\n }\n\n public HackedMethod method(String str, Class<?>... clsArr) throws HackAssertionException {\n return new HackedMethod(this.mClass, str, clsArr, 0);\n }\n\n public HackedConstructor constructor(Class<?>... clsArr) throws HackAssertionException {\n return new HackedConstructor(this.mClass, clsArr);\n }\n\n public HackedClass(Class<C> cls) {\n this.mClass = cls;\n }\n\n public Class<C> getmClass() {\n return this.mClass;\n }\n}",
"public static class HackedField<C, T> {\n private final Field mField;\n\n public <T2> android.taobao.atlas.hack.Hack.HackedField<C, T2> ofGenericType(Class<?> cls) throws HackAssertionException {\n if (!(this.mField == null || cls.isAssignableFrom(this.mField.getType()))) {\n Hack.fail(new HackAssertionException(new ClassCastException(this.mField + \" is not of type \" + cls)));\n }\n return this;\n }\n\n public <T2> android.taobao.atlas.hack.Hack.HackedField<C, T2> ofType(Class<T2> cls) throws HackAssertionException {\n if (!(this.mField == null || cls.isAssignableFrom(this.mField.getType()))) {\n Hack.fail(new HackAssertionException(new ClassCastException(this.mField + \" is not of type \" + cls)));\n }\n return this;\n }\n\n public android.taobao.atlas.hack.Hack.HackedField<C, T> ofType(String str) throws HackAssertionException {\n android.taobao.atlas.hack.Hack.HackedField<C, T> ofType;\n try {\n ofType = ofType(Class.forName(str));\n } catch (Exception e) {\n Hack.fail(new HackAssertionException(e));\n }\n return ofType;\n }\n\n public T get(C c) {\n try {\n return this.mField.get(c);\n } catch (IllegalAccessException e) {\n e.printStackTrace();\n return null;\n }\n }\n\n public void set(C c, Object obj) {\n try {\n this.mField.set(c, obj);\n } catch (Throwable e) {\n e.printStackTrace();\n if (obj instanceof DelegateClassLoader) {\n throw new RuntimeException(\"set DelegateClassLoader fail\", e);\n }\n }\n }\n\n public void hijack(C c, InterceptionHandler<?> interceptionHandler) {\n Object obj = get(c);\n if (obj == null) {\n throw new IllegalStateException(\"Cannot hijack null\");\n }\n set(c, Interception.proxy(obj, (InterceptionHandler) interceptionHandler, obj.getClass().getInterfaces()));\n }\n\n HackedField(Class<C> cls, String str, int i) throws HackAssertionException {\n Field field = null;\n if (cls == null) {\n this.mField = null;\n return;\n }\n try {\n field = cls.getDeclaredField(str);\n if (i > 0 && (field.getModifiers() & i) != i) {\n Hack.fail(new HackAssertionException(field + \" does not match modifiers: \" + i));\n }\n field.setAccessible(true);\n } catch (Exception e) {\n HackAssertionException hackAssertionException = new HackAssertionException(e);\n hackAssertionException.setHackedClass(cls);\n hackAssertionException.setHackedFieldName(str);\n Hack.fail(hackAssertionException);\n } finally {\n this.mField = field;\n }\n }\n\n public Field getField() {\n return this.mField;\n }\n}",
"public static class HackedMethod {\n protected final Method mMethod;\n\n public Object invoke(Object obj, Object... objArr) throws IllegalArgumentException, InvocationTargetException {\n Object obj2 = null;\n try {\n obj2 = this.mMethod.invoke(obj, objArr);\n } catch (IllegalAccessException e) {\n e.printStackTrace();\n }\n return obj2;\n }\n\n HackedMethod(Class<?> cls, String str, Class<?>[] clsArr, int i) throws HackAssertionException {\n Method method = null;\n if (cls == null) {\n this.mMethod = null;\n return;\n }\n try {\n method = cls.getDeclaredMethod(str, clsArr);\n if (i > 0 && (method.getModifiers() & i) != i) {\n Hack.fail(new HackAssertionException(method + \" does not match modifiers: \" + i));\n }\n method.setAccessible(true);\n } catch (Exception e) {\n HackAssertionException hackAssertionException = new HackAssertionException(e);\n hackAssertionException.setHackedClass(cls);\n hackAssertionException.setHackedMethodName(str);\n Hack.fail(hackAssertionException);\n } finally {\n this.mMethod = method;\n }\n }\n\n public Method getMethod() {\n return this.mMethod;\n }\n}",
"public interface Logger {\n void debug(String str);\n\n void error(String str);\n\n void error(String str, Throwable th);\n\n void error(StringBuffer stringBuffer, Throwable th);\n\n void fatal(String str);\n\n void fatal(String str, Throwable th);\n\n void info(String str);\n\n boolean isDebugEnabled();\n\n boolean isErrorEnabled();\n\n boolean isFatalEnabled();\n\n boolean isInfoEnabled();\n\n boolean isVerboseEnabled();\n\n boolean isWarnEnabled();\n\n void verbose(String str);\n\n void warn(String str);\n\n void warn(String str, Throwable th);\n\n void warn(StringBuffer stringBuffer, Throwable th);\n}",
"public class LoggerFactory {\n public static int logLevel;\n\n static {\n logLevel = 3;\n }\n\n public static Logger getInstance(String str) {\n return getInstance(str, null);\n }\n\n public static Logger getInstance(Class<?> cls) {\n return getInstance(null, cls);\n }\n\n private static Logger getInstance(String str, Class<?> cls) {\n if (cls != null) {\n return new AndroidLogger((Class) cls);\n }\n return new AndroidLogger(str);\n }\n}"
] | import android.app.Application;
import android.app.Instrumentation;
import android.app.Service;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.content.res.Resources.Theme;
import android.os.Build.VERSION;
import android.taobao.atlas.hack.Hack.AssertionFailureHandler;
import android.taobao.atlas.hack.Hack.HackDeclaration;
import android.taobao.atlas.hack.Hack.HackDeclaration.HackAssertionException;
import android.taobao.atlas.hack.Hack.HackedClass;
import android.taobao.atlas.hack.Hack.HackedField;
import android.taobao.atlas.hack.Hack.HackedMethod;
import android.taobao.atlas.log.Logger;
import android.taobao.atlas.log.LoggerFactory;
import android.view.ContextThemeWrapper;
import dalvik.system.DexClassLoader;
import java.util.ArrayList;
import java.util.Map; | package android.taobao.atlas.hack;
public class AtlasHacks extends HackDeclaration implements AssertionFailureHandler {
public static HackedClass<Object> ActivityThread; | public static HackedMethod ActivityThread_currentActivityThread; | 5 |
mariok/pinemup | src/main/java/net/sourceforge/pinemup/ui/swing/tray/TrayMenuUpdater.java | [
"public class CategoryAddedEvent extends EventObject {\n private static final long serialVersionUID = 3366814253028410097L;\n\n private final Category addedCategory;\n\n public CategoryAddedEvent(PinBoard source, Category addedCategory) {\n super(source);\n this.addedCategory = addedCategory;\n }\n\n @Override\n public PinBoard getSource() {\n return (PinBoard)source;\n }\n\n public Category getAddedCategory() {\n return addedCategory;\n }\n}",
"public interface CategoryAddedEventListener extends EventListener {\n void categoryAdded(CategoryAddedEvent event);\n}",
"public class CategoryChangedEvent extends ObjectChangedEvent<Category> {\n private static final long serialVersionUID = -1625574299332502650L;\n\n public CategoryChangedEvent(Category source) {\n super(source);\n }\n}",
"public interface CategoryChangedEventListener extends EventListener {\n void categoryChanged(CategoryChangedEvent event);\n}",
"public class CategoryRemovedEvent extends EventObject {\n private static final long serialVersionUID = 5340998352321719112L;\n\n private final Category removedCategory;\n\n public CategoryRemovedEvent(PinBoard source, Category removedCategory) {\n super(source);\n this.removedCategory = removedCategory;\n }\n\n @Override\n public PinBoard getSource() {\n return (PinBoard)source;\n }\n\n public Category getAddedCategory() {\n return removedCategory;\n }\n}",
"public interface CategoryRemovedEventListener extends EventListener {\n void categoryRemoved(CategoryRemovedEvent event);\n}",
"public class UserSettingsChangedEvent extends ObjectChangedEvent<UserSettings> {\n private static final long serialVersionUID = -1625574299332502650L;\n\n public UserSettingsChangedEvent(UserSettings source) {\n super(source);\n }\n}",
"public interface UserSettingsChangedEventListener extends EventListener {\n void settingsChanged(UserSettingsChangedEvent event);\n}"
] | import net.sourceforge.pinemup.core.model.CategoryAddedEvent;
import net.sourceforge.pinemup.core.model.CategoryAddedEventListener;
import net.sourceforge.pinemup.core.model.CategoryChangedEvent;
import net.sourceforge.pinemup.core.model.CategoryChangedEventListener;
import net.sourceforge.pinemup.core.model.CategoryRemovedEvent;
import net.sourceforge.pinemup.core.model.CategoryRemovedEventListener;
import net.sourceforge.pinemup.core.settings.UserSettingsChangedEvent;
import net.sourceforge.pinemup.core.settings.UserSettingsChangedEventListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | package net.sourceforge.pinemup.ui.swing.tray;
public class TrayMenuUpdater implements CategoryChangedEventListener, UserSettingsChangedEventListener, CategoryAddedEventListener,
CategoryRemovedEventListener {
private static final Logger LOG = LoggerFactory.getLogger(TrayMenuUpdater.class);
private final TrayMenu trayMenu;
public TrayMenuUpdater(TrayMenu trayMenu) {
this.trayMenu = trayMenu;
}
@Override
public void settingsChanged(UserSettingsChangedEvent event) {
trayMenu.initWithNewLanguage();
}
@Override | public void categoryChanged(CategoryChangedEvent event) { | 2 |
PearsonEducation/StatsPoller | src/main/java/com/pearson/statspoller/internal_metric_collectors/InternalCollectorFramework.java | [
"public class ApplicationConfiguration {\n\n private static final Logger logger = LoggerFactory.getLogger(ApplicationConfiguration.class.getName());\n \n public static final int VALUE_NOT_SET_CODE = -4444;\n \n private static boolean isInitializeSuccess_ = false; \n \n private static HierarchicalIniConfigurationWrapper applicationConfiguration_ = null;\n \n private static boolean globalMetricNamePrefixEnabled_ = false;\n private static String globalMetricNamePrefix_ = null;\n private static long outputInterval_ = VALUE_NOT_SET_CODE;\n \n private static long checkOutputFilesInterval_ = VALUE_NOT_SET_CODE;\n private static boolean alwaysCheckOutputFiles_ = false;\n private static long maxMetricAge_ = VALUE_NOT_SET_CODE;\n private static boolean outputInternalMetricsToDisk_ = true;\n private static boolean legacyMode_ = false;\n \n private static final List<GraphiteOutputModule> graphiteOutputModules_ = new ArrayList<>();\n private static final List<OpenTsdbTelnetOutputModule> openTsdbTelnetOutputModules_ = new ArrayList<>();\n private static final List<OpenTsdbHttpOutputModule> openTsdbHttpOutputModules_ = new ArrayList<>();\n \n private static String statspollerMetricCollectorPrefix_ = null;\n private static boolean statspollerEnableJavaMetricCollector_ = false;\n private static long statspollerJavaMetricCollectorCollectionInterval_ = VALUE_NOT_SET_CODE;\n \n private static boolean linuxMetricCollectorEnable_ = false;\n private static String linuxProcLocation_ = null;\n private static String linuxSysLocation_ = null;\n private static long linuxMetricCollectorCollectionInterval_ = VALUE_NOT_SET_CODE;\n \n private static final List<String[]> processCounterPrefixesAndRegexes_ = new ArrayList<>();\n private static long processCounterMetricCollectorCollectionInterval_ = VALUE_NOT_SET_CODE;\n private static final List<FileCounterMetricCollector> fileCounterMetricCollectors_ = new ArrayList<>();\n private static final List<ExternalMetricCollector> externalMetricCollectors_ = new ArrayList<>();\n private static final List<JmxMetricCollector> jmxMetricCollectors_ = new ArrayList<>();\n private static final List<ApacheHttpMetricCollector> apacheHttpMetricCollectors_ = new ArrayList<>();\n private static final List<CadvisorMetricCollector> cadvisorMetricCollectors_ = new ArrayList<>();\n private static final List<MongoMetricCollector> mongoMetricCollectors_ = new ArrayList<>();\n private static final List<MysqlMetricCollector> mysqlMetricCollectors_ = new ArrayList<>();\n private static final List<PostgresMetricCollector> postgresMetricCollectors_ = new ArrayList<>();\n private static final List<DbQuerier> dbQuerier_ = new ArrayList<>();\n \n private static long applicationStartTimeInMs_ = VALUE_NOT_SET_CODE;\n private static String hostname_ = null;\n \n public static boolean initialize(String filePathAndFilename, boolean isPrimary) {\n \n if (filePathAndFilename == null) {\n return false;\n }\n \n applicationConfiguration_ = new HierarchicalIniConfigurationWrapper(filePathAndFilename);\n \n if (!applicationConfiguration_.isValid()) {\n return false;\n }\n \n if (isPrimary) isInitializeSuccess_ = setPrimaryApplicationConfigurationValues();\n else setSecondaryApplicationConfigurationValues();\n \n return isInitializeSuccess_;\n }\n\n private static boolean setPrimaryApplicationConfigurationValues() {\n \n try {\n // get the OS's hostname\n hostname_ = getOsHostname();\n \n // get legacy mode -- reading this first since it is used by many other config settings\n // if in auto mode, then check the output_interval variable. \n // assume no one would want to output less frequently than 1 day, so if output_interval is greater than 3600, then assume legacy_mode = true.\n String legacyModeString = applicationConfiguration_.safeGetString(\"legacy_mode\", \"auto\");\n if (legacyModeString == null) legacyModeString = \"auto\";\n if (legacyModeString.equalsIgnoreCase(\"true\")) legacyMode_ = true;\n else if (legacyModeString.equalsIgnoreCase(\"false\")) legacyMode_ = false;\n else if (legacyModeString.equalsIgnoreCase(\"auto\")) {\n double outputInterval = applicationConfiguration_.safeGetDouble(\"output_interval\", 30); \n legacyMode_ = (outputInterval > 3600);\n }\n \n // advanced core statspoller configuration values\n maxMetricAge_ = applicationConfiguration_.safeGetLong(\"max_metric_age\", 90 * 1000); // remove?\n outputInternalMetricsToDisk_ = applicationConfiguration_.safeGetBoolean(\"output_internal_metrics_to_disk\", true);\n double checkOutputFilesInterval = applicationConfiguration_.safeGetDouble(\"check_output_files_interval\", 5);\n checkOutputFilesInterval_ = legacyMode_ ? (long) checkOutputFilesInterval : (long) (checkOutputFilesInterval * 1000); \n \n String alwaysCheckOutputFiles = applicationConfiguration_.safeGetString(\"always_check_output_files\", \"auto\");\n if ((alwaysCheckOutputFiles != null) && alwaysCheckOutputFiles.equalsIgnoreCase(\"true\")) alwaysCheckOutputFiles_ = true;\n else if ((alwaysCheckOutputFiles != null) && alwaysCheckOutputFiles.equalsIgnoreCase(\"false\")) alwaysCheckOutputFiles_ = false;\n else alwaysCheckOutputFiles_ = !SystemUtils.IS_OS_WINDOWS;\n \n // core statspoller configuration values\n globalMetricNamePrefixEnabled_ = true;\n double outputInterval = applicationConfiguration_.safeGetDouble(\"output_interval\", 30); \n outputInterval_ = legacyMode_ ? (long) outputInterval : (long) (outputInterval * 1000); \n globalMetricNamePrefix_ = getGlobalMetricNamePrefix_FromApplicationConfFile_CurrentAndLegacy();\n if ((globalMetricNamePrefix_ == null) || globalMetricNamePrefix_.trim().isEmpty()) {\n logger.error(\"global_metric_name_prefix cannot be blank. Aborting application initialization\");\n return false;\n }\n \n // graphite configuration\n graphiteOutputModules_.addAll(readLegacyGraphiteOutputModule());\n graphiteOutputModules_.addAll(readGraphiteOutputModules());\n\n // opentsdb configuration\n openTsdbTelnetOutputModules_.addAll(readOpenTsdbTelnetOutputModules());\n \n // opentsdb configuration\n openTsdbHttpOutputModules_.addAll(readOpenTsdbHttpOutputModules());\n\n // native (built-in) server-info collector\n statspollerMetricCollectorPrefix_ = applicationConfiguration_.safeGetString(\"statspoller_metric_collector_prefix\", \"StatsPoller\");\n statspollerEnableJavaMetricCollector_ = applicationConfiguration_.safeGetBoolean(\"statspoller_enable_java_metric_collector\", true);\n double statspollerJavaMetricCollectorCollectionInterval = applicationConfiguration_.safeGetDouble(\"statspoller_java_metric_collector_collection_interval\", 30);\n statspollerJavaMetricCollectorCollectionInterval_ = legacyMode_ ? (long) statspollerJavaMetricCollectorCollectionInterval : (long) (statspollerJavaMetricCollectorCollectionInterval * 1000); \n \n // linux (built-in) metric collectors\n String linuxMetricCollectorEnable = applicationConfiguration_.safeGetString(\"linux_metric_collector_enable\", \"auto\");\n if (linuxMetricCollectorEnable.equalsIgnoreCase(\"auto\") && SystemUtils.IS_OS_LINUX) linuxMetricCollectorEnable_ = true;\n else linuxMetricCollectorEnable_ = linuxMetricCollectorEnable.equalsIgnoreCase(\"true\");\n linuxProcLocation_ = applicationConfiguration_.safeGetString(\"linux_proc_location\", \"/proc\");\n linuxSysLocation_ = applicationConfiguration_.safeGetString(\"linux_sys_location\", \"/sys\");\n double linuxMetricCollectorCollectionInterval = applicationConfiguration_.safeGetDouble(\"linux_metric_collector_collection_interval\", 30);\n linuxMetricCollectorCollectionInterval_ = legacyMode_ ? (long) linuxMetricCollectorCollectionInterval : (long) (linuxMetricCollectorCollectionInterval * 1000);\n \n double processCounterInterval = applicationConfiguration_.safeGetDouble(\"process_counter_interval\", 30);\n processCounterMetricCollectorCollectionInterval_ = legacyMode_ ? (long) processCounterInterval : (long) (processCounterInterval * 1000); \n \n // record application startup time\n applicationStartTimeInMs_ = System.currentTimeMillis();\n \n // startup non-core metric collectors\n setSecondaryApplicationConfigurationValues();\n \n return true; \n } \n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n return false;\n }\n \n }\n \n private static boolean setSecondaryApplicationConfigurationValues() {\n \n try {\n // load the configurations of the external metric collectors (metric collection plugins)\n externalMetricCollectors_.addAll(readExternalMetricCollectors(legacyMode_));\n \n // add file counter collectors\n fileCounterMetricCollectors_.addAll(readFileCounterMetricCollectors(legacyMode_));\n\n // add linux process counter collectors\n processCounterPrefixesAndRegexes_.addAll(readProcessCounterPrefixesAndRegexes());\n \n // add jmx collectors\n JmxMetricCollector jmxMetricCollector = readJmxMetricCollector(\"\", legacyMode_);\n if (jmxMetricCollector != null) jmxMetricCollectors_.add(jmxMetricCollector);\n for (int i = -1; i <= 10000; i++) {\n String collectorSuffix = \"_\" + (i + 1);\n jmxMetricCollector = readJmxMetricCollector(collectorSuffix, legacyMode_);\n if (jmxMetricCollector != null) jmxMetricCollectors_.add(jmxMetricCollector);\n }\n \n // add apache http collectors\n ApacheHttpMetricCollector apacheHttpMetricCollector = readApacheHttpMetricCollector(\"\", legacyMode_);\n if (apacheHttpMetricCollector != null) apacheHttpMetricCollectors_.add(apacheHttpMetricCollector);\n for (int i = -1; i <= 10000; i++) {\n String collectorSuffix = \"_\" + (i + 1);\n apacheHttpMetricCollector = readApacheHttpMetricCollector(collectorSuffix, legacyMode_);\n if (apacheHttpMetricCollector != null) apacheHttpMetricCollectors_.add(apacheHttpMetricCollector);\n }\n \n // add cadvisor collectors\n CadvisorMetricCollector cadvisorMetricCollector = readCadvisorMetricCollector(\"\", legacyMode_);\n if (cadvisorMetricCollector != null) cadvisorMetricCollectors_.add(cadvisorMetricCollector);\n for (int i = -1; i <= 10000; i++) {\n String collectorSuffix = \"_\" + (i + 1);\n cadvisorMetricCollector = readCadvisorMetricCollector(collectorSuffix, legacyMode_);\n if (cadvisorMetricCollector != null) cadvisorMetricCollectors_.add(cadvisorMetricCollector);\n }\n \n // add mongo collectors\n MongoMetricCollector mongoMetricCollector = readMongoMetricCollector(\"\", legacyMode_);\n if (mongoMetricCollector != null) mongoMetricCollectors_.add(mongoMetricCollector);\n for (int i = -1; i <= 10000; i++) {\n String collectorSuffix = \"_\" + (i + 1);\n mongoMetricCollector = readMongoMetricCollector(collectorSuffix, legacyMode_);\n if (mongoMetricCollector != null) mongoMetricCollectors_.add(mongoMetricCollector);\n }\n \n // add mysql collectors\n MysqlMetricCollector mysqlMetricCollector = readMysqlMetricCollector(\"\", legacyMode_);\n if (mysqlMetricCollector != null) mysqlMetricCollectors_.add(mysqlMetricCollector);\n for (int i = -1; i <= 10000; i++) {\n String collectorSuffix = \"_\" + (i + 1);\n mysqlMetricCollector = readMysqlMetricCollector(collectorSuffix, legacyMode_);\n if (mysqlMetricCollector != null) mysqlMetricCollectors_.add(mysqlMetricCollector);\n }\n if (!mysqlMetricCollectors_.isEmpty()) loadMySQLDrivers();\n \n // add postgres collectors\n PostgresMetricCollector postgresMetricCollector = readPostgresMetricCollector(\"\", legacyMode_);\n if (postgresMetricCollector != null) postgresMetricCollectors_.add(postgresMetricCollector);\n for (int i = -1; i <= 10000; i++) {\n String collectorSuffix = \"_\" + (i + 1);\n postgresMetricCollector = readPostgresMetricCollector(collectorSuffix, legacyMode_);\n if (postgresMetricCollector != null) postgresMetricCollectors_.add(postgresMetricCollector);\n }\n\n // add db querier collectors\n DbQuerier dbQuerier = readDbQuerierMetricCollector(\"\", legacyMode_);\n if (dbQuerier != null) dbQuerier_.add(dbQuerier);\n for (int i = -1; i <= 10000; i++) {\n String collectorSuffix = \"_\" + (i + 1);\n dbQuerier = readDbQuerierMetricCollector(collectorSuffix, legacyMode_);\n if (dbQuerier != null) dbQuerier_.add(dbQuerier);\n }\n if (!dbQuerier_.isEmpty()) loadMySQLDrivers();\n\n return true; \n } \n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n return false;\n }\n \n }\n \n private static String getGlobalMetricNamePrefix_FromApplicationConfFile_CurrentAndLegacy() {\n String globalMetricNamePrefix = applicationConfiguration_.safeGetString(\"global_metric_name_prefix\", getOsHostname()).replace(\"$HOSTNAME\", hostname_);\n String globalMetricNamePrefixValue = applicationConfiguration_.safeGetString(\"global_metric_name_prefix_value\", getOsHostname()).replace(\"$HOSTNAME\", hostname_);\n\n String awsInstanceId = null;\n if (((globalMetricNamePrefix != null) && globalMetricNamePrefix.contains(\"$AWS-INSTANCE-ID\")) || \n ((globalMetricNamePrefixValue != null) && globalMetricNamePrefixValue.contains(\"$AWS-INSTANCE-ID\"))) {\n awsInstanceId = getAwsInstanceId();\n }\n \n if ((globalMetricNamePrefix != null) && (globalMetricNamePrefixValue != null) && !globalMetricNamePrefixValue.trim().isEmpty() &&\n globalMetricNamePrefix.equals(hostname_) && !globalMetricNamePrefix.equals(globalMetricNamePrefixValue)) {\n if ((awsInstanceId != null) && (globalMetricNamePrefixValue != null)) globalMetricNamePrefixValue = globalMetricNamePrefixValue.replace(\"$AWS-INSTANCE-ID\", awsInstanceId);\n return globalMetricNamePrefixValue;\n }\n else {\n if ((awsInstanceId != null) && (globalMetricNamePrefix != null)) globalMetricNamePrefix = globalMetricNamePrefix.replace(\"$AWS-INSTANCE-ID\", awsInstanceId);\n return globalMetricNamePrefix;\n }\n }\n \n private static String getOsHostname() {\n \n try {\n String hostname = System.getenv().get(\"COMPUTERNAME\");\n if ((hostname != null) && !hostname.trim().equals(\"\")) return hostname;\n\n hostname = System.getenv().get(\"HOSTNAME\");\n if ((hostname != null) && !hostname.trim().equals(\"\")) return hostname;\n \n hostname = InetAddress.getLocalHost().getHostName();\n if ((hostname != null) && !hostname.trim().equals(\"\")) return hostname;\n }\n catch (Exception e) {\n logger.debug(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n \n return \"UNKNOWN-HOST\";\n }\n \n private static String getAwsInstanceId() {\n \n try {\n String url = \"http://169.254.169.254/latest/meta-data/instance-id\";\n String awsInstanceId = NetIo.downloadUrl(url, 1, 1, true);\n if ((awsInstanceId != null) && !awsInstanceId.trim().isEmpty()) return awsInstanceId.trim();\n }\n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n \n return \"UNKNOWN-AWS-INSTANCE-ID\";\n }\n \n private static List<GraphiteOutputModule> readLegacyGraphiteOutputModule() {\n\n List<GraphiteOutputModule> graphiteOutputModules = new ArrayList<>();\n \n Boolean doesLegacyGraphiteOutputConfigExist = applicationConfiguration_.safeGetBoolean(\"graphite_output_enabled\", null);\n if (doesLegacyGraphiteOutputConfigExist == null) return graphiteOutputModules;\n \n boolean graphiteOutputEnabled = applicationConfiguration_.safeGetBoolean(\"graphite_output_enabled\", false);\n String graphiteHost = applicationConfiguration_.safeGetString(\"graphite_host\", \"localhost\");\n int graphitePort = applicationConfiguration_.safeGetInt(\"graphite_port\", 2003);\n int graphiteMaxBatchSize = applicationConfiguration_.safeGetInt(\"graphite_max_batch_size\", 1000);\n int graphiteSendRetryAttempts = applicationConfiguration_.safeGetInt(\"graphite_send_retry_attempts\", 2);\n String uniqueId = \"Graphite-LegacyConfig\";\n \n GraphiteOutputModule graphiteOutputModule = new GraphiteOutputModule(graphiteOutputEnabled, graphiteHost, graphitePort,\n graphiteSendRetryAttempts, graphiteMaxBatchSize, true, true, uniqueId);\n \n graphiteOutputModules.add(graphiteOutputModule);\n \n return graphiteOutputModules;\n }\n \n private static List<GraphiteOutputModule> readGraphiteOutputModules() {\n \n List<GraphiteOutputModule> graphiteOutputModules = new ArrayList<>();\n \n for (int i = -1; i < 10000; i++) {\n String graphiteOutputModuleKey = \"graphite_output_module_\" + (i + 1);\n String graphiteOutputModuleValue = applicationConfiguration_.safeGetString(graphiteOutputModuleKey, null);\n \n if (graphiteOutputModuleValue == null) continue;\n \n try {\n CSVReader reader = new CSVReader(new StringReader(graphiteOutputModuleValue));\n List<String[]> csvValuesArray = reader.readAll();\n\n if ((csvValuesArray != null) && !csvValuesArray.isEmpty() && (csvValuesArray.get(0) != null)) {\n String[] csvValues = csvValuesArray.get(0);\n\n if (csvValues.length >= 4) { \n boolean isOutputEnabled = Boolean.valueOf(csvValues[0]);\n String host = csvValues[1];\n int port = Integer.valueOf(csvValues[2]);\n int numSendRetryAttempts = Integer.valueOf(csvValues[3]);\n \n int maxMetricsPerMessage = 1000;\n if (csvValues.length > 4) maxMetricsPerMessage = Integer.valueOf(csvValues[4]);\n \n boolean sanitizeMetrics = false;\n if (csvValues.length > 5) sanitizeMetrics = Boolean.valueOf(csvValues[5]);\n \n boolean substituteCharacters = false;\n if (csvValues.length > 6) substituteCharacters = Boolean.valueOf(csvValues[6]);\n \n String uniqueId = \"Graphite-\" + (i+1);\n \n GraphiteOutputModule graphiteOutputModule = new GraphiteOutputModule(isOutputEnabled, host, port, \n numSendRetryAttempts, maxMetricsPerMessage, sanitizeMetrics, substituteCharacters, uniqueId);\n \n graphiteOutputModules.add(graphiteOutputModule);\n }\n }\n }\n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n }\n \n return graphiteOutputModules;\n }\n\n private static List<OpenTsdbTelnetOutputModule> readOpenTsdbTelnetOutputModules() {\n \n List<OpenTsdbTelnetOutputModule> openTsdbTelnetOutputModules = new ArrayList<>();\n \n for (int i = -1; i < 10000; i++) {\n String openTsdbTelnetOutputModuleKey = \"opentsdb_telnet_output_module_\" + (i + 1);\n String openTsdbTelnetOutputModuleValue = applicationConfiguration_.safeGetString(openTsdbTelnetOutputModuleKey, null);\n \n if (openTsdbTelnetOutputModuleValue == null) continue;\n \n try {\n CSVReader reader = new CSVReader(new StringReader(openTsdbTelnetOutputModuleValue));\n List<String[]> csvValuesArray = reader.readAll();\n\n if ((csvValuesArray != null) && !csvValuesArray.isEmpty() && (csvValuesArray.get(0) != null)) {\n String[] csvValues = csvValuesArray.get(0);\n\n if (csvValues.length >= 4) { \n boolean isOutputEnabled = Boolean.valueOf(csvValues[0]);\n String host = csvValues[1];\n int port = Integer.valueOf(csvValues[2]);\n int numSendRetryAttempts = Integer.valueOf(csvValues[3]);\n \n boolean sanitizeMetrics = false;\n if (csvValues.length > 4) sanitizeMetrics = Boolean.valueOf(csvValues[4]);\n \n String uniqueId = \"OpenTSDB-Telnet-\" + (i+1);\n \n OpenTsdbTelnetOutputModule openTsdbTelnetOutputModule = new OpenTsdbTelnetOutputModule(isOutputEnabled, host, port, \n numSendRetryAttempts, sanitizeMetrics, uniqueId);\n \n openTsdbTelnetOutputModules.add(openTsdbTelnetOutputModule);\n }\n }\n }\n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n }\n \n return openTsdbTelnetOutputModules;\n }\n \n private static List<OpenTsdbHttpOutputModule> readOpenTsdbHttpOutputModules() {\n \n List<OpenTsdbHttpOutputModule> openTsdbHttpOutputModules = new ArrayList<>();\n \n for (int i = -1; i < 10000; i++) {\n String openTsdbHttpOutputModuleKey = \"opentsdb_http_output_module_\" + (i + 1);\n String openTsdbHttpOutputModuleValue = applicationConfiguration_.safeGetString(openTsdbHttpOutputModuleKey, null);\n \n if (openTsdbHttpOutputModuleValue == null) continue;\n \n try {\n CSVReader reader = new CSVReader(new StringReader(openTsdbHttpOutputModuleValue));\n List<String[]> csvValuesArray = reader.readAll();\n\n if ((csvValuesArray != null) && !csvValuesArray.isEmpty() && (csvValuesArray.get(0) != null)) {\n String[] csvValues = csvValuesArray.get(0);\n\n if (csvValues.length >= 4) { \n boolean isOutputEnabled = Boolean.valueOf(csvValues[0]);\n String url = csvValues[1];\n int numSendRetryAttempts = Integer.valueOf(csvValues[2]);\n int maxMetricsPerMessage = Integer.valueOf(csvValues[3]);\n \n boolean sanitizeMetrics = false;\n if (csvValues.length > 4) sanitizeMetrics = Boolean.valueOf(csvValues[4]);\n \n String uniqueId = \"OpenTSDB-HTTP-\" + (i+1);\n \n OpenTsdbHttpOutputModule openTsdbHttpOutputModule = new OpenTsdbHttpOutputModule(isOutputEnabled, url, numSendRetryAttempts, \n maxMetricsPerMessage, sanitizeMetrics, uniqueId);\n openTsdbHttpOutputModules.add(openTsdbHttpOutputModule);\n }\n }\n }\n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n }\n \n return openTsdbHttpOutputModules;\n }\n\n private static List<String[]> readProcessCounterPrefixesAndRegexes() {\n \n List<String[]> processCounterPrefixesAndRegexes = new ArrayList<>();\n \n try {\n List<Object> processCounterRegexConfigs = applicationConfiguration_.safeGetList(\"process_counter_regex\", new ArrayList<>());\n if (processCounterRegexConfigs != null) {\n for (Object processCounterRegexConfig : processCounterRegexConfigs) {\n String[] processCounterMetricCollectorRegex = parseProcessCounterMetricCollectorRegexCsv((String) processCounterRegexConfig);\n if (processCounterMetricCollectorRegex != null) processCounterPrefixesAndRegexes.add(processCounterMetricCollectorRegex);\n }\n }\n\n for (int i = -1; i <= 10000; i++) {\n String processCounterRegexConfig_Key = \"process_counter_regex_\" + (i + 1);\n String processCounterRegexConfig_Value = applicationConfiguration_.safeGetString(processCounterRegexConfig_Key, null);\n if (processCounterRegexConfig_Value == null) continue;\n\n String[] processCounterMetricCollectorRegex = parseProcessCounterMetricCollectorRegexCsv((String) processCounterRegexConfig_Value);\n if (processCounterMetricCollectorRegex != null) processCounterPrefixesAndRegexes.add(processCounterMetricCollectorRegex);\n }\n }\n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e)); \n return processCounterPrefixesAndRegexes;\n }\n \n return processCounterPrefixesAndRegexes;\n }\n \n private static String[] parseProcessCounterMetricCollectorRegexCsv(String processCounterMetricCollectorConfig) {\n \n if ((processCounterMetricCollectorConfig == null) || processCounterMetricCollectorConfig.isEmpty()) {\n return null;\n }\n\n try {\n CSVReader reader = new CSVReader(new StringReader(processCounterMetricCollectorConfig));\n List<String[]> csvValuesArray = reader.readAll();\n\n if ((csvValuesArray != null) && !csvValuesArray.isEmpty() && (csvValuesArray.get(0) != null)) {\n String[] csvValues = csvValuesArray.get(0);\n \n if (csvValues.length == 2) { \n if ((csvValues[0] == null) || csvValues[0].isEmpty() || (csvValues[1] == null) || csvValues[1].isEmpty()) return null;\n \n String[] processCounterMetricCollectorRegex = new String[2];\n processCounterMetricCollectorRegex[0] = csvValues[0];\n processCounterMetricCollectorRegex[1] = csvValues[1];\n return processCounterMetricCollectorRegex;\n }\n }\n }\n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e)); \n return null;\n }\n \n return null;\n }\n \n private static List<FileCounterMetricCollector> readFileCounterMetricCollectors(boolean legacyMode) {\n \n List<FileCounterMetricCollector> fileCounterMetricCollectors = new ArrayList<>();\n\n try {\n List<Object> fileCounterMetricCollectorConfigs = applicationConfiguration_.safeGetList(\"file_counter\", new ArrayList<>());\n if (fileCounterMetricCollectorConfigs != null) {\n for (Object fileCounterMetricCollectorConfig : fileCounterMetricCollectorConfigs) {\n FileCounterMetricCollector fileCounterMetricCollector = parseFileCounterMetricCollectorCsv((String) fileCounterMetricCollectorConfig, legacyMode);\n if (fileCounterMetricCollector != null) fileCounterMetricCollectors.add(fileCounterMetricCollector);\n }\n }\n\n for (int i = -1; i <= 10000; i++) {\n String fileCounterMetricCollector_Key = \"file_counter_\" + (i + 1);\n String fileCounterMetricCollector_Value = applicationConfiguration_.safeGetString(fileCounterMetricCollector_Key, null);\n\n if (fileCounterMetricCollector_Value == null) continue;\n\n FileCounterMetricCollector fileCounterMetricCollector = parseFileCounterMetricCollectorCsv(fileCounterMetricCollector_Value, legacyMode);\n if (fileCounterMetricCollector != null) fileCounterMetricCollectors.add(fileCounterMetricCollector);\n }\n }\n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e)); \n return null;\n }\n \n return fileCounterMetricCollectors;\n }\n \n private static FileCounterMetricCollector parseFileCounterMetricCollectorCsv(String fileCounterMetricCollectorConfig, boolean legacyMode) {\n \n if ((fileCounterMetricCollectorConfig == null) || fileCounterMetricCollectorConfig.isEmpty()) {\n return null;\n }\n\n try {\n CSVReader reader = new CSVReader(new StringReader(fileCounterMetricCollectorConfig));\n List<String[]> csvValuesArray = reader.readAll();\n\n if ((csvValuesArray != null) && !csvValuesArray.isEmpty() && (csvValuesArray.get(0) != null)) {\n String[] csvValues = csvValuesArray.get(0);\n \n if (csvValues.length == 4) { \n String path = csvValues[0];\n String countSubdirectories = csvValues[1];\n boolean countSubdirectories_Boolean = Boolean.parseBoolean(countSubdirectories);\n double collectionIntervalInSeconds = Long.valueOf(csvValues[2].trim());\n long collectionIntervalInMilliseconds = legacyMode ? (long) collectionIntervalInSeconds : (long) (collectionIntervalInSeconds * 1000); \n String metricPrefix = csvValues[3];\n String outputFile = \"./output/\" + \"filecounter_\" + metricPrefix + \".out\";\n \n FileCounterMetricCollector fileCounterMetricCollector = new FileCounterMetricCollector(true,\n collectionIntervalInMilliseconds, \"FileCounter.\" + metricPrefix, outputFile, outputInternalMetricsToDisk_,\n path, countSubdirectories_Boolean);\n \n return fileCounterMetricCollector;\n }\n }\n }\n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e)); \n return null;\n }\n \n return null;\n }\n \n private static List<ExternalMetricCollector> readExternalMetricCollectors(boolean legacyMode) {\n \n List<ExternalMetricCollector> externalMetricCollectors = new ArrayList<>();\n\n try {\n List<Object> metricCollectorConfigs = applicationConfiguration_.safeGetList(\"metric_collector\", new ArrayList<>());\n\n if (metricCollectorConfigs != null) {\n for (Object metricCollectorsConfig : metricCollectorConfigs) {\n ExternalMetricCollector externalMetricCollector = parseExternalMetricCollectorCsv((String) metricCollectorsConfig, legacyMode);\n if (externalMetricCollector != null) externalMetricCollectors.add(externalMetricCollector);\n }\n }\n\n for (int i = -1; i <= 10000; i++) {\n String metricCollectorKey = \"metric_collector_\" + (i + 1);\n String metricCollectorValue = applicationConfiguration_.safeGetString(metricCollectorKey, null);\n if (metricCollectorValue == null) continue;\n ExternalMetricCollector externalMetricCollector = parseExternalMetricCollectorCsv(metricCollectorValue, legacyMode);\n if (externalMetricCollector != null) externalMetricCollectors.add(externalMetricCollector);\n }\n }\n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e)); \n return null;\n }\n \n return externalMetricCollectors;\n }\n \n private static ExternalMetricCollector parseExternalMetricCollectorCsv(String metricCollectorsConfig, boolean legacyMode) {\n \n if (metricCollectorsConfig == null) {\n return null;\n }\n \n try {\n metricCollectorsConfig = metricCollectorsConfig.replace(\"\\\\\", \"\\\\\\\\\");\n\n CSVReader reader = new CSVReader(new StringReader(metricCollectorsConfig));\n List<String[]> csvValuesArray = reader.readAll();\n\n if ((csvValuesArray != null) && !csvValuesArray.isEmpty() && (csvValuesArray.get(0) != null)) {\n String[] csvValues = csvValuesArray.get(0);\n\n if (csvValues.length == 4) {\n String programPathAndFilename = csvValues[0].trim();\n double collectionIntervalInSeconds = Long.valueOf(csvValues[1].trim());\n long collectionIntervalInMilliseconds = legacyMode ? (long) collectionIntervalInSeconds : (long) (collectionIntervalInSeconds * 1000); \n String outputPathAndFilename = csvValues[2].trim();\n String metricPrefix = csvValues[3].trim();\n\n ExternalMetricCollector externalMetricCollector = new ExternalMetricCollector(programPathAndFilename, collectionIntervalInMilliseconds, outputPathAndFilename, metricPrefix);\n return externalMetricCollector;\n }\n }\n }\n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n \n return null;\n }\n \n private static JmxMetricCollector readJmxMetricCollector(String collectorSuffix, boolean legacyMode) {\n \n if (applicationConfiguration_ == null) {\n return null;\n }\n \n if (collectorSuffix == null) collectorSuffix = \"\";\n \n try {\n String jmxEnabledKey = \"jmx_enabled\" + collectorSuffix;\n boolean jmxEnabledValue = applicationConfiguration_.safeGetBoolean(jmxEnabledKey, false);\n if (!jmxEnabledValue) return null;\n\n String jmxHostKey = \"jmx_host\" + collectorSuffix;\n String jmxHostValue = applicationConfiguration_.safeGetString(jmxHostKey, null);\n\n String jmxPortKey = \"jmx_port\" + collectorSuffix;\n String tempValue = applicationConfiguration_.safeGetString(jmxPortKey, null);\n int jmxPortValue = -1;\n if ((tempValue != null) && !tempValue.isEmpty()) jmxPortValue = applicationConfiguration_.safeGetInteger(jmxPortKey, -1);\n\n String jmxServiceUrlKey = \"jmx_service_url\" + collectorSuffix;\n String jmxServiceUrlValue = applicationConfiguration_.safeGetString(jmxServiceUrlKey, null);\n\n String jmxUsernameKey = \"jmx_username\" + collectorSuffix;\n String jmxUsernameValue = applicationConfiguration_.safeGetString(jmxUsernameKey, \"\");\n\n String jmxPasswordKey = \"jmx_password\" + collectorSuffix;\n String jmxPasswordValue = applicationConfiguration_.safeGetString(jmxPasswordKey, \"\");\n\n String jmxCollectionIntervalKey = \"jmx_collection_interval\" + collectorSuffix;\n double jmxCollectionIntervalValue = applicationConfiguration_.safeGetDouble(jmxCollectionIntervalKey, 30);\n long jmxCollectionIntervalValue_Long = legacyMode ? (long) jmxCollectionIntervalValue : (long) (jmxCollectionIntervalValue * 1000); \n\n String jmxNumConnectionAttemptRetriesKey = \"jmx_num_connection_attempt_retries\" + collectorSuffix;\n int jmxNumConnectionAttemptRetriesValue = applicationConfiguration_.safeGetInteger(jmxNumConnectionAttemptRetriesKey, 3);\n\n String jmxSleepAfterConnectTimeKey = \"jmx_sleep_after_connect_time\" + collectorSuffix;\n double jmxSleepAfterConnectTimeValue = applicationConfiguration_.safeGetDouble(jmxSleepAfterConnectTimeKey, 30);\n long jmxSleepAfterConnectTimeValue_Long = legacyMode ? (long) jmxSleepAfterConnectTimeValue : (long) (jmxSleepAfterConnectTimeValue * 1000); \n\n String jmxQueryMetricTreeKey = \"jmx_query_metric_tree\" + collectorSuffix;\n double jmxQueryMetricTreeValue = applicationConfiguration_.safeGetDouble(jmxQueryMetricTreeKey, 300);\n long jmxQueryMetricTreeValue_Long = legacyMode ? (long) jmxQueryMetricTreeValue : (long) (jmxQueryMetricTreeValue * 1000); \n \n String jmxFlushCacheIntervalKey = \"jmx_flush_cache_interval\" + collectorSuffix;\n double jmxFlushCacheIntervalValue = applicationConfiguration_.safeGetDouble(jmxFlushCacheIntervalKey, 3600);\n long jmxFlushCacheIntervalValue_Long = legacyMode ? (long) jmxFlushCacheIntervalValue : (long) (jmxFlushCacheIntervalValue * 1000); \n \n String jmxCollectStringAttributesKey = \"jmx_collect_string_attributes\" + collectorSuffix;\n Boolean jmxCollectStringAttributesValue = applicationConfiguration_.safeGetBoolean(jmxCollectStringAttributesKey, false);\n\n String jmxDerivedMetricsEnabledKey = \"jmx_derived_metrics_enabled\" + collectorSuffix;\n boolean jmxDerivedMetricsEnabledValue = applicationConfiguration_.safeGetBoolean(jmxDerivedMetricsEnabledKey, true);\n\n String jmxMetricPrefixKey = \"jmx_metric_prefix\" + collectorSuffix;\n String jmxMetricPrefixValue = applicationConfiguration_.safeGetString(jmxMetricPrefixKey, \"JMX\");\n String graphiteSanitizedJmxMetricPrefix = GraphiteMetric.getGraphiteSanitizedString(jmxMetricPrefixValue, true, true);\n \n String jmxBlacklistObjectNameRegexsKey = \"jmx_blacklist_objectname_regex\" + collectorSuffix;\n List<Object> jmxBlacklistObjectNameRegexsValue = applicationConfiguration_.safeGetList(jmxBlacklistObjectNameRegexsKey, null);\n List<String> jmxBlacklistObjectNameRegexsValueStrings = new ArrayList<>();\n if (jmxBlacklistObjectNameRegexsValue != null) { \n for (Object object : jmxBlacklistObjectNameRegexsValue) {\n jmxBlacklistObjectNameRegexsValueStrings.add((String) object);\n }\n }\n\n String jmxBlacklistRegexsKey = \"jmx_blacklist_regex\" + collectorSuffix;\n List<Object> jmxBlacklistRegexsValue = applicationConfiguration_.safeGetList(jmxBlacklistRegexsKey, null);\n List<String> jmxBlacklistRegexsValueStrings = new ArrayList<>();\n if (jmxBlacklistRegexsValue != null) { \n for (Object object : jmxBlacklistRegexsValue) {\n jmxBlacklistRegexsValueStrings.add((String) object);\n }\n }\n\n String jmxWhitelistRegexsKey = \"jmx_whitelist_regex\" + collectorSuffix;\n List<Object> jmxWhitelistRegexsValue = applicationConfiguration_.safeGetList(jmxWhitelistRegexsKey, null);\n List<String> jmxWhitelistRegexsValueStrings = new ArrayList<>();\n if (jmxWhitelistRegexsValue != null) {\n for (Object object : jmxWhitelistRegexsValue) {\n jmxWhitelistRegexsValueStrings.add((String) object);\n }\n }\n\n String jmxOutputFileValue = \"./output/\" + \"jmx_\" + jmxMetricPrefixValue + \".out\";\n\n JmxMetricCollector jmxMetricCollector = new JmxMetricCollector(jmxEnabledValue, \n jmxCollectionIntervalValue_Long, graphiteSanitizedJmxMetricPrefix, jmxOutputFileValue, outputInternalMetricsToDisk_,\n jmxHostValue, jmxPortValue, jmxServiceUrlValue, jmxNumConnectionAttemptRetriesValue, \n jmxSleepAfterConnectTimeValue_Long, jmxQueryMetricTreeValue_Long, jmxFlushCacheIntervalValue_Long, \n jmxCollectStringAttributesValue, jmxDerivedMetricsEnabledValue,\n jmxUsernameValue, jmxPasswordValue, jmxBlacklistObjectNameRegexsValueStrings, \n jmxBlacklistRegexsValueStrings, jmxWhitelistRegexsValueStrings);\n\n return jmxMetricCollector;\n }\n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e)); \n return null;\n }\n }\n \n private static ApacheHttpMetricCollector readApacheHttpMetricCollector(String collectorSuffix, boolean legacyMode) {\n \n if (applicationConfiguration_ == null) {\n return null;\n }\n \n if (collectorSuffix == null) collectorSuffix = \"\";\n\n try {\n String apacheEnabledKey = \"apachehttp_enabled\" + collectorSuffix;\n boolean apacheEnabledValue = applicationConfiguration_.safeGetBoolean(apacheEnabledKey, false);\n if (!apacheEnabledValue) return null;\n \n String apacheProtocolKey = \"apachehttp_protocol\" + collectorSuffix;\n String apacheProtocolValue = applicationConfiguration_.safeGetString(apacheProtocolKey, \"http\");\n \n String apacheHostKey = \"apachehttp_host\" + collectorSuffix;\n String apacheHostValue = applicationConfiguration_.safeGetString(apacheHostKey, \"127.0.0.1\");\n\n String apachePortKey = \"apachehttp_port\" + collectorSuffix;\n int apachePortValue = applicationConfiguration_.safeGetInteger(apachePortKey, 80);\n \n String apacheCollectionIntervalKey = \"apachehttp_collection_interval\" + collectorSuffix;\n double apacheHttpCollectionIntervalValue = applicationConfiguration_.safeGetDouble(apacheCollectionIntervalKey, 30);\n long apacheHttpCollectionIntervalValue_Long = legacyMode ? (long) apacheHttpCollectionIntervalValue : (long) (apacheHttpCollectionIntervalValue * 1000); \n\n String apacheMetricPrefixKey = \"apachehttp_metric_prefix\" + collectorSuffix;\n String apacheHttpMetricPrefixValue = applicationConfiguration_.safeGetString(apacheMetricPrefixKey, \"ApacheHttp\");\n String graphiteSanitizedApacheHttpMetricPrefix = GraphiteMetric.getGraphiteSanitizedString(apacheHttpMetricPrefixValue, true, true);\n\n String apacheOutputFileValue = \"./output/\" + \"apachehttp_\" + graphiteSanitizedApacheHttpMetricPrefix + \".out\";\n \n if (apacheEnabledValue && (apacheHostValue != null) && (apachePortValue != -1)) {\n ApacheHttpMetricCollector apacheHttpMetricCollector = new ApacheHttpMetricCollector(apacheEnabledValue,\n apacheHttpCollectionIntervalValue_Long, graphiteSanitizedApacheHttpMetricPrefix, apacheOutputFileValue, outputInternalMetricsToDisk_,\n apacheProtocolValue, apacheHostValue, apachePortValue);\n \n return apacheHttpMetricCollector;\n }\n else return null;\n }\n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e)); \n return null;\n }\n }\n \n private static CadvisorMetricCollector readCadvisorMetricCollector(String collectorSuffix, boolean legacyMode) {\n \n if (applicationConfiguration_ == null) {\n return null;\n }\n \n if (collectorSuffix == null) collectorSuffix = \"\";\n\n try {\n String cadvisorEnabledKey = \"cadvisor_enabled\" + collectorSuffix;\n boolean cadvisorEnabledValue = applicationConfiguration_.safeGetBoolean(cadvisorEnabledKey, false);\n if (!cadvisorEnabledValue) return null;\n \n String cadvisorProtocolKey = \"cadvisor_protocol\" + collectorSuffix;\n String cadvisorProtocolValue = applicationConfiguration_.safeGetString(cadvisorProtocolKey, \"http\");\n \n String cadvisorHostKey = \"cadvisor_host\" + collectorSuffix;\n String cadvisorHostValue = applicationConfiguration_.safeGetString(cadvisorHostKey, \"127.0.0.1\");\n\n String cadvisorPortKey = \"cadvisor_port\" + collectorSuffix;\n int cadvisorPortValue = applicationConfiguration_.safeGetInteger(cadvisorPortKey, 8080);\n \n String cadvisorUsernameKey = \"cadvisor_username\" + collectorSuffix;\n String cadvisorUsernameValue = applicationConfiguration_.safeGetString(cadvisorUsernameKey, \"\");\n \n String cadvisorPasswordKey = \"cadvisor_password\" + collectorSuffix;\n String cadvisorPasswordValue = applicationConfiguration_.safeGetString(cadvisorPasswordKey, \"\");\n \n String cadvisorApiVersionKey = \"cadvisor_api_version\" + collectorSuffix;\n String cadvisorApiVersionValue = applicationConfiguration_.safeGetString(cadvisorApiVersionKey, \"v1.3\");\n \n String cadvisorCollectionIntervalKey = \"cadvisor_collection_interval\" + collectorSuffix;\n double cadvisorCollectionIntervalValue = applicationConfiguration_.safeGetDouble(cadvisorCollectionIntervalKey, 30);\n long cadvisorCollectionIntervalValue_Long = legacyMode ? (long) cadvisorCollectionIntervalValue : (long) (cadvisorCollectionIntervalValue * 1000); \n\n String cadvisorMetricPrefixKey = \"cadvisor_metric_prefix\" + collectorSuffix;\n String cadvisorMetricPrefixValue = applicationConfiguration_.safeGetString(cadvisorMetricPrefixKey, \"cAdvisor\");\n String graphiteSanitizedCadvisorMetricPrefix = GraphiteMetric.getGraphiteSanitizedString(cadvisorMetricPrefixValue, true, true);\n\n String cadvisorOutputFileValue = \"./output/\" + \"cadvisor_\" + graphiteSanitizedCadvisorMetricPrefix + \".out\";\n \n if (cadvisorEnabledValue && (cadvisorHostValue != null) && (cadvisorPortValue != -1)) {\n CadvisorMetricCollector cadvisorMetricCollector = new CadvisorMetricCollector(cadvisorEnabledValue,\n cadvisorCollectionIntervalValue_Long, graphiteSanitizedCadvisorMetricPrefix, cadvisorOutputFileValue, outputInternalMetricsToDisk_,\n cadvisorProtocolValue, cadvisorHostValue, cadvisorPortValue, cadvisorUsernameValue, cadvisorPasswordValue, cadvisorApiVersionValue);\n \n return cadvisorMetricCollector;\n }\n else return null;\n }\n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e)); \n return null;\n }\n }\n \n private static MongoMetricCollector readMongoMetricCollector(String collectorSuffix, boolean legacyMode) {\n \n if (applicationConfiguration_ == null) {\n return null;\n }\n \n if (collectorSuffix == null) collectorSuffix = \"\";\n\n try {\n String mongoEnabledKey = \"mongo_enabled\" + collectorSuffix;\n boolean mongoEnabledValue = applicationConfiguration_.safeGetBoolean(mongoEnabledKey, false);\n if (!mongoEnabledValue) return null;\n \n String mongoHostKey = \"mongo_host\" + collectorSuffix;\n String mongoHostValue = applicationConfiguration_.safeGetString(mongoHostKey, \"127.0.0.1\");\n\n String mongoPortKey = \"mongo_port\" + collectorSuffix;\n String mongoPortValue_String = applicationConfiguration_.safeGetString(mongoPortKey, \"27017\").trim();\n boolean isPortNumeric = StringUtils.isNumeric(mongoPortValue_String) && !mongoPortValue_String.isBlank();\n Integer mongoPortValue = isPortNumeric ? Integer.valueOf(mongoPortValue_String) : null;\n \n String mongoUsernameKey = \"mongo_username\" + collectorSuffix;\n String mongoUsernameValue = applicationConfiguration_.safeGetString(mongoUsernameKey, \"\");\n \n String mongoPasswordKey = \"mongo_password\" + collectorSuffix;\n String mongoPasswordValue = applicationConfiguration_.safeGetString(mongoPasswordKey, \"\");\n \n String mongoVerboseOutputKey = \"mongo_verbose_output\" + collectorSuffix;\n boolean mongoVerboseOutputValue = applicationConfiguration_.safeGetBoolean(mongoVerboseOutputKey, false); \n \n String mongoCollectionIntervalKey = \"mongo_collection_interval\" + collectorSuffix;\n double mongoCollectionIntervalValue = applicationConfiguration_.safeGetDouble(mongoCollectionIntervalKey, 60);\n long mongoCollectionIntervalValue_Long = legacyMode ? (long) mongoCollectionIntervalValue : (long) (mongoCollectionIntervalValue * 1000); \n\n String mongoMetricPrefixKey = \"mongo_metric_prefix\" + collectorSuffix;\n String mongoMetricPrefixValue = applicationConfiguration_.safeGetString(mongoMetricPrefixKey, \"Mongo\");\n String graphiteSanitizedMongoMetricPrefix = GraphiteMetric.getGraphiteSanitizedString(mongoMetricPrefixValue, true, true);\n \n String mongoSrvRecordKey = \"mongo_srv_record\" + collectorSuffix;\n boolean mongoSrvRecordValue = applicationConfiguration_.safeGetBoolean(mongoSrvRecordKey, false);\n \n String mongoArgumentsKey = \"mongo_arguments\" + collectorSuffix;\n String mongoArgumentsValue = applicationConfiguration_.safeGetString(mongoArgumentsKey, \"authSource=admin\");\n \n String mongoOutputFileValue = \"./output/\" + \"mongo_\" + graphiteSanitizedMongoMetricPrefix + \".out\";\n\n if (mongoEnabledValue && (mongoHostValue != null)) {\n MongoMetricCollector mongoMetricCollector = new MongoMetricCollector(mongoEnabledValue, \n mongoCollectionIntervalValue_Long, graphiteSanitizedMongoMetricPrefix, mongoOutputFileValue, outputInternalMetricsToDisk_,\n mongoHostValue, mongoPortValue, mongoUsernameValue, mongoPasswordValue, mongoVerboseOutputValue, mongoSrvRecordValue, mongoArgumentsValue);\n \n return mongoMetricCollector;\n }\n else return null;\n }\n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e)); \n return null;\n }\n }\n\n private static MysqlMetricCollector readMysqlMetricCollector(String collectorSuffix, boolean legacyMode) {\n \n if (applicationConfiguration_ == null) {\n return null;\n }\n \n if (collectorSuffix == null) collectorSuffix = \"\";\n List<OpenTsdbTag> openTsdbTags = new ArrayList<>();\n \n try {\n String mysqlEnabledKey = \"mysql_enabled\" + collectorSuffix;\n boolean mysqlEnabledValue = applicationConfiguration_.safeGetBoolean(mysqlEnabledKey, false);\n if (!mysqlEnabledValue) return null;\n \n String mysqlHostKey = \"mysql_host\" + collectorSuffix;\n String mysqlHostValue = applicationConfiguration_.safeGetString(mysqlHostKey, \"127.0.0.1\");\n String openTsdbFriendlyHost = OpenTsdbMetric.getOpenTsdbSanitizedString(mysqlHostValue);\n openTsdbTags.add(new OpenTsdbTag(\"Host=\" + openTsdbFriendlyHost));\n\n String mysqlPortKey = \"mysql_port\" + collectorSuffix;\n int mysqlPortValue = applicationConfiguration_.safeGetInteger(mysqlPortKey, 3306);\n String openTsdbFriendlyPort = OpenTsdbMetric.getOpenTsdbSanitizedString(Integer.toString(mysqlPortValue));\n openTsdbTags.add(new OpenTsdbTag(\"Port=\" + openTsdbFriendlyPort));\n\n String mysqlUsernameKey = \"mysql_username\" + collectorSuffix;\n String mysqlUsernameValue = applicationConfiguration_.safeGetString(mysqlUsernameKey, \"\");\n \n String mysqlPasswordKey = \"mysql_password\" + collectorSuffix;\n String mysqlPasswordValue = applicationConfiguration_.safeGetString(mysqlPasswordKey, \"\");\n \n String mysqlJdbcKey = \"mysql_jdbc\" + collectorSuffix;\n String mysqlJdbcValue = applicationConfiguration_.safeGetString(mysqlJdbcKey, \"\");\n \n String mysqlCollectionIntervalKey = \"mysql_collection_interval\" + collectorSuffix;\n double mysqlCollectionIntervalValue = applicationConfiguration_.safeGetDouble(mysqlCollectionIntervalKey, 60);\n long mysqlCollectionIntervalValue_Long = legacyMode ? (long) mysqlCollectionIntervalValue : (long) (mysqlCollectionIntervalValue * 1000); \n\n String mysqlMetricPrefixKey = \"mysql_metric_prefix\" + collectorSuffix;\n String mysqlMetricPrefixValue = applicationConfiguration_.safeGetString(mysqlMetricPrefixKey, \"MySQL\");\n String graphiteSanitizedMysqlMetricPrefix = GraphiteMetric.getGraphiteSanitizedString(mysqlMetricPrefixValue, true, true);\n \n String mysqlOutputFileValue = \"./output/\" + \"mysql_\" + graphiteSanitizedMysqlMetricPrefix + \".out\";\n\n if (mysqlEnabledValue && (mysqlHostValue != null) && (mysqlPortValue != -1)) {\n MysqlMetricCollector mysqlMetricCollector = new MysqlMetricCollector(mysqlEnabledValue, \n mysqlCollectionIntervalValue_Long, graphiteSanitizedMysqlMetricPrefix, mysqlOutputFileValue, outputInternalMetricsToDisk_,\n mysqlHostValue, mysqlPortValue, mysqlUsernameValue, mysqlPasswordValue, mysqlJdbcValue, \n openTsdbTags);\n \n return mysqlMetricCollector;\n }\n else return null;\n }\n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e)); \n return null;\n }\n }\n \n private static PostgresMetricCollector readPostgresMetricCollector(String collectorSuffix, boolean legacyMode) {\n \n if (applicationConfiguration_ == null) {\n return null;\n }\n \n if (collectorSuffix == null) collectorSuffix = \"\";\n List<OpenTsdbTag> openTsdbTags = new ArrayList<>();\n \n try {\n String postgresEnabledKey = \"postgres_enabled\" + collectorSuffix;\n boolean postgresEnabledValue = applicationConfiguration_.safeGetBoolean(postgresEnabledKey, false);\n if (!postgresEnabledValue) return null;\n\n String postgresHostKey = \"postgres_host\" + collectorSuffix;\n String postgresHostValue = applicationConfiguration_.safeGetString(postgresHostKey, \"127.0.0.1\");\n String openTsdbFriendlyHost = OpenTsdbMetric.getOpenTsdbSanitizedString(postgresHostValue);\n openTsdbTags.add(new OpenTsdbTag(\"Host=\" + openTsdbFriendlyHost));\n\n String postgresPortKey = \"postgres_port\" + collectorSuffix;\n int postgresPortValue = applicationConfiguration_.safeGetInteger(postgresPortKey, 5432);\n String openTsdbFriendlyPort = OpenTsdbMetric.getOpenTsdbSanitizedString(Integer.toString(postgresPortValue));\n openTsdbTags.add(new OpenTsdbTag(\"Port=\" + openTsdbFriendlyPort));\n\n String postgresUsernameKey = \"postgres_username\" + collectorSuffix;\n String postgresUsernameValue = applicationConfiguration_.safeGetString(postgresUsernameKey, \"\");\n \n String postgresPasswordKey = \"postgres_password\" + collectorSuffix;\n String postgresPasswordValue = applicationConfiguration_.safeGetString(postgresPasswordKey, \"\");\n \n String postgresJdbcKey = \"postgres_jdbc\" + collectorSuffix;\n String postgresJdbcValue = applicationConfiguration_.safeGetString(postgresJdbcKey, \"\");\n \n String postgresCollectionIntervalKey = \"postgres_collection_interval\" + collectorSuffix;\n double postgresCollectionIntervalValue = applicationConfiguration_.safeGetDouble(postgresCollectionIntervalKey, 60);\n long postgresCollectionIntervalValue_Long = legacyMode ? (long) postgresCollectionIntervalValue : (long) (postgresCollectionIntervalValue * 1000); \n\n String postgresMetricPrefixKey = \"postgres_metric_prefix\" + collectorSuffix;\n String postgresMetricPrefixValue = applicationConfiguration_.safeGetString(postgresMetricPrefixKey, \"PostgreSQL\");\n String graphiteSanitizedMysqlMetricPrefix = GraphiteMetric.getGraphiteSanitizedString(postgresMetricPrefixValue, true, true);\n \n String postgresOutputFileValue = \"./output/\" + \"postgres_\" + graphiteSanitizedMysqlMetricPrefix + \".out\";\n\n if (postgresEnabledValue && (postgresHostValue != null) && (postgresPortValue != -1)) {\n PostgresMetricCollector postgresMetricCollector = new PostgresMetricCollector(postgresEnabledValue, \n postgresCollectionIntervalValue_Long, graphiteSanitizedMysqlMetricPrefix, postgresOutputFileValue, outputInternalMetricsToDisk_,\n postgresHostValue, postgresPortValue, postgresUsernameValue, postgresPasswordValue, postgresJdbcValue, \n openTsdbTags);\n \n return postgresMetricCollector;\n }\n else return null;\n }\n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e)); \n return null;\n }\n }\n\n private static DbQuerier readDbQuerierMetricCollector(String collectorSuffix, boolean legacyMode) {\n \n if (applicationConfiguration_ == null) {\n return null;\n }\n \n if (collectorSuffix == null) collectorSuffix = \"\";\n \n try {\n String dbQuerierEnabledKey = \"db_querier_enabled\" + collectorSuffix;\n boolean dbQuerierEnabledValue = applicationConfiguration_.safeGetBoolean(dbQuerierEnabledKey, false);\n if (!dbQuerierEnabledValue) return null;\n\n String dbQuerierUsernameKey = \"db_querier_username\" + collectorSuffix;\n String dbQuerierUsernameValue = applicationConfiguration_.safeGetString(dbQuerierUsernameKey, \"\");\n \n String dbQuerierPasswordKey = \"db_querier_password\" + collectorSuffix;\n String dbQuerierPasswordValue = applicationConfiguration_.safeGetString(dbQuerierPasswordKey, \"\");\n \n String dbQuerierJdbcKey = \"db_querier_jdbc\" + collectorSuffix;\n String dbQuerierJdbcValue = applicationConfiguration_.safeGetString(dbQuerierJdbcKey, \"\");\n \n String dbQuerierCollectionIntervalKey = \"db_querier_collection_interval\" + collectorSuffix;\n double dbQuerierCollectionIntervalValue = applicationConfiguration_.safeGetDouble(dbQuerierCollectionIntervalKey, 60);\n long dbQuerierCollectionIntervalValue_Long = legacyMode ? (long) dbQuerierCollectionIntervalValue : (long) (dbQuerierCollectionIntervalValue * 1000); \n\n String dbQuerierMetricPrefixKey = \"db_querier_metric_prefix\" + collectorSuffix;\n String dbQuerierMetricPrefixValue = applicationConfiguration_.safeGetString(dbQuerierMetricPrefixKey, \"DB_Querier\");\n String graphiteSanitizedDbQuerierMetricPrefix = GraphiteMetric.getGraphiteSanitizedString(dbQuerierMetricPrefixValue, true, true);\n \n String dbQuerierQueryKey = \"db_querier_query\" + collectorSuffix;\n List<Object> dbQuerierQueryValues_Objects = applicationConfiguration_.safeGetList(dbQuerierQueryKey, new ArrayList<>());\n List<String> dbQuerierQueryValues_Strings = new ArrayList<>();\n for (Object object : dbQuerierQueryValues_Objects) dbQuerierQueryValues_Strings.add(object.toString());\n \n String dbQuerierOutputFileValue = \"./output/\" + \"db_querier_\" + graphiteSanitizedDbQuerierMetricPrefix + \".out\";\n\n if (dbQuerierEnabledValue && (dbQuerierJdbcValue != null) && (!dbQuerierJdbcValue.trim().isEmpty())) {\n DbQuerier dbQuerier = new DbQuerier(dbQuerierEnabledValue, \n dbQuerierCollectionIntervalValue_Long, graphiteSanitizedDbQuerierMetricPrefix, dbQuerierOutputFileValue, outputInternalMetricsToDisk_,\n dbQuerierUsernameValue, dbQuerierPasswordValue, dbQuerierJdbcValue, dbQuerierQueryValues_Strings);\n \n return dbQuerier;\n }\n else return null;\n }\n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e)); \n return null;\n }\n }\n \n private static void loadMySQLDrivers() {\n \n if ((mysqlMetricCollectors_ == null) || mysqlMetricCollectors_.isEmpty()) {\n return;\n }\n\n try {\n Class.forName(\"org.mariadb.jdbc.Driver\").newInstance();\n }\n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n \n try {\n Class.forName(\"com.mysql.jdbc.Driver\").newInstance();\n }\n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n }\n \n public static boolean isGlobalMetricNamePrefixEnabled() {\n return globalMetricNamePrefixEnabled_;\n }\n\n public static String getGlobalMetricNamePrefix() {\n return globalMetricNamePrefix_;\n }\n\n public static long getOutputInterval() {\n return outputInterval_;\n }\n\n public static long getCheckOutputFilesInterval() {\n return checkOutputFilesInterval_;\n }\n \n public static boolean isAlwaysCheckOutputFiles() {\n return alwaysCheckOutputFiles_;\n }\n\n public static long getMaxMetricAge() {\n return maxMetricAge_;\n }\n\n public static boolean isOutputInternalMetricsToDisk() {\n return outputInternalMetricsToDisk_;\n }\n\n public static boolean isLegacyMode() {\n return legacyMode_;\n }\n\n public static List<GraphiteOutputModule> getGraphiteOutputModules() {\n if (graphiteOutputModules_ == null) return null;\n else return new ArrayList<>(graphiteOutputModules_);\n }\n\n public static List<OpenTsdbTelnetOutputModule> getOpenTsdbTelnetOutputModules() {\n if (openTsdbTelnetOutputModules_ == null) return null;\n else return new ArrayList<>(openTsdbTelnetOutputModules_);\n }\n\n public static List<OpenTsdbHttpOutputModule> getOpenTsdbHttpOutputModules() {\n if (openTsdbHttpOutputModules_ == null) return null;\n else return new ArrayList<>(openTsdbHttpOutputModules_);\n }\n \n public static String getStatspollerMetricCollectorPrefix() {\n return statspollerMetricCollectorPrefix_;\n }\n \n public static boolean isStatsPollerEnableJavaMetricCollector() {\n return statspollerEnableJavaMetricCollector_;\n }\n \n public static long getStatspollerJavaMetricCollectorCollectionInterval() {\n return statspollerJavaMetricCollectorCollectionInterval_;\n }\n \n public static boolean isLinuxMetricCollectorEnable() {\n return linuxMetricCollectorEnable_;\n }\n \n public static String getLinuxProcLocation() {\n return linuxProcLocation_;\n }\n\n public static String getLinuxSysLocation() {\n return linuxSysLocation_;\n }\n \n public static long getLinuxMetricCollectorCollectionInterval() {\n return linuxMetricCollectorCollectionInterval_;\n }\n\n public static List<String[]> getProcessCounterPrefixesAndRegexes() {\n if (processCounterPrefixesAndRegexes_ == null) return null;\n return new ArrayList<>(processCounterPrefixesAndRegexes_);\n }\n\n public static long getProcessCounterMetricCollectorCollectionInterval() {\n return processCounterMetricCollectorCollectionInterval_;\n }\n\n public static List<FileCounterMetricCollector> getFileCounterMetricCollectors() {\n if (fileCounterMetricCollectors_ == null) return null;\n return new ArrayList<>(fileCounterMetricCollectors_);\n }\n \n public static List<ExternalMetricCollector> getExternalMetricCollectors() {\n if (externalMetricCollectors_ == null) return null;\n return new ArrayList<>(externalMetricCollectors_);\n }\n\n public static List<JmxMetricCollector> getJmxMetricCollectors() {\n if (jmxMetricCollectors_ == null) return null;\n return new ArrayList<>(jmxMetricCollectors_);\n }\n\n public static List<ApacheHttpMetricCollector> getApacheHttpMetricCollectors() {\n if (apacheHttpMetricCollectors_ == null) return null;\n return new ArrayList<>(apacheHttpMetricCollectors_);\n }\n\n public static List<CadvisorMetricCollector> getCadvisorMetricCollectors() {\n if (cadvisorMetricCollectors_ == null) return null;\n return new ArrayList<>(cadvisorMetricCollectors_);\n }\n \n public static List<MongoMetricCollector> getMongoMetricCollectors() {\n if (mongoMetricCollectors_ == null) return null;\n return new ArrayList<>(mongoMetricCollectors_);\n }\n\n public static List<MysqlMetricCollector> getMysqlMetricCollectors() {\n if (mysqlMetricCollectors_ == null) return null;\n return new ArrayList<>(mysqlMetricCollectors_);\n }\n \n public static List<PostgresMetricCollector> getPostgresMetricCollectors() {\n if (postgresMetricCollectors_ == null) return null;\n return new ArrayList<>(postgresMetricCollectors_);\n }\n \n public static List<DbQuerier> getDbQueriers() {\n if (dbQuerier_ == null) return null;\n return new ArrayList<>(dbQuerier_);\n }\n\n public static long getApplicationStartTimeInMs() {\n return applicationStartTimeInMs_;\n }\n\n public static String getHostname() {\n return hostname_;\n }\n\n}",
"public class GlobalVariables {\n \n private static final Logger logger = LoggerFactory.getLogger(GlobalVariables.class.getName());\n \n public final static ConcurrentHashMap<Long,GraphiteMetric> graphiteMetrics = new ConcurrentHashMap<>();\n public final static ConcurrentHashMap<Long,OpenTsdbMetric> openTsdbMetrics = new ConcurrentHashMap<>();\n public final static AtomicLong metricHashKeyGenerator = new AtomicLong(Long.MIN_VALUE);\n public final static AtomicLong metricTransmitErrorCount = new AtomicLong(0l);\n \n}",
"public class GraphiteMetric implements GraphiteMetricFormat, OpenTsdbMetricFormat, GenericMetricFormat, InfluxdbMetricFormat_v1 {\n \n private static final Logger logger = LoggerFactory.getLogger(GraphiteMetric.class.getName());\n \n private long hashKey_ = -1;\n \n private final String metricPath_;\n private final BigDecimal metricValue_;\n private final long metricTimestamp_;\n private final long metricReceivedTimestampInMilliseconds_;\n \n private final boolean isMetricTimestampInSeconds_;\n \n // metricTimestamp is assumed to be in seconds\n public GraphiteMetric(String metricPath, BigDecimal metricValue, int metricTimestamp) {\n this.metricPath_ = metricPath;\n this.metricValue_ = metricValue;\n this.metricTimestamp_ = metricTimestamp;\n this.metricReceivedTimestampInMilliseconds_ = ((long) metricTimestamp) * 1000;\n \n this.isMetricTimestampInSeconds_ = true;\n }\n \n // metricTimestamp is assumed to be in seconds\n public GraphiteMetric(String metricPath, BigDecimal metricValue, int metricTimestamp, long metricReceivedTimestampInMilliseconds) {\n this.metricPath_ = metricPath;\n this.metricValue_ = metricValue;\n this.metricTimestamp_ = metricTimestamp;\n this.metricReceivedTimestampInMilliseconds_ = metricReceivedTimestampInMilliseconds;\n \n this.isMetricTimestampInSeconds_ = true;\n }\n \n // metricTimestamp is assumed to be in milliseconds\n public GraphiteMetric(String metricPath, BigDecimal metricValue, long metricTimestamp, long metricReceivedTimestampInMilliseconds) {\n this.metricPath_ = metricPath;\n this.metricValue_ = metricValue;\n this.metricTimestamp_ = metricTimestamp;\n this.metricReceivedTimestampInMilliseconds_ = metricReceivedTimestampInMilliseconds;\n \n this.isMetricTimestampInSeconds_ = false;\n }\n \n @Override\n public int hashCode() {\n return new HashCodeBuilder(11, 13)\n .append(metricPath_)\n .append(metricValue_)\n .append(metricTimestamp_)\n .append(metricReceivedTimestampInMilliseconds_)\n .append(isMetricTimestampInSeconds_)\n .toHashCode();\n }\n \n @Override\n public boolean equals(Object obj) {\n if (obj == null) return false;\n if (obj == this) return true;\n if (obj.getClass() != getClass()) return false;\n \n GraphiteMetric graphiteMetric = (GraphiteMetric) obj;\n \n boolean isMetricValueEqual = false;\n if ((metricValue_ != null) && (graphiteMetric.getMetricValue() != null)) {\n isMetricValueEqual = metricValue_.compareTo(graphiteMetric.getMetricValue()) == 0;\n }\n else if (metricValue_ == null) {\n isMetricValueEqual = graphiteMetric.getMetricValue() == null;\n }\n \n return new EqualsBuilder()\n .append(metricPath_, graphiteMetric.getMetricPath())\n .append(isMetricValueEqual, true)\n .append(metricTimestamp_, graphiteMetric.getMetricTimestamp())\n .append(metricReceivedTimestampInMilliseconds_, graphiteMetric.getMetricReceivedTimestampInMilliseconds())\n .append(isMetricTimestampInSeconds_, isMetricTimestampInSeconds())\n .isEquals();\n }\n \n @Override\n public String toString() {\n StringBuilder stringBuilder = new StringBuilder();\n \n stringBuilder.append(metricPath_).append(\" \")\n .append(getMetricValueString()).append(\" \") \n .append(metricTimestamp_)\n .append(\" @ \").append(metricReceivedTimestampInMilliseconds_);\n \n return stringBuilder.toString();\n }\n\n @Override\n public String getGraphiteFormatString(boolean sanitizeMetric, boolean substituteCharacters) {\n StringBuilder stringBuilder = new StringBuilder();\n \n String metricPath = GraphiteMetric.getGraphiteSanitizedString(metricPath_, sanitizeMetric, substituteCharacters);\n \n stringBuilder.append(metricPath).append(\" \").append(getMetricValueString()).append(\" \").append(getMetricTimestampInSeconds());\n\n return stringBuilder.toString();\n }\n \n @Override\n public String getOpenTsdbTelnetFormatString(boolean sanitizeMetric) {\n return getOpenTsdbTelnetFormatString(sanitizeMetric, null, null);\n }\n \n @Override\n public String getOpenTsdbTelnetFormatString(boolean sanitizeMetric, String defaultOpenTsdbTagKey, String defaultOpenTsdbTagValue) {\n StringBuilder stringBuilder = new StringBuilder();\n \n String metric = sanitizeMetric ? OpenTsdbMetric.getOpenTsdbSanitizedString(metricPath_) : metricPath_;\n \n String tag = (defaultOpenTsdbTagKey == null) ? \"Format=Graphite\" : (defaultOpenTsdbTagKey + \"=\" + defaultOpenTsdbTagValue);\n \n stringBuilder.append(metric).append(\" \").append(getMetricTimestampInSeconds()).append(\" \").append(getMetricValueString()).append(\" \").append(tag);\n\n return stringBuilder.toString();\n }\n \n @Override\n public String getOpenTsdbJsonFormatString(boolean sanitizeMetric) {\n return getOpenTsdbJsonFormatString(sanitizeMetric, null, null);\n }\n \n @Override\n public String getOpenTsdbJsonFormatString(boolean sanitizeMetric, String defaultOpenTsdbTagKey, String defaultOpenTsdbTagValue) {\n \n if ((metricPath_ == null) || metricPath_.isEmpty()) return null;\n if (getMetricTimestampInSeconds() < 0) return null;\n if ((getMetricValue() == null)) return null;\n \n StringBuilder openTsdbJson = new StringBuilder();\n\n openTsdbJson.append(\"{\");\n\n if (sanitizeMetric) openTsdbJson.append(\"\\\"metric\\\":\\\"\").append(StringEscapeUtils.escapeJson(OpenTsdbMetric.getOpenTsdbSanitizedString(metricPath_))).append(\"\\\",\");\n else openTsdbJson.append(\"\\\"metric\\\":\\\"\").append(StringEscapeUtils.escapeJson(metricPath_)).append(\"\\\",\");\n \n openTsdbJson.append(\"\\\"timestamp\\\":\").append(getMetricTimestampInSeconds()).append(\",\");\n openTsdbJson.append(\"\\\"value\\\":\").append(getMetricValueString()).append(\",\");\n\n openTsdbJson.append(\"\\\"tags\\\":{\");\n if ((defaultOpenTsdbTagKey == null) || (defaultOpenTsdbTagValue == null)) openTsdbJson.append(\"\\\"Format\\\":\\\"Graphite\\\"\");\n else openTsdbJson.append(\"\\\"\").append(defaultOpenTsdbTagKey).append(\"\\\":\\\"\").append(defaultOpenTsdbTagValue).append(\"\\\"\");\n openTsdbJson.append(\"}\");\n\n openTsdbJson.append(\"}\");\n \n return openTsdbJson.toString();\n }\n \n @Override\n public String getInfluxdbV1JsonFormatString() {\n\n if ((metricPath_ == null) || metricPath_.isEmpty()) return null;\n if (metricTimestamp_ < 0) return null;\n if ((getMetricValue() == null)) return null;\n\n StringBuilder influxdbJson = new StringBuilder();\n\n influxdbJson.append(\"{\");\n\n // the metric name, with the prefix already built-in\n influxdbJson.append(\"\\\"name\\\":\\\"\").append(StringEscapeUtils.escapeJson(metricPath_)).append(\"\\\",\");\n\n // column order: value, time, tag(s)\n influxdbJson.append(\"\\\"columns\\\":[\\\"value\\\",\\\"time\\\"],\");\n\n // only include one point in the points array. note-- timestamp will always be sent to influxdb in milliseconds\n influxdbJson.append(\"\\\"points\\\":[[\");\n influxdbJson.append(getMetricValueString()).append(\",\");\n influxdbJson.append(getMetricTimestampInMilliseconds());\n \n influxdbJson.append(\"]]}\");\n\n return influxdbJson.toString();\n }\n \n /*\n @param unsanitizedInput The input is expected to be a Graphite 'metric path'.\n \n @param sanitizeMetric When set to true, all input will have back-to-back '.' characters merged into a single '.'.\n Example: \"lol...lol\" -> \"lol.lol\"\n \n @param 'substituteCharacters' When set to true: a few special characters will be turned into characters that Graphite can handle. \n % -> Pct\n (){}[]/\\ -> |\n */\n public static String getGraphiteSanitizedString(String unsanitizedInput, boolean sanitizeMetric, boolean substituteCharacters) {\n\n if (unsanitizedInput == null) return null;\n if (!sanitizeMetric && !substituteCharacters) return unsanitizedInput;\n \n StringBuilder sanitizedInput = new StringBuilder();\n\n for (int i = 0; i < unsanitizedInput.length(); i++) {\n char character = unsanitizedInput.charAt(i);\n\n if (substituteCharacters && Character.isLetterOrDigit(character)) {\n sanitizedInput.append(character);\n continue;\n }\n\n if (sanitizeMetric && (character == '.')) {\n int iPlusOne = i + 1;\n \n if (((iPlusOne < unsanitizedInput.length()) && (unsanitizedInput.charAt(iPlusOne) != '.')) || (iPlusOne == unsanitizedInput.length())) {\n sanitizedInput.append(character);\n continue;\n }\n }\n\n if (substituteCharacters) {\n if (character == '%') {\n sanitizedInput.append(\"Pct\");\n continue;\n }\n \n if (character == ' ') {\n sanitizedInput.append(\"_\");\n continue;\n }\n \n if ((character == '\\\\') || (character == '/') || \n (character == '[') || (character == ']') || \n (character == '{') || (character == '}') ||\n (character == '(') || (character == ')')) {\n sanitizedInput.append(\"|\");\n continue;\n }\n\n }\n \n if (sanitizeMetric && (character != '.')) sanitizedInput.append(character);\n else if (!sanitizeMetric) sanitizedInput.append(character);\n }\n \n return sanitizedInput.toString();\n }\n \n public static GraphiteMetric parseGraphiteMetric(String unparsedMetric, String metricPrefix, long metricReceivedTimestampInMilliseconds) {\n \n if (unparsedMetric == null) {\n return null;\n }\n \n try {\n int metricPathIndexRange = unparsedMetric.indexOf(' ', 0);\n String metricPath = null;\n if (metricPathIndexRange > 0) {\n if ((metricPrefix != null) && !metricPrefix.isEmpty()) metricPath = metricPrefix + unparsedMetric.substring(0, metricPathIndexRange);\n else metricPath = unparsedMetric.substring(0, metricPathIndexRange);\n }\n\n int metricValueIndexRange = unparsedMetric.indexOf(' ', metricPathIndexRange + 1);\n BigDecimal metricValueBigDecimal = null;\n if (metricValueIndexRange > 0) {\n String metricValueString = unparsedMetric.substring(metricPathIndexRange + 1, metricValueIndexRange);\n \n if (metricValueString.length() > 100) {\n logger.debug(\"Metric parse error. Metric value can't be more than 100 characters long. Metric value was \\\"\" + metricValueString.length() + \"\\\" characters long.\");\n }\n else {\n metricValueBigDecimal = new BigDecimal(metricValueString);\n }\n }\n\n String metricTimestampString = unparsedMetric.substring(metricValueIndexRange + 1, unparsedMetric.length());\n int metricTimestamp = Integer.parseInt(metricTimestampString);\n \n if ((metricPath == null) || metricPath.isEmpty() || (metricValueBigDecimal == null) ||\n (metricTimestampString == null) || metricTimestampString.isEmpty() || \n (metricTimestampString.length() != 10) || (metricTimestamp < 0)) {\n logger.warn(\"Metric parse error: \\\"\" + unparsedMetric + \"\\\"\");\n return null;\n }\n else {\n GraphiteMetric graphiteMetric = new GraphiteMetric(metricPath, metricValueBigDecimal, metricTimestamp, metricReceivedTimestampInMilliseconds); \n return graphiteMetric;\n }\n }\n catch (NumberFormatException e) {\n logger.error(\"Error on \" + unparsedMetric + System.lineSeparator() + e.toString() + System.lineSeparator()); \n return null;\n }\n catch (Exception e) {\n logger.error(\"Error on \" + unparsedMetric + System.lineSeparator() + e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e)); \n return null;\n }\n }\n \n public static List<GraphiteMetric> parseGraphiteMetrics(String unparsedMetrics, long metricReceivedTimestampInMilliseconds) {\n return parseGraphiteMetrics(unparsedMetrics, null, metricReceivedTimestampInMilliseconds);\n }\n \n public static List<GraphiteMetric> parseGraphiteMetrics(String unparsedMetrics, String metricPrefix, long metricReceivedTimestampInMilliseconds) {\n \n if ((unparsedMetrics == null) || unparsedMetrics.isEmpty()) {\n return new ArrayList<>();\n }\n \n List<GraphiteMetric> graphiteMetrics = new ArrayList();\n \n try {\n int currentIndex = 0;\n int newLineLocation = 0;\n\n while(newLineLocation != -1) {\n newLineLocation = unparsedMetrics.indexOf('\\n', currentIndex);\n\n String unparsedMetric;\n\n if (newLineLocation == -1) {\n unparsedMetric = unparsedMetrics.substring(currentIndex, unparsedMetrics.length());\n }\n else {\n unparsedMetric = unparsedMetrics.substring(currentIndex, newLineLocation);\n currentIndex = newLineLocation + 1;\n }\n\n if ((unparsedMetric != null) && !unparsedMetric.isEmpty()) {\n GraphiteMetric graphiteMetric = GraphiteMetric.parseGraphiteMetric(unparsedMetric.trim(), metricPrefix, metricReceivedTimestampInMilliseconds);\n\n if (graphiteMetric != null) {\n graphiteMetrics.add(graphiteMetric);\n }\n }\n }\n }\n catch (Exception e) {\n logger.warn(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n \n return graphiteMetrics;\n }\n\n public long getHashKey() {\n return this.hashKey_;\n }\n \n @Override\n public long getMetricHashKey() {\n return getHashKey();\n }\n \n public void setHashKey(long hashKey) {\n this.hashKey_ = hashKey;\n }\n \n @Override\n public void setMetricHashKey(long hashKey) {\n setHashKey(hashKey);\n }\n \n public String getMetricPath() {\n return metricPath_;\n }\n \n @Override\n public String getMetricKey() {\n return getMetricPath();\n }\n \n public BigDecimal getMetricValue() {\n return metricValue_;\n }\n \n @Override\n public BigDecimal getMetricValueBigDecimal() {\n return metricValue_;\n }\n \n @Override\n public String getMetricValueString() {\n if (metricValue_ == null) return null;\n return MathUtilities.getFastPlainStringWithNoTrailingZeros(metricValue_);\n }\n \n public long getMetricTimestamp() {\n return metricTimestamp_;\n }\n \n @Override\n public int getMetricTimestampInSeconds() {\n if (isMetricTimestampInSeconds_) return (int) metricTimestamp_;\n else return (int) (metricTimestamp_ / 1000);\n }\n \n @Override\n public long getMetricTimestampInMilliseconds() {\n if (!isMetricTimestampInSeconds_) return metricTimestamp_;\n else return (long) (metricTimestamp_ * 1000);\n }\n \n @Override\n public long getMetricReceivedTimestampInMilliseconds() {\n return metricReceivedTimestampInMilliseconds_;\n }\n\n public boolean isMetricTimestampInSeconds() {\n return isMetricTimestampInSeconds_;\n }\n \n}",
"public class OpenTsdbMetric implements GraphiteMetricFormat, OpenTsdbMetricFormat, GenericMetricFormat, InfluxdbMetricFormat_v1 {\n \n private static final Logger logger = LoggerFactory.getLogger(OpenTsdbMetric.class.getName());\n \n private long hashKey_ = -1;\n \n private final long metricTimestamp_;\n private final BigDecimal metricValue_;\n private final boolean isTimestampInMilliseconds_;\n private long metricReceivedTimestampInMilliseconds_ = -1;\n \n private String metricKey_ = null;\n private final int metricLength_; // 'metric' refers to the OpenTSDB 'metric name' \n\n public OpenTsdbMetric(String metric, long metricTimestampInMilliseconds, BigDecimal metricValue, List<OpenTsdbTag> tags) {\n this.metricTimestamp_ = metricTimestampInMilliseconds;\n this.metricValue_ = metricValue;\n this.isTimestampInMilliseconds_ = true;\n this.metricReceivedTimestampInMilliseconds_ = metricTimestampInMilliseconds;\n \n this.metricKey_ = createAndGetMetricKey(metric, tags);\n \n if (metric != null) this.metricLength_ = metric.length();\n else this.metricLength_ = -1;\n }\n \n public OpenTsdbMetric(String metric, int metricTimestampInSeconds, BigDecimal metricValue, List<OpenTsdbTag> tags) {\n this.metricTimestamp_ = metricTimestampInSeconds;\n this.metricValue_ = metricValue;\n this.isTimestampInMilliseconds_ = false;\n this.metricReceivedTimestampInMilliseconds_ = metricTimestampInSeconds * 1000;\n \n this.metricKey_ = createAndGetMetricKey(metric, tags);\n \n if (metric != null) this.metricLength_ = metric.length();\n else this.metricLength_ = -1;\n }\n \n public OpenTsdbMetric(String metric, long metricTimestamp, BigDecimal metricValue, List<OpenTsdbTag> tags, \n boolean isTimestampInMilliseconds, long metricReceivedTimestampInMilliseconds) {\n this.metricTimestamp_ = metricTimestamp;\n this.metricValue_ = metricValue;\n this.isTimestampInMilliseconds_ = isTimestampInMilliseconds;\n this.metricReceivedTimestampInMilliseconds_ = metricReceivedTimestampInMilliseconds;\n \n this.metricKey_ = createAndGetMetricKey(metric, tags);\n \n if (metric != null) this.metricLength_ = metric.length();\n else this.metricLength_ = -1;\n }\n\n public final String createAndGetMetricKey(String metric, List<OpenTsdbTag> tags) {\n\n if (metricKey_ != null) return metricKey_;\n if (metric == null) return null;\n \n ArrayList sortedUnparseTags = getSortedUnparsedTags(tags);\n if ((sortedUnparseTags == null) || sortedUnparseTags.isEmpty()) return null;\n \n StringBuilder metricKey = new StringBuilder(64);\n \n metricKey.append(metric);\n metricKey.append(\" : \");\n\n for (int i = 0; i < sortedUnparseTags.size(); i++) {\n metricKey.append(sortedUnparseTags.get(i));\n if ((i + 1) != sortedUnparseTags.size()) metricKey.append(\" \");\n }\n \n metricKey_ = metricKey.toString();\n \n return metricKey_;\n }\n \n private String getMetricFromMetricKey() {\n if (metricKey_ == null) return null;\n if (metricLength_ < 0) return null;\n if (metricLength_ >= metricKey_.length()) return metricKey_;\n \n return metricKey_.substring(0, metricLength_);\n }\n\n private List<OpenTsdbTag> getMetricTagsFromMetricKey() {\n if (metricKey_ == null) return new ArrayList<>();\n if (metricLength_ < 1) return new ArrayList<>();\n if ((metricLength_ + 3) >= metricKey_.length()) return new ArrayList<>();\n \n List<OpenTsdbTag> openTsdbTags = OpenTsdbTag.parseTags(metricKey_, metricLength_ + 2);\n return openTsdbTags;\n }\n \n /*\n The input is expected to be an OpenTSDB metric, an OpenTSDB tag key, or an OpenTSDB tag value\n */\n public static String getOpenTsdbSanitizedString(String unsanitizedInput) {\n\n if (unsanitizedInput == null) {\n return null;\n }\n\n StringBuilder sanitizedInput = new StringBuilder();\n \n for (int i = 0; i < unsanitizedInput.length(); i++) {\n char character = unsanitizedInput.charAt(i);\n \n if (Character.isLetterOrDigit(character)) {\n sanitizedInput.append(character);\n continue;\n }\n \n if ((character == '-') || (character == '_') || (character == '.') || (character == '/')) {\n sanitizedInput.append(character);\n continue;\n }\n }\n\n return sanitizedInput.toString();\n }\n\n @Override\n public String toString() { \n return getOpenTsdbTelnetFormatString(false) + \" @ \" + metricReceivedTimestampInMilliseconds_;\n }\n\n @Override\n public String getGraphiteFormatString(boolean sanitizeMetric, boolean substituteCharacters) {\n StringBuilder stringBuilder = new StringBuilder();\n \n String metricPath = GraphiteMetric.getGraphiteSanitizedString(getMetric(), sanitizeMetric, substituteCharacters);\n \n stringBuilder.append(metricPath).append(\" \").append(getMetricValueString()).append(\" \").append(getMetricTimestampInSeconds());\n \n return stringBuilder.toString();\n }\n \n @Override\n public String getOpenTsdbTelnetFormatString(boolean sanitizeMetric) {\n return getOpenTsdbTelnetFormatString(sanitizeMetric, null, null);\n }\n \n @Override\n public String getOpenTsdbTelnetFormatString(boolean sanitizeMetric, String defaultOpenTsdbTagKey, String defaultOpenTsdbTagValue) {\n StringBuilder stringBuilder = new StringBuilder();\n \n String metric = sanitizeMetric ? getOpenTsdbSanitizedString(getMetric()) : getMetric();\n \n stringBuilder.append(metric).append(\" \").append(metricTimestamp_).append(\" \").append(getMetricValueString()).append(\" \");\n\n List<OpenTsdbTag> openTsdbTags = getMetricTagsFromMetricKey();\n if ((openTsdbTags != null) && (defaultOpenTsdbTagKey != null)) openTsdbTags.add(new OpenTsdbTag(defaultOpenTsdbTagKey + \"=\" + defaultOpenTsdbTagValue));\n \n if (openTsdbTags != null) {\n for (int i = 0; i < openTsdbTags.size(); i++) {\n String tagKey = sanitizeMetric ? getOpenTsdbSanitizedString(openTsdbTags.get(i).getTagKey()) : openTsdbTags.get(i).getTagKey();\n String tagValue = sanitizeMetric ? getOpenTsdbSanitizedString(openTsdbTags.get(i).getTagValue()) : openTsdbTags.get(i).getTagValue();\n\n stringBuilder.append(tagKey).append('=').append(tagValue);\n if ((i + 1) != openTsdbTags.size()) stringBuilder.append(\" \");\n }\n }\n \n return stringBuilder.toString();\n }\n \n @Override\n public String getOpenTsdbJsonFormatString(boolean sanitizeMetric) {\n return getOpenTsdbJsonFormatString(sanitizeMetric, null, null);\n }\n \n @Override\n public String getOpenTsdbJsonFormatString(boolean sanitizeMetric, String defaultOpenTsdbTagKey, String defaultOpenTsdbTagValue) {\n \n String metric = sanitizeMetric ? getOpenTsdbSanitizedString(getMetric()) : getMetric();\n List<OpenTsdbTag> openTsdbTags = getMetricTagsFromMetricKey();\n if ((openTsdbTags != null) && (defaultOpenTsdbTagKey != null)) openTsdbTags.add(new OpenTsdbTag(defaultOpenTsdbTagKey + \"=\" + defaultOpenTsdbTagValue));\n\n if ((metric == null) || metric.isEmpty()) return null;\n if (metricTimestamp_ < 0) return null;\n if ((getMetricValue() == null)) return null;\n \n StringBuilder openTsdbJson = new StringBuilder();\n\n openTsdbJson.append(\"{\");\n\n openTsdbJson.append(\"\\\"metric\\\":\\\"\").append(StringEscapeUtils.escapeJson(metric)).append(\"\\\",\");\n openTsdbJson.append(\"\\\"timestamp\\\":\").append(metricTimestamp_).append(\",\");\n openTsdbJson.append(\"\\\"value\\\":\").append(getMetricValueString()).append(\",\");\n\n openTsdbJson.append(\"\\\"tags\\\":{\");\n\n if (openTsdbTags != null) {\n for (int j = 0; j < openTsdbTags.size(); j++) {\n OpenTsdbTag tag = openTsdbTags.get(j);\n \n if (sanitizeMetric) {\n openTsdbJson.append(\"\\\"\").append(StringEscapeUtils.escapeJson(getOpenTsdbSanitizedString(tag.getTagKey())));\n openTsdbJson.append(\"\\\":\\\"\").append(StringEscapeUtils.escapeJson(getOpenTsdbSanitizedString(tag.getTagValue()))).append(\"\\\"\");\n }\n else {\n openTsdbJson.append(\"\\\"\").append(StringEscapeUtils.escapeJson(tag.getTagKey()));\n openTsdbJson.append(\"\\\":\\\"\").append(StringEscapeUtils.escapeJson(tag.getTagValue())).append(\"\\\"\");\n }\n \n if ((j + 1) != openTsdbTags.size()) openTsdbJson.append(\",\");\n }\n }\n \n openTsdbJson.append(\"}\");\n\n openTsdbJson.append(\"}\");\n \n return openTsdbJson.toString();\n }\n \n @Override\n public String getInfluxdbV1JsonFormatString() {\n\n String metric = getMetric();\n List<OpenTsdbTag> openTsdbTags = getMetricTagsFromMetricKey();\n\n if ((metric == null) || metric.isEmpty()) return null;\n if (metricTimestamp_ < 0) return null;\n if ((getMetricValue() == null)) return null;\n\n StringBuilder influxdbJson = new StringBuilder();\n\n influxdbJson.append(\"{\");\n\n // the metric name, with the prefix already built-in\n influxdbJson.append(\"\\\"name\\\":\\\"\");\n influxdbJson.append(StringEscapeUtils.escapeJson(metric)).append(\"\\\",\");\n\n // column order: value, time, tag(s)\n influxdbJson.append(\"\\\"columns\\\":[\\\"value\\\",\\\"time\\\"\");\n\n if (openTsdbTags != null && !openTsdbTags.isEmpty()) {\n influxdbJson.append(\",\");\n \n for (int j = 0; j < openTsdbTags.size(); j++) {\n OpenTsdbTag tag = openTsdbTags.get(j);\n influxdbJson.append(\"\\\"\").append(StringEscapeUtils.escapeJson(tag.getTagKey())).append(\"\\\"\");\n if ((j + 1) != openTsdbTags.size()) influxdbJson.append(\",\");\n }\n }\n\n influxdbJson.append(\"],\");\n \n // only include one point in the points array. note-- timestamp will always be sent to influxdb in milliseconds\n influxdbJson.append(\"\\\"points\\\":[[\");\n influxdbJson.append(getMetricValueString()).append(\",\");\n influxdbJson.append(getMetricTimestampInMilliseconds());\n \n if ((openTsdbTags != null) && !openTsdbTags.isEmpty()) {\n influxdbJson.append(\",\");\n \n for (int j = 0; j < openTsdbTags.size(); j++) {\n OpenTsdbTag tag = openTsdbTags.get(j);\n influxdbJson.append(\"\\\"\").append(StringEscapeUtils.escapeJson(tag.getTagValue())).append(\"\\\"\");\n if ((j + 1) != openTsdbTags.size()) influxdbJson.append(\",\");\n }\n }\n \n influxdbJson.append(\"]]}\");\n\n return influxdbJson.toString();\n }\n \n public static String getOpenTsdbJson(List<? extends OpenTsdbMetricFormat> openTsdbFormatMetrics, boolean sanitizeMetrics) {\n return getOpenTsdbJson(openTsdbFormatMetrics, sanitizeMetrics, null, null);\n }\n \n public static String getOpenTsdbJson(List<? extends OpenTsdbMetricFormat> openTsdbFormatMetrics, boolean sanitizeMetrics, String defaultOpenTsdbTagKey, String defaultOpenTsdbTagValue) {\n \n if (openTsdbFormatMetrics == null) return null;\n\n StringBuilder openTsdbJson = new StringBuilder();\n \n openTsdbJson.append(\"[\");\n \n for (int i = 0; i < openTsdbFormatMetrics.size(); i++) {\n OpenTsdbMetricFormat openTsdbMetric = openTsdbFormatMetrics.get(i);\n String openTsdbJsonString = openTsdbMetric.getOpenTsdbJsonFormatString(sanitizeMetrics, defaultOpenTsdbTagKey, defaultOpenTsdbTagValue);\n \n if (openTsdbJsonString != null) {\n openTsdbJson.append(openTsdbJsonString);\n if ((i + 1) != openTsdbFormatMetrics.size()) openTsdbJson.append(\",\");\n }\n }\n \n openTsdbJson.append(\"]\");\n \n return openTsdbJson.toString();\n }\n \n public static OpenTsdbMetric parseOpenTsdbTelnetMetric(String unparsedMetric, String metricPrefix, long metricReceivedTimestampInMilliseconds) {\n \n if (unparsedMetric == null) {\n return null;\n }\n \n try {\n int metricIndexRange = unparsedMetric.indexOf(' ', 0);\n String metric = null;\n if (metricIndexRange > 0) {\n if ((metricPrefix != null) && !metricPrefix.isEmpty()) metric = metricPrefix + unparsedMetric.substring(0, metricIndexRange);\n else metric = unparsedMetric.substring(0, metricIndexRange);\n }\n\n int metricTimestampIndexRange = unparsedMetric.indexOf(' ', metricIndexRange + 1);\n String metricTimestampString = null;\n long metricTimestamp = -1;\n Boolean isTimestampInMilliseconds = null;\n if (metricTimestampIndexRange > 0) {\n metricTimestampString = unparsedMetric.substring(metricIndexRange + 1, metricTimestampIndexRange);\n metricTimestamp = Long.parseLong(metricTimestampString);\n if (metricTimestampString.length() == 13) isTimestampInMilliseconds = true;\n else if (metricTimestampString.length() <= 10) isTimestampInMilliseconds = false;\n }\n\n int metricValueIndexRange = unparsedMetric.indexOf(' ', metricTimestampIndexRange + 1);\n \n BigDecimal metricValueBigDecimal = null;\n if (metricValueIndexRange > 0) {\n String metricValueString = unparsedMetric.substring(metricTimestampIndexRange + 1, metricValueIndexRange);\n \n if (metricValueString.length() > 100) {\n logger.debug(\"Metric parse error. Metric value can't be more than 100 characters long. Metric value was \\\"\" + metricValueString.length() + \"\\\" characters long.\");\n }\n else {\n metricValueBigDecimal = new BigDecimal(metricValueString);\n }\n }\n \n List<OpenTsdbTag> openTsdbTags = OpenTsdbTag.parseTags(unparsedMetric, metricValueIndexRange);\n \n if ((metric == null) || metric.isEmpty() || \n (metricValueBigDecimal == null) ||\n (metricTimestampString == null) || (metricTimestamp == -1) || \n (openTsdbTags == null) || (openTsdbTags.isEmpty()) || \n (isTimestampInMilliseconds == null) || ((metricTimestampString.length() != 10) && (metricTimestampString.length() != 13))) {\n logger.warn(\"Metric parse error: \\\"\" + unparsedMetric + \"\\\"\");\n return null;\n }\n else {\n OpenTsdbMetric openTsdbMetric = new OpenTsdbMetric(metric, metricTimestamp, metricValueBigDecimal, openTsdbTags, \n isTimestampInMilliseconds, metricReceivedTimestampInMilliseconds); \n \n if ((openTsdbMetric.getMetricKey() != null) && (openTsdbMetric.getMetricTimestampInMilliseconds() > -1)) return openTsdbMetric;\n else return null;\n }\n }\n catch (NumberFormatException e) {\n logger.error(\"Error on \" + unparsedMetric + System.lineSeparator() + e.toString() + System.lineSeparator()); \n return null;\n }\n catch (Exception e) {\n logger.error(\"Error on \" + unparsedMetric + System.lineSeparator() + e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e)); \n return null;\n }\n }\n \n public static ArrayList getSortedUnparsedTags(List<OpenTsdbTag> openTsdbTags) {\n \n ArrayList<String> sortedUnparsedTags = new ArrayList<>();\n \n if ((openTsdbTags == null) || openTsdbTags.isEmpty()) {\n sortedUnparsedTags.trimToSize();\n return sortedUnparsedTags;\n }\n \n for (OpenTsdbTag openTsdbTag : openTsdbTags) {\n String tag = openTsdbTag.getTag();\n if (tag != null) sortedUnparsedTags.add(tag);\n }\n \n Collections.sort(sortedUnparsedTags);\n sortedUnparsedTags.trimToSize();\n \n return sortedUnparsedTags;\n }\n \n public static List<OpenTsdbMetric> parseOpenTsdbJson(String inputJson, String metricPrefix, long metricsReceivedTimestampInMilliseconds) {\n return parseOpenTsdbJson(inputJson, metricPrefix, metricsReceivedTimestampInMilliseconds, new ArrayList<Integer>());\n }\n \n /* successCountAndFailCount is modified by this method. index-0 will have the successfully parsed metric count, and index-1 will have the metrics with errors count */\n public static List<OpenTsdbMetric> parseOpenTsdbJson(String inputJson, String metricPrefix, long metricsReceivedTimestampInMilliseconds, List<Integer> successCountAndFailCount) {\n\n if ((inputJson == null) || inputJson.isEmpty()) {\n return new ArrayList<>();\n }\n\n int successMetricCount = 0, errorMetricCount = 0;\n List<OpenTsdbMetric> openTsdbMetrics = new ArrayList<>();\n JsonElement jsonElement = null;\n JsonArray jsonArray = null;\n\n try {\n JsonParser parser = new JsonParser();\n jsonElement = parser.parse(inputJson);\n \n if (!jsonElement.isJsonArray()) {\n jsonArray = new JsonArray();\n jsonArray.add(jsonElement);\n }\n else {\n jsonArray = jsonElement.getAsJsonArray();\n }\n }\n catch (Exception e) {\n logger.warn(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n \n if (jsonArray == null) return openTsdbMetrics;\n \n for (int i = 0; i < jsonArray.size(); i++) {\n JsonElement jsonElementOfArray = null;\n\n try {\n jsonElementOfArray = jsonArray.get(i);\n JsonObject jsonObject_TopLevel = jsonElementOfArray.getAsJsonObject();\n \n String metric = parseOpenTsdbJson_ValidateAndReturn_Metric(jsonObject_TopLevel);\n if (metric == null) continue;\n if ((metricPrefix != null) && !metricPrefix.isEmpty()) metric = metricPrefix + metric;\n \n OpenTsdbTimestamp openTsdbTimestamp = parseOpenTsdbJson_ValidateAndReturn_MetricTimestamp(jsonObject_TopLevel);\n if (openTsdbTimestamp == null) continue;\n \n BigDecimal metricValue = parseOpenTsdbJson_ValidateAndReturn_MetricValue(jsonObject_TopLevel);\n if (metricValue == null) continue;\n \n List<OpenTsdbTag> openTsdbTags = parseOpenTsdbJson_ValidateAndReturn_Tags(jsonObject_TopLevel);\n if ((openTsdbTags == null) || openTsdbTags.isEmpty()) continue;\n \n OpenTsdbMetric openTsdbMetric = new OpenTsdbMetric(metric, openTsdbTimestamp.getTimestampLong(), metricValue, openTsdbTags, \n openTsdbTimestamp.isMilliseconds(), metricsReceivedTimestampInMilliseconds); \n\n if ((openTsdbMetric.getMetricKey() != null) && (openTsdbMetric.getMetricTimestampInMilliseconds() > -1)) openTsdbMetrics.add(openTsdbMetric);\n }\n catch (Exception e) {\n if (jsonElementOfArray != null) {\n try {\n logger.warn(\"Metric parse error: \" + jsonElementOfArray.getAsString());\n }\n catch (Exception e2) {\n logger.warn(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n }\n else {\n logger.warn(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n }\n }\n\n successMetricCount = openTsdbMetrics.size();\n errorMetricCount = jsonArray.size() - successMetricCount;\n if (successCountAndFailCount == null) successCountAndFailCount = new ArrayList<>();\n if (!successCountAndFailCount.isEmpty()) successCountAndFailCount.clear();\n successCountAndFailCount.add(successMetricCount);\n successCountAndFailCount.add(errorMetricCount);\n\n return openTsdbMetrics;\n }\n\n protected static String parseOpenTsdbJson_ValidateAndReturn_Metric(JsonObject jsonObject) {\n \n try {\n String metric = jsonObject.getAsJsonPrimitive(\"metric\").getAsString();\n \n if ((metric == null) || metric.isEmpty()) {\n logger.warn(\"Metric parse error. Invalid metric name/path: \\\"\" + jsonObject.toString());\n return null;\n }\n \n return metric;\n }\n catch (Exception e) { \n try {\n logger.warn(\"Metric parse error. Invalid metric name/path: \\\"\" + jsonObject.toString());\n }\n catch (Exception e2) {\n logger.warn(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n \n return null;\n }\n \n }\n\n protected static OpenTsdbTimestamp parseOpenTsdbJson_ValidateAndReturn_MetricTimestamp(JsonObject jsonObject) {\n \n try {\n long metricTimestamp = jsonObject.getAsJsonPrimitive(\"timestamp\").getAsLong();\n \n if (metricTimestamp < 0) {\n logger.warn(\"Metric parse error. Invalid metric timestamp: \\\"\" + jsonObject.toString());\n return null;\n }\n \n String metricTimestampString = Long.toString(metricTimestamp); \n \n if ((metricTimestamp <= 2147483647l) && (metricTimestampString.length() <= 10)) {\n return new OpenTsdbTimestamp(metricTimestamp, false);\n }\n else if (metricTimestampString.length() == 13) {\n return new OpenTsdbTimestamp(metricTimestamp, true);\n }\n else {\n logger.warn(\"Metric parse error. Invalid metric timestamp: \\\"\" + jsonObject.toString());\n return null;\n }\n }\n catch (Exception e) { \n try {\n logger.warn(\"Metric parse error. Invalid metric timestamp: \\\"\" + jsonObject.toString());\n }\n catch (Exception e2) {\n logger.warn(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n \n return null;\n }\n \n }\n \n protected static BigDecimal parseOpenTsdbJson_ValidateAndReturn_MetricValue(JsonObject jsonObject) {\n \n try {\n String numericString = jsonObject.getAsJsonPrimitive(\"value\").getAsString();\n \n if (numericString.length() > 100) {\n logger.debug(\"Metric parse error. Metric value can't be more than 100 characters long. Metric value was \\\"\" + numericString.length() + \"\\\" characters long.\");\n return null;\n }\n \n BigDecimal metricValue = new BigDecimal(numericString);\n\n return metricValue;\n }\n catch (Exception e) { \n try {\n logger.warn(\"Metric parse error. Invalid metric value: \\\"\" + jsonObject.toString());\n }\n catch (Exception e2) {\n logger.warn(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n \n return null;\n }\n \n }\n \n protected static List<OpenTsdbTag> parseOpenTsdbJson_ValidateAndReturn_Tags(JsonObject jsonObject) {\n \n List<OpenTsdbTag> openTsdbTags = new ArrayList<>();\n \n try {\n JsonObject JsonObject_Tags = jsonObject.getAsJsonObject(\"tags\");\n\n try {\n for (Map.Entry<String,JsonElement> tagsObject_Entry : JsonObject_Tags.entrySet()) {\n String tagKey = tagsObject_Entry.getKey();\n String tagValue = tagsObject_Entry.getValue().getAsString();\n\n if ((tagKey != null) && (tagValue != null) && !tagKey.isEmpty() && !tagValue.isEmpty()) {\n OpenTsdbTag openTsdbTag = new OpenTsdbTag(tagKey + \"=\" + tagValue);\n openTsdbTags.add(openTsdbTag);\n }\n else {\n logger.warn(\"Metric parse error. Invalid metric tag: \\\"\" + jsonObject.toString());\n }\n }\n }\n catch (Exception e) { \n logger.warn(\"Metric parse error. Invalid metric tag: \\\"\" + jsonObject.toString());\n }\n }\n catch (Exception e) { \n logger.warn(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n \n if (openTsdbTags.isEmpty()) {\n logger.warn(\"Metric parse error. At least 1 valid tag required: \\\"\" + jsonObject.toString());\n }\n \n return openTsdbTags;\n }\n \n public static List<OpenTsdbMetric> parseOpenTsdbTelnetMetrics(String unparsedMetrics, String metricPrefix, long metricReceivedTimestampInMilliseconds) {\n \n if ((unparsedMetrics == null) || unparsedMetrics.isEmpty()) {\n return new ArrayList<>();\n }\n \n List<OpenTsdbMetric> openTsdbMetrics = new ArrayList();\n \n try {\n int currentIndex = 0;\n int newLineLocation = 0;\n\n while(newLineLocation != -1) {\n newLineLocation = unparsedMetrics.indexOf('\\n', currentIndex);\n\n String unparsedMetric;\n\n if (newLineLocation == -1) {\n unparsedMetric = unparsedMetrics.substring(currentIndex, unparsedMetrics.length());\n }\n else {\n unparsedMetric = unparsedMetrics.substring(currentIndex, newLineLocation);\n currentIndex = newLineLocation + 1;\n }\n\n if ((unparsedMetric != null) && !unparsedMetric.isEmpty()) {\n OpenTsdbMetric openTsdbMetric = OpenTsdbMetric.parseOpenTsdbTelnetMetric(unparsedMetric.trim(), metricPrefix, metricReceivedTimestampInMilliseconds);\n if (openTsdbMetric != null) openTsdbMetrics.add(openTsdbMetric);\n }\n }\n }\n catch (Exception e) {\n logger.warn(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n \n return openTsdbMetrics;\n }\n \n public long getHashKey() {\n return this.hashKey_;\n }\n \n @Override\n public long getMetricHashKey() {\n return getHashKey();\n }\n \n public void setHashKey(long hashKey) {\n this.hashKey_ = hashKey;\n }\n \n @Override\n public void setMetricHashKey(long hashKey) {\n setHashKey(hashKey);\n }\n \n @Override\n public String getMetricKey() {\n return metricKey_;\n }\n \n public String getMetric() {\n return getMetricFromMetricKey();\n }\n \n public int getMetricLength() {\n return metricLength_;\n }\n \n public long getMetricTimestamp() {\n return metricTimestamp_;\n }\n \n @Override\n public int getMetricTimestampInSeconds() {\n if (!isTimestampInMilliseconds_) return (int) metricTimestamp_;\n else return (int) (metricTimestamp_ / 1000);\n }\n \n @Override\n public long getMetricTimestampInMilliseconds() {\n if (isTimestampInMilliseconds_) return metricTimestamp_;\n else return (metricTimestamp_ * 1000);\n }\n \n public BigDecimal getMetricValue() {\n return metricValue_;\n }\n \n @Override\n public String getMetricValueString() {\n if (metricValue_ == null) return null;\n return MathUtilities.getFastPlainStringWithNoTrailingZeros(metricValue_);\n }\n \n @Override\n public BigDecimal getMetricValueBigDecimal() {\n return metricValue_;\n }\n\n public List<OpenTsdbTag> getTags() {\n return getMetricTagsFromMetricKey();\n }\n \n public boolean isTimestampInMilliseconds() {\n return isTimestampInMilliseconds_;\n }\n \n @Override\n public long getMetricReceivedTimestampInMilliseconds() {\n return metricReceivedTimestampInMilliseconds_;\n }\n\n}",
"public class StackTrace {\n \n private static final Logger logger = LoggerFactory.getLogger(StackTrace.class.getName());\n \n public static String getStringFromStackTrace(Exception exception) {\n try {\n StringWriter stringWriter = new StringWriter();\n PrintWriter printWriter = new PrintWriter(stringWriter);\n \n exception.printStackTrace(printWriter);\n \n return stringWriter.toString();\n }\n catch (Exception e) {\n logger.error(e.toString() + \" - Failed to convert stack-trace to string\");\n return null;\n }\n }\n \n public static String getStringFromStackTrace(StackTraceElement[] stackTraceElements) {\n try {\n \n StringBuilder stackTrace = new StringBuilder();\n \n for (StackTraceElement stackTraceElement : stackTraceElements) {\n stackTrace.append(stackTraceElement).append(System.lineSeparator());\n }\n \n return stackTrace.toString();\n }\n catch (Exception e) {\n logger.error(e.toString() + \" - Failed to convert stack-trace to string\");\n return null;\n }\n }\n \n}",
"public class Threads {\n \n private static final Logger logger = LoggerFactory.getLogger(Threads.class.getName());\n \n public static void sleepMilliseconds(long milliseconds) {\n sleepMilliseconds(milliseconds, false);\n }\n \n public static void sleepMilliseconds(long milliseconds, boolean logSleepTime) {\n \n if (milliseconds <= 0) {\n return;\n }\n \n try {\n if (logSleepTime) {\n logger.debug(\"Sleeping for \" + milliseconds + \" milliseconds\");\n }\n \n Thread.sleep(milliseconds);\n }\n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n }\n \n public static void sleepSeconds(int seconds) {\n sleepSeconds(seconds, false);\n }\n \n public static void sleepSeconds(int seconds, boolean logSleepTime) {\n \n if (seconds <= 0) {\n return;\n }\n \n try {\n if (logSleepTime) {\n logger.debug(\"Sleeping for \" + seconds + \" seconds\");\n }\n \n Thread.sleep((long) (seconds * 1000));\n }\n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n }\n \n public static void sleepSeconds(double seconds) {\n sleepSeconds(seconds, false);\n }\n \n public static void sleepSeconds(double seconds, boolean logSleepTime) {\n \n if (seconds <= 0) {\n return;\n }\n \n try {\n if (logSleepTime) {\n logger.debug(\"Sleeping for \" + seconds + \" seconds\");\n }\n \n Thread.sleep((long) (seconds * 1000));\n }\n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n }\n \n public static void sleepMinutes(int minutes) {\n sleepMinutes(minutes, false);\n }\n \n public static void sleepMinutes(int minutes, boolean logSleepTime) {\n \n if (minutes <= 0) {\n return;\n }\n \n try {\n if (logSleepTime) {\n logger.debug(\"Sleeping for \" + minutes + \" minutes\");\n }\n \n Thread.sleep((long) (60 * minutes * 1000));\n }\n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n }\n \n public static void sleepMinutes(double minutes) {\n sleepMinutes(minutes, false);\n }\n \n public static void sleepMinutes(double minutes, boolean logSleepTime) {\n \n if (minutes <= 0) {\n return;\n }\n \n try {\n if (logSleepTime) {\n logger.debug(\"Sleeping for \" + minutes + \" minutes\");\n }\n \n Thread.sleep((long) (60 * minutes * 1000));\n }\n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n }\n \n public static void threadExecutorFixedPool(List threads, int nThreadPoolSize, long timeoutTime, TimeUnit timeoutTimeunit) {\n \n if ((threads == null) || threads.isEmpty() ||(nThreadPoolSize <= 0) || (timeoutTime <= 0) || (timeoutTimeunit == null)) {\n return;\n }\n \n try {\n ExecutorService threadExecutor = Executors.newFixedThreadPool(nThreadPoolSize);\n for (Object thread : threads) {\n threadExecutor.execute((Runnable) thread);\n }\n\n threadExecutor.shutdown();\n boolean didFinishWithoutTimeout = threadExecutor.awaitTermination(timeoutTime, timeoutTimeunit);\n \n if (!didFinishWithoutTimeout) {\n try {\n threadExecutor.shutdownNow();\n }\n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n \n try {\n threadExecutor.awaitTermination(timeoutTime, timeoutTimeunit);\n }\n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n }\n }\n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n\n }\n \n public static void threadExecutorCachedPool(List threads, long timeoutTime, TimeUnit timeoutTimeunit) {\n \n if ((threads == null) || threads.isEmpty() || (timeoutTime <= 0) || (timeoutTimeunit == null)) {\n return;\n }\n \n try {\n ExecutorService threadExecutor = Executors.newCachedThreadPool();\n \n for (Object thread : threads) {\n threadExecutor.execute((Runnable) thread);\n }\n\n threadExecutor.shutdown();\n boolean didFinishWithoutTimeout = threadExecutor.awaitTermination(timeoutTime, timeoutTimeunit);\n \n if (!didFinishWithoutTimeout) {\n try {\n threadExecutor.shutdownNow();\n }\n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n \n try {\n threadExecutor.awaitTermination(timeoutTime, timeoutTimeunit);\n }\n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n }\n }\n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n\n }\n \n public static void shutdownThreadExecutor(ExecutorService threadExecutor, Long timeoutTime, TimeUnit timeoutTimeunit, \n boolean forceShutdownIfTimeoutReached, boolean waitForeverForForceShutdownToFinish) {\n\n if (threadExecutor == null) {\n logger.error(\"ThreadExecutor cannot be null\");\n return;\n }\n \n if ((timeoutTime == null) || (timeoutTime <= 0)) {\n logger.error(\"TimeoutTime cannot be null or less than 0\");\n return;\n }\n \n if (timeoutTimeunit == null) {\n logger.error(\"Timeout-Timeunit cannot be null\");\n return;\n }\n\n boolean didFinishWithoutTimeout = false;\n \n try {\n threadExecutor.shutdown();\n didFinishWithoutTimeout = threadExecutor.awaitTermination(timeoutTime, timeoutTimeunit);\n }\n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n \n if (forceShutdownIfTimeoutReached) {\n try {\n if (!didFinishWithoutTimeout) {\n try {\n threadExecutor.shutdownNow();\n }\n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n } \n }\n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n\n if (waitForeverForForceShutdownToFinish) {\n try {\n threadExecutor.awaitTermination(99999999, TimeUnit.DAYS);\n }\n catch (Exception e) {\n logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n }\n }\n }\n \n}",
"public class FileIo {\n\n private static final Logger logger = LoggerFactory.getLogger(FileIo.class.getName());\n \n /**\n * Creates a directory. \n * @return Returns false if unsuccessful or if an exception was encountered. Returns true if the directory was successfully created.\n */\n public static boolean createDirectory(String parentPath, String directoryName) {\n \n if ((parentPath == null) || parentPath.isEmpty() || (directoryName == null) || directoryName.isEmpty()) {\n return false;\n }\n\n try {\n File directory = new File(parentPath + File.separator + directoryName);\n boolean doesDirectoryExist = directory.exists();\n\n boolean createDirectorySuccess = true;\n if (!doesDirectoryExist) {\n createDirectorySuccess = directory.mkdir();\n }\n\n return createDirectorySuccess;\n }\n catch (Exception e) {\n logger.debug(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n return false;\n }\n }\n\n /**\n * This is a quiet method.\n */ \n public static boolean deleteFile(String filePath, String filename) {\n \n if ((filePath == null) || filePath.isEmpty() || (filename == null) || filename.isEmpty()) {\n return false;\n }\n \n return deleteFile(filePath + File.separator + filename);\n }\n \n /**\n * This is a quiet method.\n */\n public static boolean deleteFile(String filePathAndName) {\n \n if ((filePathAndName == null) || filePathAndName.isEmpty()) {\n return false;\n }\n \n boolean isSuccessfulDelete = false;\n\n try {\n File fileToDelete = new File(filePathAndName);\n isSuccessfulDelete = fileToDelete.delete();\n }\n catch (Exception e) {\n logger.debug(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n isSuccessfulDelete = false;\n }\n \n return isSuccessfulDelete;\n }\n \n /**\n * This is a quiet method.\n */\n public static boolean deleteFilesInADirectory(String directoryPath) {\n \n if ((directoryPath == null) || directoryPath.isEmpty()) {\n return false;\n }\n \n boolean isSuccessfulDelete = true;\n\n List<File> files = getListOfFilesInADirectory(directoryPath);\n \n if (files == null) {\n return false;\n }\n \n try {\n for (File file : files) {\n boolean fileDeleteSuccess = deleteFile(directoryPath, file.getName());\n\n if (!fileDeleteSuccess) {\n isSuccessfulDelete = false;\n }\n }\n }\n catch (Exception e) {\n logger.debug(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n isSuccessfulDelete = false;\n }\n \n return isSuccessfulDelete;\n }\n \n /**\n * This is a quiet method.\n * Only deletes files. Doesn't delete directories.\n */\n public static boolean deleteDirectoryFiles(Set<String> inputFilePathsAndNames) {\n \n if ((inputFilePathsAndNames == null)) {\n return false;\n }\n\n boolean didSuccessfullyDeleteAllFiles = true; \n \n try {\n for (String filePathAndName : inputFilePathsAndNames) {\n File file = new File(filePathAndName);\n\n if (!file.isDirectory()) {\n boolean deleteSuccess = deleteFile(filePathAndName);\n\n if (!deleteSuccess) {\n logger.debug(\"Warning - \" + filePathAndName + \" failed to delete\");\n didSuccessfullyDeleteAllFiles = false;\n }\n }\n }\n }\n catch (Exception e) {\n logger.debug(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n return false;\n }\n \n return didSuccessfullyDeleteAllFiles;\n }\n \n /**\n * This is a quiet method.\n * Only deletes directories. Will fail if the directories have files in them.\n */\n public static boolean deleteDirectorySubdirectories(String rootDirectory) {\n \n if ((rootDirectory == null)) {\n return false;\n }\n\n boolean didSuccessfullyDeleteAllDirectories = true; \n \n try {\n List<File> files = getListOfFilesInADirectory(rootDirectory);\n\n for (File file : files) {\n if (file.isDirectory()) {\n boolean deleteSuccess = deleteDirectoryAndContents(file);\n\n if (!deleteSuccess) {\n logger.debug(\"Warning - failed to delete \" + file.getAbsolutePath());\n didSuccessfullyDeleteAllDirectories = false;\n }\n }\n }\n }\n catch (Exception e) {\n logger.debug(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n return false;\n }\n \n return didSuccessfullyDeleteAllDirectories;\n }\n \n /**\n * This is a quiet method.\n * Method template code from http://www.exampledepot.com/egs/java.io/DeleteDir.html\n */\n public static boolean deleteDirectoryAndContents(File rootDirectory) {\n \n if ((rootDirectory == null) || !rootDirectory.isDirectory()) {\n return false;\n } \n \n try {\n String[] directoryContents = rootDirectory.list();\n for (int i = 0; i < directoryContents.length; i++) {\n boolean success = deleteDirectoryAndContents(new File(rootDirectory, directoryContents[i]));\n\n if (!success) {\n return false;\n }\n }\n \n return rootDirectory.delete();\n }\n catch (Exception e) {\n logger.debug(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n return false;\n }\n }\n \n /**\n * This is a quiet method.\n */\n public static boolean doesFileExist(String filePathAndName) {\n \n if ((filePathAndName == null) || filePathAndName.isEmpty()) {\n return false;\n }\n\n File file = new File(filePathAndName);\n \n boolean doesFileExist;\n \n try {\n doesFileExist = file.exists();\n }\n catch (Exception e) {\n logger.debug(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n doesFileExist = false;\n }\n\n return doesFileExist;\n }\n \n /**\n * This is a quiet method.\n */\n public static boolean doesFileExist(File file) {\n \n if (file == null) {\n return false;\n }\n \n boolean doesFileExist;\n \n try {\n doesFileExist = file.exists();\n }\n catch (Exception e) {\n logger.debug(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n doesFileExist = false;\n }\n\n return doesFileExist;\n }\n \n /**\n * This is a quiet method.\n */\n public static boolean doesFileExist(String filePath, String filename) {\n if ((filePath == null) || filePath.isEmpty() || (filename == null) || filename.isEmpty()) {\n return false;\n }\n \n return doesFileExist(filePath + File.separator + filename);\n }\n \n public static long getFileLastModified(String filePathAndName) {\n File file = new File(filePathAndName);\n long lastModified = file.lastModified();\n\n return lastModified;\n }\n \n /**\n * This is a quiet method.\n */\n public static boolean renameFile(String filePath, String oldFilename, String newFilename) {\n \n if ((filePath == null) || filePath.isEmpty() ||\n (oldFilename == null) || oldFilename.isEmpty() || \n (newFilename == null) || newFilename.isEmpty()) {\n return false;\n }\n \n File oldFile = new File(filePath + File.separator + oldFilename);\n File newFile = new File(filePath + File.separator + newFilename);\n\n boolean isSuccessfulRename;\n \n try {\n isSuccessfulRename = oldFile.renameTo(newFile);\n }\n catch (Exception e) {\n logger.debug(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n isSuccessfulRename = false;\n }\n \n return isSuccessfulRename;\n }\n\n public static boolean copyFile(String sourceFilePath, String sourceFilename, String destinationFilePath, String destinationFilename) {\n \n if ((sourceFilePath == null) || sourceFilePath.isEmpty() ||\n (sourceFilename == null) || sourceFilename.isEmpty() || \n (destinationFilePath == null) || destinationFilePath.isEmpty() ||\n (destinationFilename == null) || destinationFilename.isEmpty()) {\n return false;\n }\n\n boolean isCopySuccess = false;\n \n FileChannel sourceFileChannel = null;\n FileChannel destinationFileChannel = null;\n\n try {\n File sourceFile = new File(sourceFilePath + File.separator + sourceFilename);\n File destinationFile = new File(destinationFilePath + File.separator + destinationFilename);\n\n if (sourceFile.exists()) {\n\n if (!destinationFile.exists()) {\n destinationFile.createNewFile();\n }\n\n sourceFileChannel = new FileInputStream(sourceFile).getChannel();\n destinationFileChannel = new FileOutputStream(destinationFile).getChannel();\n\n destinationFileChannel.transferFrom(sourceFileChannel, 0, sourceFileChannel.size());\n \n isCopySuccess = true;\n }\n }\n catch (Exception e) {\n logger.debug(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n finally {\n if (sourceFileChannel != null) {\n try {\n sourceFileChannel.close();\n }\n catch (Exception e) {\n logger.debug(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n }\n \n if (destinationFileChannel != null) {\n try {\n destinationFileChannel.close();\n }\n catch (Exception e) {\n logger.debug(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n }\n \n return isCopySuccess;\n }\n }\n \n /**\n * This is a quiet method.\n */\n public static List<String> getListOfDirectoryNamesInADirectory(String directoryPath) {\n \n if ((directoryPath == null) || directoryPath.isEmpty()) {\n return new ArrayList<>();\n }\n\n File directory = new File(directoryPath);\n String[] filenames;\n \n try {\n filenames = directory.list();\n }\n catch (Exception e) {\n logger.debug(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n return new ArrayList<>();\n }\n \n List<String> directoryNamesList = new ArrayList<>();\n \n if (filenames != null) {\n for (int i = 0; i < filenames.length; i++) {\n try {\n File file = new File(directoryPath + File.separator + filenames[i]);\n\n if (file.isDirectory()) {\n directoryNamesList.add(file.getName());\n }\n }\n catch (Exception e) {\n logger.debug(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n }\n }\n \n return directoryNamesList;\n }\n \n /**\n * This is a quiet method.\n */\n public static List<File> getListOfDirectoryFilesInADirectory(String directoryPath) {\n \n if ((directoryPath == null) || directoryPath.isEmpty()) {\n return new ArrayList<>();\n }\n\n File directory = new File(directoryPath);\n String[] filenames;\n \n try {\n filenames = directory.list();\n }\n catch (Exception e) {\n logger.debug(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n return new ArrayList<>();\n }\n \n List<File> directoryFilesList = new ArrayList<>();\n \n if (filenames != null) {\n for (int i = 0; i < filenames.length; i++) {\n try {\n File file = new File(directoryPath + File.separator + filenames[i]);\n \n if (file.isDirectory()) {\n directoryFilesList.add(file);\n }\n }\n catch (Exception e) {\n logger.debug(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n }\n }\n \n return directoryFilesList;\n }\n \n /**\n * This is a quiet method.\n */\n public static List<String> getListOfFilenamesInADirectory(String directoryPath) {\n \n if ((directoryPath == null) || directoryPath.isEmpty()) {\n return new ArrayList<>();\n }\n\n File directory = new File(directoryPath);\n String[] filenames;\n \n try {\n filenames = directory.list();\n }\n catch (Exception e) {\n logger.debug(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n return new ArrayList<>();\n }\n \n List<String> filenamesList = new ArrayList<>();\n \n for (int i = 0; i < filenames.length; i++) {\n filenamesList.add(filenames[i]);\n }\n \n return filenamesList;\n }\n \n /**\n * This is a quiet method.\n */\n public static List<File> getListOfFilesInADirectory(String directoryPath) {\n \n if ((directoryPath == null) || directoryPath.isEmpty()) {\n return new ArrayList<>();\n }\n \n List<File> files = new ArrayList<>();\n \n File directory = new File(directoryPath);\n String[] filenames;\n \n try {\n filenames = directory.list();\n }\n catch (Exception e) {\n logger.debug(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n return new ArrayList<>();\n }\n \n if (filenames != null) {\n for (int i = 0; i < filenames.length; i++) {\n try {\n File file = new File(directoryPath + File.separator + filenames[i]);\n\n if (file.exists()) {\n files.add(file);\n }\n }\n catch (Exception e) {\n logger.debug(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n }\n }\n \n return files;\n }\n \n /**\n * This is a quiet method.\n */\n public static List<File> getListOfFilesInADirectory(String directoryPath, List<String> filenames) {\n \n if ((directoryPath == null) || directoryPath.isEmpty() || (filenames == null) || filenames.isEmpty()) {\n return new ArrayList<>();\n }\n \n List<File> files = new ArrayList<>();\n \n for (int i = 0; i < filenames.size(); i++) {\n try {\n File file = new File(directoryPath + File.separator + filenames.get(i));\n\n if (file.exists()) {\n files.add(file);\n }\n }\n catch (Exception e) {\n logger.debug(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n }\n \n return files;\n }\n \n public static String getFileExtensionFromFilename(String filename) {\n \n if ((filename == null) || filename.isEmpty()) {\n return null;\n }\n \n int indexOfBeginExtension = filename.lastIndexOf('.');\n\n if ((indexOfBeginExtension != -1) && ((indexOfBeginExtension + 1) != filename.length())) {\n String fileExtension = filename.substring(indexOfBeginExtension + 1, filename.length());\n return fileExtension;\n }\n else {\n return null;\n }\n }\n \n public static String getFilenameWithoutExtension(String filename) {\n \n if ((filename == null) || filename.isEmpty()) {\n return null;\n }\n \n int indexOfBeginExtension = filename.lastIndexOf('.');\n\n if ((indexOfBeginExtension != -1) && ((indexOfBeginExtension + 1) != filename.length())) {\n String filenameWithoutExtension = filename.substring(0, indexOfBeginExtension);\n return filenameWithoutExtension;\n }\n else {\n return null;\n }\n }\n \n /**\n * This is a quiet method.\n */\n public static boolean saveStringToFile(String saveFilePath, String saveFilename, String saveString) {\n return saveStringToFile(saveFilePath + File.separator + saveFilename, saveString);\n }\n \n /**\n * This is a quiet method.\n */\n public static boolean saveStringToFile(String saveFilePathAndName, String saveString) {\n \n if ((saveFilePathAndName == null) || saveFilePathAndName.isEmpty() ||\n (saveString == null) || saveString.isEmpty()) {\n return false;\n }\n \n BufferedWriter writer = null;\n \n try { \n File outputFile = new File(saveFilePathAndName); \n writer = new BufferedWriter(new FileWriter(outputFile));\n \n writer.write(saveString);\n \n return true;\n }\n catch (Exception e) {\n logger.debug(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n return false;\n }\n finally {\n try {\n if (writer != null) {\n writer.close();\n }\n }\n catch (Exception e){\n logger.debug(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n }\n }\n \n public static String readFileToString(String filePath, String filename) {\n String filePathAndName = filePath + File.separator + filename;\n return readFileToString(filePathAndName);\n }\n \n public static String readFileToString(String filePathAndName) {\n \n if ((filePathAndName == null) || (filePathAndName.length() == 0)) {\n return null;\n }\n \n File file;\n \n try {\n file = new File(filePathAndName);\n }\n catch (Exception e) {\n logger.debug(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n return null;\n }\n \n return readFileToString(file);\n }\n \n /**\n * This is a quiet method.\n */\n public static String readFileToString(File file) {\n \n if (file == null) {\n return null;\n }\n \n BufferedReader reader = null;\n \n try {\n reader = new BufferedReader(new FileReader(file));\n \n StringBuilder fileContents = new StringBuilder(\"\");\n boolean isFirstLine = true;\n \n String currentLine = reader.readLine();\n while (currentLine != null) {\n if (isFirstLine) isFirstLine = false;\n else fileContents.append(System.lineSeparator());\n \n fileContents.append(currentLine);\n currentLine = reader.readLine();\n } \n \n return fileContents.toString();\n }\n catch (Exception e) {\n logger.debug(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n return null;\n }\n finally {\n try {\n if (reader != null) {\n reader.close();\n }\n }\n catch (Exception e) {\n logger.debug(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));\n }\n }\n }\n\n public static String readFileToString(File file, int numRetries, int timeBetweenRetriesInMilliseconds) {\n \n if ((file == null) || (numRetries < 0) || (timeBetweenRetriesInMilliseconds < 0)) {\n return null;\n }\n \n String fileContents = null;\n \n for (int i = 0; (i <= numRetries) && (fileContents == null); i++) {\n fileContents = readFileToString(file);\n\n if (fileContents == null) {\n Threads.sleepMilliseconds(timeBetweenRetriesInMilliseconds);\n }\n }\n \n return fileContents;\n }\n \n}"
] | import com.pearson.statspoller.globals.ApplicationConfiguration;
import com.pearson.statspoller.globals.GlobalVariables;
import java.util.List;
import com.pearson.statspoller.metric_formats.graphite.GraphiteMetric;
import com.pearson.statspoller.metric_formats.opentsdb.OpenTsdbMetric;
import com.pearson.statspoller.utilities.core_utils.StackTrace;
import com.pearson.statspoller.utilities.core_utils.Threads;
import com.pearson.statspoller.utilities.file_utils.FileIo;
import java.util.ArrayList;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | package com.pearson.statspoller.internal_metric_collectors;
/**
* @author Jeffrey Schmidt
*/
public abstract class InternalCollectorFramework {
private static final Logger logger = LoggerFactory.getLogger(InternalCollectorFramework.class.getName());
protected final int NUM_FILE_WRITE_RETRIES = 3;
protected final int DELAY_BETWEEN_WRITE_RETRIES_IN_MS = 100;
private final boolean isEnabled_;
private final long collectionInterval_;
private final String internalCollectorMetricPrefix_;
private final String outputFilePathAndFilename_;
private final boolean writeOutputFiles_;
private final String linuxProcFileSystemLocation_ = removeTrailingSlash(ApplicationConfiguration.getLinuxProcLocation());
private final String linuxSysFileSystemLocation_ = removeTrailingSlash(ApplicationConfiguration.getLinuxSysLocation());
private String fullInternalCollectorMetricPrefix_ = null;
private String finalOutputFilePathAndFilename_ = null;
public InternalCollectorFramework(boolean isEnabled, long collectionInterval, String internalCollectorMetricPrefix,
String outputFilePathAndFilename, boolean writeOutputFiles) {
this.isEnabled_ = isEnabled;
this.collectionInterval_ = collectionInterval;
this.internalCollectorMetricPrefix_ = internalCollectorMetricPrefix;
this.outputFilePathAndFilename_ = outputFilePathAndFilename;
this.writeOutputFiles_ = writeOutputFiles;
createFullInternalCollectorMetricPrefix();
this.finalOutputFilePathAndFilename_ = this.outputFilePathAndFilename_;
}
public void outputGraphiteMetrics(List<GraphiteMetric> graphiteMetrics) {
if (graphiteMetrics == null) return;
for (GraphiteMetric graphiteMetric : graphiteMetrics) {
try {
if (graphiteMetric == null) continue;
String graphiteMetricPathWithPrefix = fullInternalCollectorMetricPrefix_ + graphiteMetric.getMetricPath();
GraphiteMetric outputGraphiteMetric = new GraphiteMetric(graphiteMetricPathWithPrefix, graphiteMetric.getMetricValue(), graphiteMetric.getMetricTimestampInSeconds());
outputGraphiteMetric.setHashKey(GlobalVariables.metricHashKeyGenerator.incrementAndGet());
GlobalVariables.graphiteMetrics.put(outputGraphiteMetric.getHashKey(), outputGraphiteMetric);
}
catch (Exception e) {
logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
}
}
if (writeOutputFiles_) {
String outputString = buildGraphiteMetricsFile(graphiteMetrics, true, fullInternalCollectorMetricPrefix_);
writeGraphiteMetricsToFile(outputString);
}
}
public void outputOpentsdbMetricsAsGraphiteMetrics(List<OpenTsdbMetric> openTsdbMetrics) {
if (openTsdbMetrics == null) return;
for (OpenTsdbMetric openTsdbMetric : openTsdbMetrics) {
try {
if (openTsdbMetric == null) continue;
String metricNameWithPrefix = fullInternalCollectorMetricPrefix_ + openTsdbMetric.getMetric();
GraphiteMetric outputGraphiteMetric = new GraphiteMetric(metricNameWithPrefix, openTsdbMetric.getMetricValue(), openTsdbMetric.getMetricTimestampInSeconds());
outputGraphiteMetric.setHashKey(GlobalVariables.metricHashKeyGenerator.incrementAndGet());
GlobalVariables.graphiteMetrics.put(outputGraphiteMetric.getHashKey(), outputGraphiteMetric);
}
catch (Exception e) {
logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
}
}
if (writeOutputFiles_) {
List<GraphiteMetric> graphiteMetrics = new ArrayList<>();
for (OpenTsdbMetric openTsdbMetric : openTsdbMetrics) {
try {
if (openTsdbMetric == null) continue;
GraphiteMetric graphiteMetric = new GraphiteMetric(openTsdbMetric.getMetric(), openTsdbMetric.getMetricValue(), openTsdbMetric.getMetricTimestampInSeconds());
graphiteMetrics.add(graphiteMetric);
}
catch (Exception e) {
logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
}
}
String outputString = buildGraphiteMetricsFile(graphiteMetrics, true, fullInternalCollectorMetricPrefix_);
writeGraphiteMetricsToFile(outputString);
}
}
public void outputOpenTsdbMetrics(List<OpenTsdbMetric> openTsdbMetrics) {
if (openTsdbMetrics == null) return;
for (OpenTsdbMetric openTsdbMetric : openTsdbMetrics) {
try {
if (openTsdbMetric == null) continue;
String metricNameWithPrefix = fullInternalCollectorMetricPrefix_ + openTsdbMetric.getMetric();
OpenTsdbMetric outputOpenTsdbMetric = new OpenTsdbMetric(metricNameWithPrefix, openTsdbMetric.getMetricTimestampInMilliseconds(),
openTsdbMetric.getMetricValue(), openTsdbMetric.getTags());
outputOpenTsdbMetric.setHashKey(GlobalVariables.metricHashKeyGenerator.incrementAndGet());
GlobalVariables.openTsdbMetrics.put(outputOpenTsdbMetric.getHashKey(), outputOpenTsdbMetric);
}
catch (Exception e) {
logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
}
}
if (writeOutputFiles_) {
String outputString = buildOpenTsdbMetricsFile(openTsdbMetrics, true, fullInternalCollectorMetricPrefix_);
writeGraphiteMetricsToFile(outputString);
}
}
private void writeGraphiteMetricsToFile(String output) {
if ((output == null) || output.isEmpty()) {
return;
}
boolean isSuccessfulWrite;
try {
for (int i = 0; i <= NUM_FILE_WRITE_RETRIES; i++) {
isSuccessfulWrite = FileIo.saveStringToFile(finalOutputFilePathAndFilename_, output);
if (isSuccessfulWrite) break; | else Threads.sleepMilliseconds(DELAY_BETWEEN_WRITE_RETRIES_IN_MS); | 5 |
Terracotta-OSS/offheap-store | src/test/java/org/terracotta/offheapstore/paging/EvictionRefusalStealingIT.java | [
"public class UpfrontAllocatingPageSource implements PageSource {\n\n public static final String ALLOCATION_LOG_LOCATION = UpfrontAllocatingPageSource.class.getName() + \".allocationDump\";\n\n private static final Logger LOGGER = LoggerFactory.getLogger(UpfrontAllocatingPageSource.class);\n private static final double PROGRESS_LOGGING_STEP_SIZE = 0.1;\n private static final long PROGRESS_LOGGING_THRESHOLD = MemoryUnit.GIGABYTES.toBytes(4L);\n\n private static final Comparator<Page> REGION_COMPARATOR = (a, b) -> {\n if (a.address() == b.address()) {\n return a.size() - b.size();\n } else {\n return a.address() - b.address();\n }\n };\n\n private final SortedMap<Long, Runnable> risingThresholds = new TreeMap<>();\n private final SortedMap<Long, Runnable> fallingThresholds = new TreeMap<>();\n\n private final List<PowerOfTwoAllocator> sliceAllocators = new ArrayList<>();\n private final List<PowerOfTwoAllocator> victimAllocators = new ArrayList<>();\n\n private final List<ByteBuffer> buffers = new ArrayList<>();\n\n /*\n * TODO : currently the TreeSet along with the comparator above works for the\n * subSet queries due to the alignment properties of the region allocation\n * being used here. I more flexible implementation might involve switching\n * to using an AATreeSet subclass - that would also require me to finish\n * writing the subSet implementation for that class.\n */\n private final List<NavigableSet<Page>> victims = new ArrayList<>();\n\n private volatile int availableSet = ~0;\n\n /**\n * Create an up-front allocating buffer source of {@code toAllocate} total bytes, in\n * {@code chunkSize} byte chunks.\n *\n * @param source source from which initial buffers will be allocated\n * @param toAllocate total space to allocate in bytes\n * @param chunkSize chunkSize size to allocate in bytes\n */\n public UpfrontAllocatingPageSource(BufferSource source, long toAllocate, int chunkSize) {\n this(source, toAllocate, chunkSize, -1, true);\n }\n\n /**\n * Create an up-front allocating buffer source of {@code toAllocate} total bytes, in\n * maximally sized chunks, within the given bounds.\n *\n * @param source source from which initial buffers will be allocated\n * @param toAllocate total space to allocate in bytes\n * @param maxChunk the largest chunk size in bytes\n * @param minChunk the smallest chunk size in bytes\n */\n public UpfrontAllocatingPageSource(BufferSource source, long toAllocate, int maxChunk, int minChunk) {\n this(source, toAllocate, maxChunk, minChunk, false);\n }\n\n /**\n * Create an up-front allocating buffer source of {@code toAllocate} total bytes, in\n * maximally sized chunks, within the given bounds.\n * <p>\n * By default we try to allocate chunks of {@code maxChunk} size. However, unless {@code fixed} is true, in case of\n * allocation failure, we will try to allocate half-smaller chunks. We do not allocate chunks smaller than {@code minChunk}\n * though.\n *\n * @param source source from which initial buffers will be allocated\n * @param toAllocate total space to allocate in bytes\n * @param maxChunk the largest chunk size in bytes\n * @param minChunk the smallest chunk size in bytes\n * @param fixed if the chunks should all be of size {@code maxChunk} or can be smaller\n */\n private UpfrontAllocatingPageSource(BufferSource source, long toAllocate, int maxChunk, int minChunk, boolean fixed) {\n Long totalPhysical = PhysicalMemory.totalPhysicalMemory();\n Long freePhysical = PhysicalMemory.freePhysicalMemory();\n if (totalPhysical != null && toAllocate > totalPhysical) {\n throw new IllegalArgumentException(\"Attempting to allocate \" + DebuggingUtils.toBase2SuffixedString(toAllocate) + \"B of memory \"\n + \"when the host only contains \" + DebuggingUtils.toBase2SuffixedString(totalPhysical) + \"B of physical memory\");\n }\n if (freePhysical != null && toAllocate > freePhysical) {\n LOGGER.warn(\"Attempting to allocate {}B of offheap when there is only {}B of free physical memory - some paging will therefore occur.\",\n DebuggingUtils.toBase2SuffixedString(toAllocate), DebuggingUtils.toBase2SuffixedString(freePhysical));\n }\n\n if(LOGGER.isInfoEnabled()) {\n LOGGER.info(\"Allocating {}B in chunks\", DebuggingUtils.toBase2SuffixedString(toAllocate));\n }\n\n for (ByteBuffer buffer : allocateBackingBuffers(source, toAllocate, maxChunk, minChunk, fixed)) {\n sliceAllocators.add(new PowerOfTwoAllocator(buffer.capacity()));\n victimAllocators.add(new PowerOfTwoAllocator(buffer.capacity()));\n victims.add(new TreeSet<>(REGION_COMPARATOR));\n buffers.add(buffer);\n }\n }\n\n /**\n * Return the total allocated capacity, used or not\n *\n * @return the total capacity\n */\n public long getCapacity() {\n long capacity = 0;\n for(ByteBuffer buffer : buffers) {\n capacity += buffer.capacity();\n }\n return capacity;\n }\n\n /**\n * Allocates a byte buffer of at least the given size.\n * <p>\n * This {@code BufferSource} is limited to allocating regions that are a power\n * of two in size. Supplied sizes are therefore rounded up to the next\n * largest power of two.\n *\n * @return a buffer of at least the given size\n */\n @Override\n public Page allocate(int size, boolean thief, boolean victim, OffHeapStorageArea owner) {\n if (thief) {\n return allocateAsThief(size, victim, owner);\n } else {\n return allocateFromFree(size, victim, owner);\n }\n }\n\n private Page allocateAsThief(final int size, boolean victim, OffHeapStorageArea owner) {\n Page free = allocateFromFree(size, victim, owner);\n\n if (free != null) {\n return free;\n }\n\n //do thieving here...\n PowerOfTwoAllocator victimAllocator = null;\n PowerOfTwoAllocator sliceAllocator = null;\n List<Page> targets = Collections.emptyList();\n Collection<AllocatedRegion> tempHolds = new ArrayList<>();\n Map<OffHeapStorageArea, Collection<Page>> releases = new IdentityHashMap<>();\n\n synchronized (this) {\n for (int i = 0; i < victimAllocators.size(); i++) {\n int address = victimAllocators.get(i).find(size, victim ? CEILING : FLOOR);\n if (address >= 0) {\n victimAllocator = victimAllocators.get(i);\n sliceAllocator = sliceAllocators.get(i);\n targets = findVictimPages(i, address, size);\n\n //need to claim everything that falls within the range of our allocation\n int claimAddress = address;\n for (Page p : targets) {\n victimAllocator.claim(p.address(), p.size());\n int claimSize = p.address() - claimAddress;\n if (claimSize > 0) {\n tempHolds.add(new AllocatedRegion(claimAddress, claimSize));\n sliceAllocator.claim(claimAddress, claimSize);\n victimAllocator.claim(claimAddress, claimSize);\n }\n claimAddress = p.address() + p.size();\n }\n int claimSize = (address + size) - claimAddress;\n if (claimSize > 0) {\n tempHolds.add(new AllocatedRegion(claimAddress, claimSize));\n sliceAllocator.claim(claimAddress, claimSize);\n victimAllocator.claim(claimAddress, claimSize);\n }\n break;\n }\n }\n\n for (Page p : targets) {\n OffHeapStorageArea a = p.binding();\n Collection<Page> c = releases.get(a);\n if (c == null) {\n c = new LinkedList<>();\n c.add(p);\n releases.put(a, c);\n } else {\n c.add(p);\n }\n }\n }\n\n /*\n * Drop the page source synchronization here to prevent deadlock against\n * map/cache threads.\n */\n Collection<Page> results = new LinkedList<>();\n for (Entry<OffHeapStorageArea, Collection<Page>> e : releases.entrySet()) {\n OffHeapStorageArea a = e.getKey();\n Collection<Page> p = e.getValue();\n results.addAll(a.release(p));\n }\n\n List<Page> failedReleases = new ArrayList<>();\n synchronized (this) {\n for (AllocatedRegion r : tempHolds) {\n sliceAllocator.free(r.address, r.size);\n victimAllocator.free(r.address, r.size);\n }\n\n if (results.size() == targets.size()) {\n for (Page p : targets) {\n victimAllocator.free(p.address(), p.size());\n free(p);\n }\n return allocateFromFree(size, victim, owner);\n } else {\n for (Page p : targets) {\n if (results.contains(p)) {\n victimAllocator.free(p.address(), p.size());\n free(p);\n } else {\n failedReleases.add(p);\n }\n }\n }\n }\n\n try {\n return allocateAsThief(size, victim, owner);\n } finally {\n synchronized (this) {\n for (Page p : failedReleases) {\n //this is just an ugly way of doing an identity equals based contains\n if (victims.get(p.index()).floor(p) == p) {\n victimAllocator.free(p.address(), p.size());\n }\n }\n }\n }\n }\n\n private List<Page> findVictimPages(int chunk, int address, int size) {\n return new ArrayList<>(victims.get(chunk).subSet(new Page(null, -1, address, null),\n new Page(null, -1, address + size, null)));\n }\n\n private Page allocateFromFree(int size, boolean victim, OffHeapStorageArea owner) {\n if (Integer.bitCount(size) != 1) {\n int rounded = Integer.highestOneBit(size) << 1;\n LOGGER.debug(\"Request to allocate {}B will allocate {}B\", size, DebuggingUtils.toBase2SuffixedString(rounded));\n size = rounded;\n }\n\n if (isUnavailable(size)) {\n return null;\n }\n\n synchronized (this) {\n for (int i = 0; i < sliceAllocators.size(); i++) {\n int address = sliceAllocators.get(i).allocate(size, victim ? CEILING : FLOOR);\n if (address >= 0) {\n if (LOGGER.isDebugEnabled()) {\n LOGGER.debug(\"Allocating a {}B buffer from chunk {} &{}\", DebuggingUtils.toBase2SuffixedString(size), i, address);\n }\n ByteBuffer b = ((ByteBuffer) buffers.get(i).limit(address + size).position(address)).slice();\n Page p = new Page(b, i, address, owner);\n if (victim) {\n victims.get(i).add(p);\n } else {\n victimAllocators.get(i).claim(address, size);\n }\n if (!risingThresholds.isEmpty()) {\n long allocated = getAllocatedSize();\n fireThresholds(allocated - size, allocated);\n }\n return p;\n }\n }\n markUnavailable(size);\n return null;\n }\n }\n\n /**\n * Frees the supplied buffer.\n * <p>\n * If the given buffer was not allocated by this source or has already been\n * freed then an {@code AssertionError} is thrown.\n */\n @Override\n public synchronized void free(Page page) {\n if (page.isFreeable()) {\n if (LOGGER.isDebugEnabled()) {\n LOGGER.debug(\"Freeing a {}B buffer from chunk {} &{}\", DebuggingUtils.toBase2SuffixedString(page.size()), page.index(), page.address());\n }\n markAllAvailable();\n sliceAllocators.get(page.index()).free(page.address(), page.size());\n victims.get(page.index()).remove(page);\n victimAllocators.get(page.index()).tryFree(page.address(), page.size());\n if (!fallingThresholds.isEmpty()) {\n long allocated = getAllocatedSize();\n fireThresholds(allocated + page.size(), allocated);\n }\n }\n }\n\n public synchronized long getAllocatedSize() {\n long sum = 0;\n for (PowerOfTwoAllocator a : sliceAllocators) {\n sum += a.occupied();\n }\n return sum;\n }\n\n public long getAllocatedSizeUnSync() {\n long sum = 0;\n for (PowerOfTwoAllocator a : sliceAllocators) {\n sum += a.occupied();\n }\n return sum;\n }\n\n private boolean isUnavailable(int size) {\n return (availableSet & size) == 0;\n }\n\n private synchronized void markAllAvailable() {\n availableSet = ~0;\n }\n\n private synchronized void markUnavailable(int size) {\n availableSet &= ~size;\n }\n\n @Override\n public synchronized String toString() {\n StringBuilder sb = new StringBuilder(\"UpfrontAllocatingPageSource\");\n for (int i = 0; i < buffers.size(); i++) {\n sb.append(\"\\nChunk \").append(i + 1).append('\\n');\n sb.append(\"Size : \").append(DebuggingUtils.toBase2SuffixedString(buffers.get(i).capacity())).append(\"B\\n\");\n sb.append(\"Free Allocator : \").append(sliceAllocators.get(i)).append('\\n');\n sb.append(\"Victim Allocator : \").append(victimAllocators.get(i));\n }\n return sb.toString();\n\n }\n\n private synchronized void fireThresholds(long incoming, long outgoing) {\n Collection<Runnable> thresholds;\n if (outgoing > incoming) {\n thresholds = risingThresholds.subMap(incoming, outgoing).values();\n } else if (outgoing < incoming) {\n thresholds = fallingThresholds.subMap(outgoing, incoming).values();\n } else {\n thresholds = Collections.emptyList();\n }\n\n for (Runnable r : thresholds) {\n try {\n r.run();\n } catch (Throwable t) {\n LOGGER.error(\"Throwable thrown by threshold action\", t);\n }\n }\n }\n\n /**\n * Adds an allocation threshold action.\n * <p>\n * There can be only a single action associated with each unique direction\n * and threshold combination. If an action is already associated with the\n * supplied combination then the action is replaced by the new action and the\n * old action is returned.\n * <p>\n * Actions are fired on passing through the supplied threshold and are called\n * synchronously with the triggering allocation. This means care must be taken\n * to avoid mutating any map that uses this page source from within the action\n * otherwise deadlocks may result. Exceptions thrown by the action will be\n * caught and logged by the page source and will not be propagated on the\n * allocating thread.\n *\n * @param direction new actions direction\n * @param threshold new actions threshold level\n * @param action fired on breaching the threshold\n * @return the replaced action or {@code null} if no action was present.\n */\n public synchronized Runnable addAllocationThreshold(ThresholdDirection direction, long threshold, Runnable action) {\n switch (direction) {\n case RISING:\n return risingThresholds.put(threshold, action);\n case FALLING:\n return fallingThresholds.put(threshold, action);\n }\n throw new AssertionError();\n }\n\n /**\n * Removes an allocation threshold action.\n * <p>\n * Removes the allocation threshold action for the given level and direction.\n *\n * @param direction registered actions direction\n * @param threshold registered actions threshold level\n * @return the removed condition or {@code null} if no action was present.\n */\n public synchronized Runnable removeAllocationThreshold(ThresholdDirection direction, long threshold) {\n switch (direction) {\n case RISING:\n return risingThresholds.remove(threshold);\n case FALLING:\n return fallingThresholds.remove(threshold);\n }\n throw new AssertionError();\n }\n\n /**\n * Allocate multiple buffers to fulfill the requested memory {@code toAllocate}. We first divide {@code toAllocate} in\n * chunks of size {@code maxChunk} and try to allocate them in parallel on all available processors. If one chunk fails to be\n * allocated, we try to allocate two chunks of {@code maxChunk / 2}. If this allocation fails, we continue dividing until\n * we reach of size of {@code minChunk}. If at that moment, the allocation still fails, an {@code IllegalArgumentException}\n * is thrown.\n * <p>\n * When {@code fixed} is requested, we will only allocated buffers of {@code maxChunk} size. If allocation fails, an\n * {@code IllegalArgumentException} is thrown without any division.\n * <p>\n * If the allocation is interrupted, the method will ignore it and continue allocation. It will then return with the\n * interrupt flag is set.\n *\n * @param source source used to allocate memory buffers\n * @param toAllocate total amount of memory to allocate\n * @param maxChunk maximum size of a buffer. This is the targeted size for all buffers if everything goes well\n * @param minChunk minimum buffer size allowed\n * @param fixed if all buffers should have a the same size (except the last one with {@code toAllocate % maxChunk != 0}, if true, {@code minChunk} isn't used\n * @return the list of allocated buffers\n * @throws IllegalArgumentException when we fail to allocate the requested memory\n */\n private static Collection<ByteBuffer> allocateBackingBuffers(final BufferSource source, long toAllocate, int maxChunk, final int minChunk, final boolean fixed) {\n\n final long start = (LOGGER.isDebugEnabled() ? System.nanoTime() : 0);\n\n final PrintStream allocatorLog = createAllocatorLog(toAllocate, maxChunk, minChunk);\n\n final Collection<ByteBuffer> buffers = new ArrayList<>((int) (toAllocate / maxChunk + 10)); // guess the number of buffers and add some padding just in case\n\n try {\n if (allocatorLog != null) {\n allocatorLog.printf(\"timestamp,threadid,duration,size,physfree,totalswap,freeswap,committed%n\");\n }\n\n List<Future<Collection<ByteBuffer>>> futures = new ArrayList<>((int) (toAllocate / maxChunk + 1));\n\n ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());\n try {\n\n for (long dispatched = 0; dispatched < toAllocate; ) {\n final int currentChunkSize = (int)Math.min(maxChunk, toAllocate - dispatched);\n futures.add(executorService.submit(() -> bufferAllocation(source, currentChunkSize, minChunk, fixed, allocatorLog, start)));\n dispatched += currentChunkSize;\n }\n } finally {\n executorService.shutdown();\n }\n\n long allocated = 0;\n long progressStep = Math.max(PROGRESS_LOGGING_THRESHOLD, (long)(toAllocate * PROGRESS_LOGGING_STEP_SIZE));\n long nextProgressLogAt = progressStep;\n\n for (Future<Collection<ByteBuffer>> future : futures) {\n Collection<ByteBuffer> result = uninterruptibleGet(future);\n buffers.addAll(result);\n for(ByteBuffer buffer : result) {\n allocated += buffer.capacity();\n if (allocated > nextProgressLogAt) {\n LOGGER.info(\"Allocation {}% complete\", (100 * allocated) / toAllocate);\n nextProgressLogAt += progressStep;\n }\n }\n }\n\n } finally {\n if (allocatorLog != null) {\n allocatorLog.close();\n }\n }\n\n if(LOGGER.isDebugEnabled()) {\n long duration = System.nanoTime() - start;\n LOGGER.debug(\"Took {} ms to create off-heap storage of {}B.\", TimeUnit.NANOSECONDS.toMillis(duration), DebuggingUtils.toBase2SuffixedString(toAllocate));\n }\n\n return Collections.unmodifiableCollection(buffers);\n }\n\n private static Collection<ByteBuffer> bufferAllocation(BufferSource source, int toAllocate, int minChunk, boolean fixed, PrintStream allocatorLog, long start) {\n long allocated = 0;\n long currentChunkSize = toAllocate;\n\n Collection<ByteBuffer> buffers = new ArrayList<>();\n\n while (allocated < toAllocate) {\n long blockStart = System.nanoTime();\n int currentAllocation = (int)Math.min(currentChunkSize, (toAllocate - allocated));\n ByteBuffer b = source.allocateBuffer(currentAllocation);\n long blockDuration = System.nanoTime() - blockStart;\n\n if (b == null) {\n if (fixed || (currentChunkSize >>> 1) < minChunk) {\n throw new IllegalArgumentException(\"An attempt was made to allocate more off-heap memory than the JVM can allow.\" +\n \" The limit on off-heap memory size is given by the -XX:MaxDirectMemorySize command (or equivalent).\");\n }\n\n // In case of failure, we try half the allocation size. It might pass if memory fragmentation caused the failure\n currentChunkSize >>>= 1;\n\n if(LOGGER.isDebugEnabled()) {\n LOGGER.debug(\"Allocated failed at {}B, trying {}B chunks.\", DebuggingUtils.toBase2SuffixedString(currentAllocation), DebuggingUtils.toBase2SuffixedString(currentChunkSize));\n }\n } else {\n buffers.add(b);\n allocated += currentAllocation;\n\n if (allocatorLog != null) {\n allocatorLog.printf(\"%d,%d,%d,%d,%d,%d,%d,%d%n\", System.nanoTime() - start,\n Thread.currentThread().getId(), blockDuration, currentAllocation, PhysicalMemory.freePhysicalMemory(), PhysicalMemory.totalSwapSpace(), PhysicalMemory.freeSwapSpace(), PhysicalMemory.ourCommittedVirtualMemory());\n }\n\n if(LOGGER.isDebugEnabled()) {\n LOGGER.debug(\"{}B chunk allocated\", DebuggingUtils.toBase2SuffixedString(currentAllocation));\n }\n }\n }\n\n return buffers;\n }\n\n private static <T> T uninterruptibleGet(Future<T> future) {\n boolean interrupted = Thread.interrupted();\n try {\n while (true) {\n try {\n return future.get();\n } catch (ExecutionException e) {\n if (e.getCause() instanceof RuntimeException) {\n throw (RuntimeException)e.getCause();\n }\n throw new RuntimeException(e);\n } catch (InterruptedException e) {\n // Remember and keep going\n interrupted = true;\n }\n }\n } finally {\n if(interrupted) {\n Thread.currentThread().interrupt();\n }\n }\n }\n\n private static PrintStream createAllocatorLog(long max, int maxChunk, int minChunk) {\n String path = System.getProperty(ALLOCATION_LOG_LOCATION);\n if (path == null) {\n return null;\n } else {\n PrintStream allocatorLogStream;\n try {\n File allocatorLogFile = File.createTempFile(\"allocation\", \".csv\", new File(path));\n allocatorLogStream = new PrintStream(allocatorLogFile, \"US-ASCII\");\n } catch (IOException e) {\n LOGGER.warn(\"Exception creating allocation log\", e);\n return null;\n }\n allocatorLogStream.printf(\"Timestamp: %s%n\", new Date());\n allocatorLogStream.printf(\"Allocating: %sB%n\",DebuggingUtils.toBase2SuffixedString(max));\n allocatorLogStream.printf(\"Max Chunk: %sB%n\",DebuggingUtils.toBase2SuffixedString(maxChunk));\n allocatorLogStream.printf(\"Min Chunk: %sB%n\",DebuggingUtils.toBase2SuffixedString(minChunk));\n return allocatorLogStream;\n }\n }\n\n public enum ThresholdDirection {\n RISING, FALLING\n }\n\n static class AllocatedRegion {\n\n private final int address;\n private final int size;\n\n AllocatedRegion(int address, int size) {\n this.address = address;\n this.size = size;\n }\n }\n}",
"public class OffHeapHashMap<K, V> extends AbstractMap<K, V> implements MapInternals, StorageEngine.Owner, HashingMap<K, V> {\n\n /*\n * Future design ideas:\n *\n * We might want to look in to reading the whole (or large chunks) of the\n * probe sequence for a key in one shot rather than doing it one by one.\n */\n\n private static final Logger LOGGER = LoggerFactory.getLogger(OffHeapHashMap.class);\n\n private static final int INITIAL_TABLE_SIZE = 128;\n private static final float TABLE_RESIZE_THRESHOLD = 0.5f;\n private static final float TABLE_SHRINK_THRESHOLD = 0.2f;\n private static final int INITIAL_REPROBE_LENGTH = 16;\n private static final int REPROBE_WARNING_THRESHOLD = 1024;\n private static final int ALLOCATE_ON_CLEAR_THRESHOLD_RATIO = 2;\n\n private static final IntBuffer DESTROYED_TABLE = IntBuffer.allocate(0);\n\n /**\n * Size of a table entry in primitive {@code int} units\n */\n protected static final int ENTRY_SIZE = 4;\n protected static final int ENTRY_BIT_SHIFT = Integer.numberOfTrailingZeros(ENTRY_SIZE);\n\n protected static final int STATUS = 0;\n protected static final int KEY_HASHCODE = 1;\n protected static final int ENCODING = 2;\n\n protected static final int STATUS_USED = 1;\n protected static final int STATUS_REMOVED = 2;\n public static final int RESERVED_STATUS_BITS = STATUS_USED | STATUS_REMOVED;\n\n protected final StorageEngine<? super K, ? super V> storageEngine;\n\n protected final PageSource tableSource;\n\n private final WeakIdentityHashMap<IntBuffer, PendingPage> pendingTableFrees = new WeakIdentityHashMap<>(pending -> freeTable(pending.tablePage));\n\n private final int initialTableSize;\n\n private final boolean tableAllocationsSteal;\n\n private final ThreadLocal<Boolean> tableResizing = ThreadLocal.withInitial(() -> Boolean.FALSE);\n\n protected volatile int size;\n\n protected volatile int modCount;\n\n /*\n * The reprobe limit as it currently stands only ever increases. If we change\n * this behavior we will need to make changes to the iterators as they assume\n * this to be true.\n */\n protected int reprobeLimit = INITIAL_REPROBE_LENGTH;\n\n private float currentTableShrinkThreshold = TABLE_SHRINK_THRESHOLD;\n\n private volatile boolean hasUsedIterators;\n\n /**\n * The current hash-table.\n * <p>\n * A list of: {@code int[] {status, hashCode, encoding-high, encoding-low}}\n */\n protected volatile IntBuffer hashtable;\n protected volatile Page hashTablePage;\n\n private Set<Entry<K, V>> entrySet;\n private Set<K> keySet;\n private Set<Long> encodingSet;\n\n /*\n * Statistics support\n */\n protected volatile int removedSlots;\n\n /**\n * Construct an instance using a custom {@link BufferSource} for the\n * hashtable.\n *\n * @param source source for the hashtable allocations\n * @param storageEngine engine used to encode the keys and values\n */\n public OffHeapHashMap(PageSource source, StorageEngine<? super K, ? super V> storageEngine) {\n this(source, storageEngine, INITIAL_TABLE_SIZE);\n }\n\n public OffHeapHashMap(PageSource source, boolean tableAllocationsSteal, StorageEngine<? super K, ? super V> storageEngine) {\n this(source, tableAllocationsSteal, storageEngine, INITIAL_TABLE_SIZE);\n }\n\n public OffHeapHashMap(PageSource source, StorageEngine<? super K, ? super V> storageEngine, boolean bootstrap) {\n this(source, false, storageEngine, INITIAL_TABLE_SIZE, bootstrap);\n }\n\n /**\n * Construct an instance using a custom {@link BufferSource} for the\n * hashtable and a custom initial table size.\n *\n * @param source source for the hashtable allocations\n * @param storageEngine engine used to encode the keys and values\n * @param tableSize the initial table size\n */\n public OffHeapHashMap(PageSource source, StorageEngine<? super K, ? super V> storageEngine, int tableSize) {\n this(source, false, storageEngine, tableSize, true);\n }\n\n public OffHeapHashMap(PageSource source, boolean tableAllocationsSteal, StorageEngine<? super K, ? super V> storageEngine, int tableSize) {\n this(source, tableAllocationsSteal, storageEngine, tableSize, true);\n }\n\n @FindbugsSuppressWarnings(\"ICAST_INTEGER_MULTIPLY_CAST_TO_LONG\")\n protected OffHeapHashMap(PageSource source, boolean tableAllocationsSteal, StorageEngine<? super K, ? super V> storageEngine, int tableSize, boolean bootstrap) {\n if (storageEngine == null) {\n throw new NullPointerException(\"StorageEngine implementation must be non-null\");\n }\n\n this.storageEngine = storageEngine;\n this.tableSource = source;\n this.tableAllocationsSteal = tableAllocationsSteal;\n\n // Find a power of 2 >= initialCapacity\n int capacity = 1;\n while (capacity < tableSize) {\n capacity <<= 1;\n }\n this.initialTableSize = capacity;\n\n if (bootstrap) {\n this.hashTablePage = allocateTable(initialTableSize);\n if (hashTablePage == null) {\n String msg = \"Initial table allocation failed.\\n\" + \"Initial Table Size (slots) : \" + initialTableSize + '\\n' +\n \"Allocation Will Require : \" + DebuggingUtils.toBase2SuffixedString(initialTableSize * ENTRY_SIZE * (Integer.SIZE / Byte.SIZE)) + \"B\\n\" +\n \"Table Page Source : \" + tableSource;\n throw new IllegalArgumentException(msg);\n }\n hashtable = hashTablePage.asIntBuffer();\n }\n this.storageEngine.bind(this);\n }\n\n @Override\n public int size() {\n return size;\n }\n\n @Override\n public boolean containsKey(Object key) {\n int hash = key.hashCode();\n\n if (size == 0) {\n return false;\n }\n\n IntBuffer view = (IntBuffer) hashtable.duplicate().position(indexFor(spread(hash)));\n\n int limit = reprobeLimit();\n\n for (int i = 0; i < limit; i++) {\n if (!view.hasRemaining()) {\n view.rewind();\n }\n\n IntBuffer entry = (IntBuffer) view.slice().limit(ENTRY_SIZE);\n\n if (isTerminating(entry)) {\n return false;\n } else if (isPresent(entry) && keyEquals(key, hash, readLong(entry, ENCODING), entry.get(KEY_HASHCODE))) {\n hit(view.position(), entry);\n return true;\n } else {\n view.position(view.position() + ENTRY_SIZE);\n }\n }\n return false;\n }\n\n @SuppressWarnings(\"unchecked\")\n @Override\n public V get(Object key) {\n int hash = key.hashCode();\n\n if (size == 0) {\n return null;\n }\n\n IntBuffer view = (IntBuffer) hashtable.duplicate().position(indexFor(spread(hash)));\n\n int limit = reprobeLimit();\n\n for (int i = 0; i < limit; i++) {\n if (!view.hasRemaining()) {\n view.rewind();\n }\n\n IntBuffer entry = (IntBuffer) view.slice().limit(ENTRY_SIZE);\n\n if (isTerminating(entry)) {\n return null;\n } else if (isPresent(entry) && keyEquals(key, hash, readLong(entry, ENCODING), entry.get(KEY_HASHCODE))) {\n hit(view.position(), entry);\n return (V) storageEngine.readValue(readLong(entry, ENCODING));\n } else {\n view.position(view.position() + ENTRY_SIZE);\n }\n }\n return null;\n }\n\n @Override\n public Long getEncodingForHashAndBinary(int hash, ByteBuffer binaryKey) {\n if (size == 0) {\n return null;\n }\n\n IntBuffer view = (IntBuffer) hashtable.duplicate().position(indexFor(spread(hash)));\n\n int limit = reprobeLimit();\n\n for (int i = 0; i < limit; i++) {\n if (!view.hasRemaining()) {\n view.rewind();\n }\n\n IntBuffer entry = (IntBuffer) view.slice().limit(ENTRY_SIZE);\n\n if (isTerminating(entry)) {\n return null;\n } else if (isPresent(entry) && binaryKeyEquals(binaryKey, hash, readLong(entry, ENCODING), entry.get(KEY_HASHCODE))) {\n return readLong(entry, ENCODING);\n } else {\n view.position(view.position() + ENTRY_SIZE);\n }\n }\n return null;\n }\n\n @Override\n @FindbugsSuppressWarnings(\"VO_VOLATILE_INCREMENT\")\n public long installMappingForHashAndEncoding(int pojoHash, ByteBuffer offheapBinaryKey, ByteBuffer offheapBinaryValue, int metadata) {\n freePendingTables();\n\n int[] newEntry = installEntry(offheapBinaryKey, pojoHash, offheapBinaryValue, metadata);\n\n int start = indexFor(spread(pojoHash));\n hashtable.position(start);\n\n int limit = reprobeLimit();\n\n for (int i = 0; i < limit; i++) {\n if (!hashtable.hasRemaining()) {\n hashtable.rewind();\n }\n\n IntBuffer entry = (IntBuffer) hashtable.slice().limit(ENTRY_SIZE);\n int entryPosition = hashtable.position();\n\n if (isAvailable(entry)) {\n if (isRemoved(entry)) {\n removedSlots--;\n }\n entry.put(newEntry);\n slotAdded(entryPosition, entry);\n hit(entryPosition, entry);\n return readLong(newEntry, ENCODING);\n } else {\n hashtable.position(hashtable.position() + ENTRY_SIZE);\n }\n }\n\n storageEngine.freeMapping(readLong(newEntry, ENCODING), newEntry[KEY_HASHCODE], false); //XXX: further contemplate the boolean value here\n\n // hit reprobe limit - must rehash\n expand(start, limit);\n\n return installMappingForHashAndEncoding(pojoHash, offheapBinaryKey, offheapBinaryValue, metadata);\n }\n\n public Integer getMetadata(Object key, int mask) {\n int safeMask = mask & ~RESERVED_STATUS_BITS;\n\n freePendingTables();\n\n int hash = key.hashCode();\n\n hashtable.position(indexFor(spread(hash)));\n\n int limit = reprobeLimit();\n\n for (int i = 0; i < limit; i++) {\n if (!hashtable.hasRemaining()) {\n hashtable.rewind();\n }\n\n IntBuffer entry = (IntBuffer) hashtable.slice().limit(ENTRY_SIZE);\n\n long encoding = readLong(entry, ENCODING);\n if (isTerminating(entry)) {\n return null;\n } else if (isPresent(entry) && keyEquals(key, hash, encoding, entry.get(KEY_HASHCODE))) {\n return entry.get(STATUS) & safeMask;\n } else {\n hashtable.position(hashtable.position() + ENTRY_SIZE);\n }\n }\n\n return null;\n }\n\n public Integer getAndSetMetadata(Object key, int mask, int values) {\n int safeMask = mask & ~RESERVED_STATUS_BITS;\n\n freePendingTables();\n\n int hash = key.hashCode();\n\n hashtable.position(indexFor(spread(hash)));\n\n int limit = reprobeLimit();\n\n for (int i = 0; i < limit; i++) {\n if (!hashtable.hasRemaining()) {\n hashtable.rewind();\n }\n\n IntBuffer entry = (IntBuffer) hashtable.slice().limit(ENTRY_SIZE);\n\n long encoding = readLong(entry, ENCODING);\n if (isTerminating(entry)) {\n return null;\n } else if (isPresent(entry) && keyEquals(key, hash, encoding, entry.get(KEY_HASHCODE))) {\n int previous = entry.get(STATUS);\n entry.put(STATUS, (previous & ~safeMask) | (values & safeMask));\n return previous & safeMask;\n } else {\n hashtable.position(hashtable.position() + ENTRY_SIZE);\n }\n }\n\n return null;\n }\n\n public V getValueAndSetMetadata(Object key, int mask, int values) {\n int safeMask = mask & ~RESERVED_STATUS_BITS;\n\n freePendingTables();\n\n int hash = key.hashCode();\n\n hashtable.position(indexFor(spread(hash)));\n\n int limit = reprobeLimit();\n\n for (int i = 0; i < limit; i++) {\n if (!hashtable.hasRemaining()) {\n hashtable.rewind();\n }\n\n IntBuffer entry = (IntBuffer) hashtable.slice().limit(ENTRY_SIZE);\n\n long encoding = readLong(entry, ENCODING);\n if (isTerminating(entry)) {\n return null;\n } else if (isPresent(entry) && keyEquals(key, hash, encoding, entry.get(KEY_HASHCODE))) {\n hit(hashtable.position(), entry);\n entry.put(STATUS, (entry.get(STATUS) & ~safeMask) | (values & safeMask));\n @SuppressWarnings(\"unchecked\")\n V result = (V) storageEngine.readValue(readLong(entry, ENCODING));\n return result;\n } else {\n hashtable.position(hashtable.position() + ENTRY_SIZE);\n }\n }\n\n return null;\n }\n\n @Override\n public V put(K key, V value) {\n return put(key, value, 0);\n }\n\n @SuppressWarnings(\"unchecked\")\n @FindbugsSuppressWarnings(\"VO_VOLATILE_INCREMENT\")\n public V put(K key, V value, int metadata) {\n freePendingTables();\n\n int hash = key.hashCode();\n\n int[] newEntry = writeEntry(key, hash, value, metadata);\n\n int start = indexFor(spread(hash));\n hashtable.position(start);\n\n int limit = reprobeLimit();\n\n for (int i = 0; i < limit; i++) {\n if (!hashtable.hasRemaining()) {\n hashtable.rewind();\n }\n\n IntBuffer entry = (IntBuffer) hashtable.slice().limit(ENTRY_SIZE);\n int entryPosition = hashtable.position();\n\n if (isAvailable(entry)) {\n storageEngine.attachedMapping(readLong(newEntry, ENCODING), hash, metadata);\n storageEngine.invalidateCache();\n int laterEntryPosition = entryPosition;\n for (IntBuffer laterEntry = entry; i < limit; i++) {\n if (isTerminating(laterEntry)) {\n break;\n } else if (isPresent(laterEntry) && keyEquals(key, hash, readLong(laterEntry, ENCODING), laterEntry.get(KEY_HASHCODE))) {\n V old = (V) storageEngine.readValue(readLong(laterEntry, ENCODING));\n storageEngine.freeMapping(readLong(laterEntry, ENCODING), laterEntry.get(KEY_HASHCODE), false);\n long oldEncoding = readLong(laterEntry, ENCODING);\n laterEntry.put(newEntry);\n slotUpdated(laterEntryPosition, (IntBuffer) laterEntry.flip(), oldEncoding);\n hit(laterEntryPosition, laterEntry);\n return old;\n } else {\n hashtable.position(hashtable.position() + ENTRY_SIZE);\n }\n\n if (!hashtable.hasRemaining()) {\n hashtable.rewind();\n }\n\n laterEntry = (IntBuffer) hashtable.slice().limit(ENTRY_SIZE);\n laterEntryPosition = hashtable.position();\n }\n if (isRemoved(entry)) {\n removedSlots--;\n }\n entry.put(newEntry);\n slotAdded(entryPosition, entry);\n hit(entryPosition, entry);\n return null;\n } else if (keyEquals(key, hash, readLong(entry, ENCODING), entry.get(KEY_HASHCODE))) {\n storageEngine.attachedMapping(readLong(newEntry, ENCODING), hash, metadata);\n storageEngine.invalidateCache();\n V old = (V) storageEngine.readValue(readLong(entry, ENCODING));\n storageEngine.freeMapping(readLong(entry, ENCODING), entry.get(KEY_HASHCODE), false);\n long oldEncoding = readLong(entry, ENCODING);\n entry.put(newEntry);\n slotUpdated(entryPosition, (IntBuffer) entry.flip(), oldEncoding);\n hit(entryPosition, entry);\n return old;\n } else {\n hashtable.position(hashtable.position() + ENTRY_SIZE);\n }\n }\n\n storageEngine.freeMapping(readLong(newEntry, ENCODING), newEntry[KEY_HASHCODE], false); //XXX: further contemplate the boolean value here\n\n // hit reprobe limit - must rehash\n expand(start, limit);\n\n return put(key, value, metadata);\n }\n\n /**\n * Associates the specified value with the specified key in this map. If the\n * map does not contain a mapping for the key, the new mapping is only\n * installed if there is room. If the map previously contained a mapping for\n * the key, the old value is replaced by the specified value even if this\n * results in a failure or eviction.\n *\n * @param key key with which the specified value is to be associated\n * @param value value to be associated with the specified key\n * @return the previous value associated with <var>key</var>, or\n * <var>null</var> if there was no mapping for <var>key</var>\n * (irrespective of whether the value was successfully installed).\n */\n public V fill(K key, V value) {\n return fill(key, value, 0);\n }\n\n @FindbugsSuppressWarnings(\"VO_VOLATILE_INCREMENT\")\n public V fill(K key, V value, int metadata) {\n freePendingTables();\n\n int hash = key.hashCode();\n\n int start = indexFor(spread(hash));\n hashtable.position(start);\n\n int limit = reprobeLimit();\n\n for (int i = 0; i < limit; i++) {\n if (!hashtable.hasRemaining()) {\n hashtable.rewind();\n }\n\n IntBuffer entry = (IntBuffer) hashtable.slice().limit(ENTRY_SIZE);\n\n if (isAvailable(entry)) {\n for (IntBuffer laterEntry = entry; i < limit; i++) {\n if (isTerminating(laterEntry)) {\n break;\n } else if (isPresent(laterEntry) && keyEquals(key, hash, readLong(laterEntry, ENCODING), laterEntry.get(KEY_HASHCODE))) {\n return put(key, value, metadata);\n } else {\n hashtable.position(hashtable.position() + ENTRY_SIZE);\n }\n\n if (!hashtable.hasRemaining()) {\n hashtable.rewind();\n }\n\n laterEntry = (IntBuffer) hashtable.slice().limit(ENTRY_SIZE);\n }\n\n int[] newEntry = tryWriteEntry(key, hash, value, metadata);\n if (newEntry == null) {\n return null;\n } else {\n return fill(key, value, hash, newEntry, metadata);\n }\n } else if (keyEquals(key, hash, readLong(entry, ENCODING), entry.get(KEY_HASHCODE))) {\n return put(key, value, metadata);\n } else {\n hashtable.position(hashtable.position() + ENTRY_SIZE);\n }\n }\n\n // hit reprobe limit - must rehash\n if (tryExpandTable()) {\n return fill(key, value, metadata);\n } else {\n return null;\n }\n }\n\n @SuppressWarnings(\"unchecked\")\n @FindbugsSuppressWarnings(\"VO_VOLATILE_INCREMENT\")\n protected final V fill(K key, V value, int hash, int[] newEntry, int metadata) {\n freePendingTables();\n\n int start = indexFor(spread(hash));\n hashtable.position(start);\n\n int limit = reprobeLimit();\n\n for (int i = 0; i < limit; i++) {\n if (!hashtable.hasRemaining()) {\n hashtable.rewind();\n }\n\n IntBuffer entry = (IntBuffer) hashtable.slice().limit(ENTRY_SIZE);\n int entryPosition = hashtable.position();\n\n if (isAvailable(entry)) {\n storageEngine.attachedMapping(readLong(newEntry, ENCODING), hash, metadata);\n storageEngine.invalidateCache();\n int laterEntryPosition = entryPosition;\n for (IntBuffer laterEntry = entry; i < limit; i++) {\n if (isTerminating(laterEntry)) {\n break;\n } else if (isPresent(laterEntry) && keyEquals(key, hash, readLong(laterEntry, ENCODING), laterEntry.get(KEY_HASHCODE))) {\n V old = (V) storageEngine.readValue(readLong(laterEntry, ENCODING));\n storageEngine.freeMapping(readLong(laterEntry, ENCODING), laterEntry.get(KEY_HASHCODE), false);\n long oldEncoding = readLong(laterEntry, ENCODING);\n laterEntry.put(newEntry);\n slotUpdated(laterEntryPosition, (IntBuffer) laterEntry.flip(), oldEncoding);\n hit(laterEntryPosition, laterEntry);\n return old;\n } else {\n hashtable.position(hashtable.position() + ENTRY_SIZE);\n }\n\n if (!hashtable.hasRemaining()) {\n hashtable.rewind();\n }\n\n laterEntry = (IntBuffer) hashtable.slice().limit(ENTRY_SIZE);\n laterEntryPosition = hashtable.position();\n }\n if (isRemoved(entry)) {\n removedSlots--;\n }\n entry.put(newEntry);\n slotAdded(entryPosition, entry);\n hit(entryPosition, entry);\n return null;\n } else if (keyEquals(key, hash, readLong(entry, ENCODING), entry.get(KEY_HASHCODE))) {\n storageEngine.attachedMapping(readLong(newEntry, ENCODING), hash, metadata);\n storageEngine.invalidateCache();\n V old = (V) storageEngine.readValue(readLong(entry, ENCODING));\n storageEngine.freeMapping(readLong(entry, ENCODING), entry.get(KEY_HASHCODE), false);\n long oldEncoding = readLong(entry, ENCODING);\n entry.put(newEntry);\n slotUpdated(entryPosition, (IntBuffer) entry.flip(), oldEncoding);\n hit(entryPosition, entry);\n return old;\n } else {\n hashtable.position(hashtable.position() + ENTRY_SIZE);\n }\n }\n\n storageEngine.freeMapping(readLong(newEntry, ENCODING), newEntry[KEY_HASHCODE], true);\n\n return null;\n }\n\n private int[] writeEntry(K key, int hash, V value, int metadata) {\n /*\n * TODO If we start supporting remapping (compaction) then we'll need to\n * worry about correcting the key representation here if the value write\n * triggers a remapping operation.\n */\n while (true) {\n int[] entry = tryWriteEntry(key, hash, value, metadata);\n if (entry == null) {\n storageEngineFailure(key);\n } else {\n return entry;\n }\n }\n }\n\n @FindbugsSuppressWarnings(\"PZLA_PREFER_ZERO_LENGTH_ARRAYS\")\n private int[] tryWriteEntry(K key, int hash, V value, int metadata) {\n if (hashtable == null) {\n throw new NullPointerException();\n } else if (hashtable == DESTROYED_TABLE) {\n throw new IllegalStateException(\"Offheap map/cache has been destroyed\");\n } else if ((metadata & RESERVED_STATUS_BITS) == 0) {\n Long encoding = storageEngine.writeMapping(key, value, hash, metadata);\n if (encoding == null) {\n return null;\n } else {\n return createEntry(hash, encoding, metadata);\n }\n } else {\n throw new IllegalArgumentException(\"Invalid metadata for key '\" + key + \"' : \" + Integer.toBinaryString(metadata));\n }\n }\n\n private int[] installEntry(ByteBuffer offheapBinaryKey, int pojoHash, ByteBuffer offheapBinaryValue, int metadata) {\n while (true) {\n int [] entry = tryInstallEntry(offheapBinaryKey, pojoHash, offheapBinaryValue, metadata);\n if (entry == null) {\n storageEngineFailure(\"<binary-key>\");\n } else {\n return entry;\n }\n }\n }\n\n @FindbugsSuppressWarnings(\"PZLA_PREFER_ZERO_LENGTH_ARRAYS\")\n private int[] tryInstallEntry(ByteBuffer offheapBinaryKey, int pojoHash, ByteBuffer offheapBinaryValue, int metadata) {\n if (hashtable == null) {\n throw new NullPointerException();\n } else if (hashtable == DESTROYED_TABLE) {\n throw new IllegalStateException(\"Offheap map/cache has been destroyed\");\n } else if ((metadata & RESERVED_STATUS_BITS) == 0) {\n Long encoding = ((BinaryStorageEngine) storageEngine).writeBinaryMapping(offheapBinaryKey, offheapBinaryValue, pojoHash, metadata);\n if (encoding == null) {\n return null;\n } else {\n return createEntry(pojoHash, encoding, metadata);\n }\n } else {\n throw new IllegalArgumentException(\"Invalid metadata for binary key : \" + Integer.toBinaryString(metadata));\n }\n }\n\n private static int[] createEntry(int hash, long encoding, int metadata) {\n return new int[] { STATUS_USED | metadata, hash, (int) (encoding >>> Integer.SIZE), (int) encoding };\n }\n\n @Override\n public V remove(Object key) {\n freePendingTables();\n\n int hash = key.hashCode();\n\n if (size == 0) {\n return null;\n }\n\n hashtable.position(indexFor(spread(hash)));\n\n int limit = reprobeLimit();\n\n for (int i = 0; i < limit; i++) {\n if (!hashtable.hasRemaining()) {\n hashtable.rewind();\n }\n\n IntBuffer entry = (IntBuffer) hashtable.slice().limit(ENTRY_SIZE);\n int entryPosition = hashtable.position();\n\n if (isTerminating(entry)) {\n return null;\n } else if (isPresent(entry) && keyEquals(key, hash, readLong(entry, ENCODING), entry.get(KEY_HASHCODE))) {\n @SuppressWarnings(\"unchecked\")\n V removedValue = (V) storageEngine.readValue(readLong(entry, ENCODING));\n storageEngine.freeMapping(readLong(entry, ENCODING), entry.get(KEY_HASHCODE), true);\n\n /*\n * TODO We might want to track the number of 'removed' slots in the\n * table, and rehash it if we reach some threshold to avoid lookup costs\n * staying artificially high when the table is relatively empty, but full\n * of 'removed' slots. This situation should be relatively rare for\n * normal cache usage - but might be more common for more map like usage\n * patterns.\n *\n * The more severe versions of this pattern are now handled by the table\n * shrinking when the occupation drops below the shrink threshold, as\n * that will rehash the table.\n */\n entry.put(STATUS, STATUS_REMOVED);\n slotRemoved(entryPosition, entry);\n shrink();\n return removedValue;\n } else {\n hashtable.position(hashtable.position() + ENTRY_SIZE);\n }\n }\n\n return null;\n }\n\n @Override\n public Map<K, V> removeAllWithHash(int hash) {\n freePendingTables();\n\n if (size == 0) {\n return Collections.emptyMap();\n }\n\n Map<K, V> removed = new HashMap<>();\n\n hashtable.position(indexFor(spread(hash)));\n\n int limit = reprobeLimit();\n\n for (int i = 0; i < limit; i++) {\n if (!hashtable.hasRemaining()) {\n hashtable.rewind();\n }\n\n IntBuffer entry = (IntBuffer) hashtable.slice().limit(ENTRY_SIZE);\n int entryPosition = hashtable.position();\n\n if (isTerminating(entry)) {\n return removed;\n } else if (isPresent(entry) && hash == entry.get(KEY_HASHCODE)) {\n @SuppressWarnings(\"unchecked\")\n V removedValue = (V) storageEngine.readValue(readLong(entry, ENCODING));\n @SuppressWarnings(\"unchecked\")\n K removedKey = (K) storageEngine.readKey(readLong(entry, ENCODING), hash);\n storageEngine.freeMapping(readLong(entry, ENCODING), entry.get(KEY_HASHCODE), true);\n\n removed.put(removedKey, removedValue);\n\n /*\n * TODO We might want to track the number of 'removed' slots in the\n * table, and rehash it if we reach some threshold to avoid lookup costs\n * staying artificially high when the table is relatively empty, but full\n * of 'removed' slots. This situation should be relatively rare for\n * normal cache usage - but might be more common for more map like usage\n * patterns.\n *\n * The more severe versions of this pattern are now handled by the table\n * shrinking when the occupation drops below the shrink threshold, as\n * that will rehash the table.\n */\n entry.put(STATUS, STATUS_REMOVED);\n slotRemoved(entryPosition, entry);\n }\n hashtable.position(hashtable.position() + ENTRY_SIZE);\n }\n\n shrink();\n return removed;\n }\n\n public boolean removeNoReturn(Object key) {\n freePendingTables();\n\n int hash = key.hashCode();\n\n hashtable.position(indexFor(spread(hash)));\n\n int limit = reprobeLimit();\n\n for (int i = 0; i < limit; i++) {\n if (!hashtable.hasRemaining()) {\n hashtable.rewind();\n }\n\n IntBuffer entry = (IntBuffer) hashtable.slice().limit(ENTRY_SIZE);\n int entryPosition = hashtable.position();\n\n if (isTerminating(entry)) {\n return false;\n } else if (isPresent(entry) && keyEquals(key, hash, readLong(entry, ENCODING), entry.get(KEY_HASHCODE))) {\n storageEngine.freeMapping(readLong(entry, ENCODING), entry.get(KEY_HASHCODE), true);\n\n /*\n * TODO We might want to track the number of 'removed' slots in the\n * table, and rehash it if we reach some threshold to avoid lookup costs\n * staying artificially high when the table is relatively empty, but full\n * of 'removed' slots. This situation should be relatively rare for\n * normal cache usage - but might be more common for more map like usage\n * patterns.\n *\n * The more severe versions of this pattern are now handled by the table\n * shrinking when the occupation drops below the shrink threshold, as\n * that will rehash the table.\n */\n entry.put(STATUS, STATUS_REMOVED);\n slotRemoved(entryPosition, entry);\n shrink();\n return true;\n } else {\n hashtable.position(hashtable.position() + ENTRY_SIZE);\n }\n }\n return false;\n }\n\n @Override\n @FindbugsSuppressWarnings(\"VO_VOLATILE_INCREMENT\")\n public void clear() {\n if (hashtable != DESTROYED_TABLE) {\n freePendingTables();\n\n modCount++;\n removedSlots = 0;\n size = 0;\n storageEngine.clear();\n allocateOrClearTable(initialTableSize);\n }\n }\n\n public void destroy() {\n removedSlots = 0;\n size = 0;\n freeTable(hashTablePage);\n for (Iterator<PendingPage> it = pendingTableFrees.values(); it.hasNext(); freeTable(it.next().tablePage));\n hashTablePage = null;\n hashtable = DESTROYED_TABLE;\n storageEngine.destroy();\n }\n\n private void allocateOrClearTable(int size) {\n int[] zeros = new int[1024 >> 2];\n hashtable.clear();\n while (hashtable.hasRemaining()) {\n if (hashtable.remaining() < zeros.length) {\n hashtable.put(zeros, 0, hashtable.remaining());\n } else {\n hashtable.put(zeros);\n }\n }\n hashtable.clear();\n\n wipePendingTables();\n\n if (hashtable.capacity() > size * ENTRY_SIZE * ALLOCATE_ON_CLEAR_THRESHOLD_RATIO) {\n Page newTablePage = allocateTable(size);\n if (newTablePage != null) {\n freeTable(hashTablePage, hashtable, reprobeLimit());\n hashTablePage = newTablePage;\n hashtable = newTablePage.asIntBuffer();\n }\n }\n }\n\n @Override\n public final Set<Entry<K, V>> entrySet() {\n Set<Entry<K, V>> es = entrySet;\n return es == null ? (entrySet = createEntrySet()) : es;\n }\n\n @Override\n public final Set<Long> encodingSet() {\n Set<Long> es = encodingSet;\n return es == null ? (encodingSet = createEncodingSet()) : es;\n }\n\n @Override\n public final Set<K> keySet() {\n Set<K> ks = keySet;\n return ks == null ? (keySet = createKeySet()) : ks;\n }\n\n protected Set<Entry<K, V>> createEntrySet() {\n return new EntrySet();\n }\n\n protected Set<Long> createEncodingSet() {\n return new EncodingSet();\n }\n\n protected Set<K> createKeySet() {\n return new KeySet();\n }\n\n protected static boolean isPresent(IntBuffer entry) {\n return (entry.get(STATUS) & STATUS_USED) != 0;\n }\n\n protected static boolean isAvailable(IntBuffer entry) {\n return (entry.get(STATUS) & STATUS_USED) == 0;\n }\n\n protected static boolean isTerminating(IntBuffer entry) {\n return isTerminating(entry.get(STATUS));\n }\n\n protected static boolean isTerminating(int entryStatus) {\n return (entryStatus & (STATUS_USED | STATUS_REMOVED)) == 0;\n }\n\n protected static boolean isRemoved(IntBuffer entry) {\n return isRemoved(entry.get(STATUS));\n }\n\n protected static boolean isRemoved(int entryStatus) {\n return (entryStatus & STATUS_REMOVED) != 0;\n }\n\n protected static long readLong(int[] array, int offset) {\n return (((long) array[offset]) << Integer.SIZE) | (0xffffffffL & array[offset + 1]);\n }\n\n protected static long readLong(IntBuffer entry, int offset) {\n return (((long) entry.get(offset)) << Integer.SIZE) | (0xffffffffL & entry.get(offset + 1));\n }\n\n protected int indexFor(int hash) {\n return indexFor(hash, hashtable);\n }\n\n protected static int indexFor(int hash, IntBuffer table) {\n return (hash << ENTRY_BIT_SHIFT) & Math.max(0, table.capacity() - 1);\n }\n\n private boolean keyEquals(Object probeKey, int probeHash, long targetEncoding, int targetHash) {\n return probeHash == targetHash && storageEngine.equalsKey(probeKey, targetEncoding);\n }\n\n private boolean binaryKeyEquals(ByteBuffer binaryProbeKey, int probeHash, long targetEncoding, int targetHash) {\n if (storageEngine instanceof BinaryStorageEngine) {\n return probeHash == targetHash && ((BinaryStorageEngine) storageEngine).equalsBinaryKey(binaryProbeKey, targetEncoding);\n } else {\n throw new UnsupportedOperationException(\"Cannot check binary quality unless configured with a BinaryStorageEngine\");\n }\n }\n\n private void expand(int start, int length) {\n if (!tryExpand()) {\n tableExpansionFailure(start, length);\n }\n }\n\n private boolean tryExpand() {\n if (((float) size) / getTableCapacity() > TABLE_RESIZE_THRESHOLD) {\n return tryExpandTable();\n } else {\n return tryIncreaseReprobe();\n }\n }\n\n private boolean tryExpandTable() {\n if (tableResizing.get()) {\n throw new AssertionError(\"Expand requested in context of an existing resize - this should be impossible\");\n } else {\n tableResizing.set(Boolean.TRUE);\n try {\n Page newTablePage = expandTable(1);\n if (newTablePage == null) {\n return false;\n } else {\n freeTable(hashTablePage, hashtable, reprobeLimit());\n hashTablePage = newTablePage;\n hashtable = newTablePage.asIntBuffer();\n removedSlots = 0;\n return true;\n }\n } finally {\n tableResizing.remove();\n }\n }\n }\n\n private Page expandTable(int scale) {\n if (hashtable == DESTROYED_TABLE) {\n throw new IllegalStateException(\"This map/cache has been destroyed\");\n }\n\n /* Increase the size of the table to accommodate more entries */\n int newsize = hashtable.capacity() << scale;\n\n /* Check we're not hitting max capacity */\n if (newsize <= 0) {\n return null;\n }\n\n long startTime = -1;\n\n if (LOGGER.isDebugEnabled()) {\n startTime = System.nanoTime();\n int slots = hashtable.capacity() / ENTRY_SIZE;\n int newslots = newsize / ENTRY_SIZE;\n LOGGER.debug(\"Expanding table from {} slots to {} slots [load-factor={}]\",\n DebuggingUtils.toBase2SuffixedString(slots),\n DebuggingUtils.toBase2SuffixedString(newslots),\n ((float) size) / slots);\n }\n\n Page newTablePage = allocateTable(newsize / ENTRY_SIZE);\n if (newTablePage == null) {\n return null;\n }\n\n IntBuffer newTable = newTablePage.asIntBuffer();\n\n for (hashtable.clear(); hashtable.hasRemaining(); hashtable.position(hashtable.position() + ENTRY_SIZE)) {\n IntBuffer entry = (IntBuffer) hashtable.slice().limit(ENTRY_SIZE);\n\n if (isPresent(entry) && !writeEntry(newTable, entry)) {\n if (LOGGER.isDebugEnabled()) {\n LOGGER.debug(\"Table expansion from {} slots to {} slots abandoned - not enough table space\",\n DebuggingUtils.toBase2SuffixedString(hashtable.capacity() / ENTRY_SIZE),\n DebuggingUtils.toBase2SuffixedString(newsize / ENTRY_SIZE));\n }\n freeTable(newTablePage);\n return expandTable(scale + 1);\n }\n }\n\n if (LOGGER.isDebugEnabled()) {\n long time = System.nanoTime() - startTime;\n LOGGER.debug(\"Table expansion from {} slots to {} slots complete : took {}ms\", DebuggingUtils.toBase2SuffixedString(hashtable.capacity() / ENTRY_SIZE),\n DebuggingUtils.toBase2SuffixedString(newsize / ENTRY_SIZE),\n ((float) time) / 1000000);\n }\n\n return newTablePage;\n }\n\n protected boolean tryIncreaseReprobe() {\n if (reprobeLimit() >= getTableCapacity()) {\n return false;\n } else {\n int newReprobeLimit = reprobeLimit() << 1;\n\n if (newReprobeLimit >= REPROBE_WARNING_THRESHOLD) {\n long slots = getTableCapacity();\n LOGGER.warn(\"Expanding reprobe sequence from {} slots to {} slots [load-factor={}]\",\n reprobeLimit(), newReprobeLimit, ((float) size) / slots);\n } else if (LOGGER.isDebugEnabled()) {\n long slots = getTableCapacity();\n LOGGER.debug(\"Expanding reprobe sequence from {} slots to {} slots [load-factor={}]\",\n reprobeLimit(), newReprobeLimit, ((float) size) / slots);\n }\n\n reprobeLimit = newReprobeLimit;\n return true;\n }\n }\n\n protected void shrinkTable() {\n shrink();\n }\n\n private void shrink() {\n if (((float) size) / getTableCapacity() <= currentTableShrinkThreshold) {\n shrinkTableImpl();\n }\n }\n\n private void shrinkTableImpl() {\n if (tableResizing.get()) {\n LOGGER.debug(\"Shrink request ignored in the context of an in-process expand - likely self stealing\");\n } else {\n tableResizing.set(Boolean.TRUE);\n try {\n float shrinkRatio = (TABLE_RESIZE_THRESHOLD * getTableCapacity()) / size;\n int shrinkShift = Integer.numberOfTrailingZeros(Integer.highestOneBit(Math.max(2, (int) shrinkRatio)));\n Page newTablePage = shrinkTableImpl(shrinkShift);\n if (newTablePage == null) {\n currentTableShrinkThreshold = currentTableShrinkThreshold / 2;\n } else {\n currentTableShrinkThreshold = TABLE_SHRINK_THRESHOLD;\n freeTable(hashTablePage, hashtable, reprobeLimit());\n hashTablePage = newTablePage;\n hashtable = newTablePage.asIntBuffer();\n removedSlots = 0;\n }\n } finally {\n tableResizing.remove();\n }\n }\n }\n\n private Page shrinkTableImpl(int scale) {\n /* Increase the size of the table to accommodate more entries */\n int newsize = hashtable.capacity() >>> scale;\n\n /* Check we're not hitting zero capacity */\n if (newsize < ENTRY_SIZE) {\n if (scale > 1) {\n return shrinkTableImpl(scale - 1);\n } else {\n return null;\n }\n }\n\n long startTime = -1;\n\n if (LOGGER.isDebugEnabled()) {\n startTime = System.nanoTime();\n int slots = hashtable.capacity() / ENTRY_SIZE;\n int newslots = newsize / ENTRY_SIZE;\n LOGGER.debug(\"Shrinking table from {} slots to {} slots [load-factor={}]\",\n DebuggingUtils.toBase2SuffixedString(slots),\n DebuggingUtils.toBase2SuffixedString(newslots),\n ((float) size) / slots);\n }\n\n Page newTablePage = allocateTable(newsize / ENTRY_SIZE);\n if (newTablePage == null) {\n return null;\n }\n\n IntBuffer newTable = newTablePage.asIntBuffer();\n\n for (hashtable.clear(); hashtable.hasRemaining(); hashtable.position(hashtable.position() + ENTRY_SIZE)) {\n IntBuffer entry = (IntBuffer) hashtable.slice().limit(ENTRY_SIZE);\n\n if (isPresent(entry) && !writeEntry(newTable, entry)) {\n if (LOGGER.isDebugEnabled()) {\n LOGGER.debug(\"Table shrinking from {} slots to {} slots abandoned - too little table space\",\n DebuggingUtils.toBase2SuffixedString(hashtable.capacity() / ENTRY_SIZE),\n DebuggingUtils.toBase2SuffixedString(newsize / ENTRY_SIZE));\n }\n freeTable(newTablePage);\n if (scale > 1) {\n return shrinkTableImpl(scale - 1);\n } else {\n hashtable.clear();\n return null;\n }\n }\n }\n\n if (LOGGER.isDebugEnabled()) {\n long time = System.nanoTime() - startTime;\n LOGGER.debug(\"Table shrinking from {} slots to {} slots complete : took {}ms\", DebuggingUtils.toBase2SuffixedString(hashtable.capacity() / ENTRY_SIZE),\n DebuggingUtils.toBase2SuffixedString(newsize / ENTRY_SIZE),\n ((float) time) / 1000000);\n }\n\n return newTablePage;\n }\n\n private boolean writeEntry(IntBuffer table, IntBuffer entry) {\n int start = indexFor(spread(entry.get(KEY_HASHCODE)), table);\n int tableMask = table.capacity() - 1;\n\n for (int i = 0; i < reprobeLimit() * ENTRY_SIZE; i += ENTRY_SIZE) {\n int address = (start + i) & tableMask;\n int existingStatus = table.get(address + STATUS);\n if (isTerminating(existingStatus)) {\n table.position(address);\n table.put(entry);\n return true;\n } else if (isRemoved(existingStatus)) {\n throw new AssertionError();\n }\n }\n\n return false;\n }\n\n protected static int spread(int hash) {\n int h = hash;\n h += (h << 15) ^ 0xffffcd7d;\n h ^= (h >>> 10);\n h += (h << 3);\n h ^= (h >>> 6);\n h += (h << 2) + (h << 14);\n return h ^ (h >>> 16);\n }\n\n private Page allocateTable(int size) {\n Page newTablePage = tableSource.allocate(size * ENTRY_SIZE * (Integer.SIZE / Byte.SIZE), tableAllocationsSteal, false, null);\n if (newTablePage != null) {\n ByteBuffer buffer = newTablePage.asByteBuffer();\n byte[] zeros = new byte[1024];\n buffer.clear();\n while (buffer.hasRemaining()) {\n if (buffer.remaining() < zeros.length) {\n buffer.put(zeros, 0, buffer.remaining());\n } else {\n buffer.put(zeros);\n }\n }\n buffer.clear();\n }\n return newTablePage;\n }\n\n private void freeTable(Page tablePage, IntBuffer table, int finalReprobe) {\n if (hasUsedIterators) {\n pendingTableFrees.put(table, new PendingPage(tablePage, finalReprobe));\n } else {\n freeTable(tablePage);\n }\n }\n\n private void freeTable(Page tablePage) {\n tableSource.free(tablePage);\n }\n\n private int reprobeLimit() {\n return reprobeLimit;\n }\n\n protected class EntrySet extends AbstractSet<Entry<K, V>> {\n\n @Override\n public Iterator<Map.Entry<K, V>> iterator() {\n return new EntryIterator();\n }\n\n @Override\n public boolean contains(Object o) {\n if (!(o instanceof Entry<?, ?>)) {\n return false;\n }\n Entry<?, ?> e = (Entry<?, ?>) o;\n V value = get(e.getKey());\n return value != null && value.equals(e.getValue());\n }\n\n @Override\n public boolean remove(Object o) {\n return removeMapping(o);\n }\n\n @Override\n public int size() {\n return size;\n }\n\n @Override\n public void clear() {\n OffHeapHashMap.this.clear();\n }\n }\n\n protected class EncodingSet extends AbstractSet<Long> {\n @Override\n public Iterator<Long> iterator() {\n return new EncodingIterator();\n }\n\n @Override\n public int size() {\n return size;\n }\n\n @Override\n public boolean contains(Object o) {\n // We could allow the impl from AbstractSet to run but that won't perform as well as you'd expect Set.contains() to run\n throw new UnsupportedOperationException();\n }\n }\n\n protected class KeySet extends AbstractSet<K> {\n\n @Override\n public Iterator<K> iterator() {\n return new KeyIterator();\n }\n\n @Override\n public boolean contains(Object o) {\n return OffHeapHashMap.this.containsKey(o);\n }\n\n @Override\n public boolean remove(Object o) {\n return OffHeapHashMap.this.remove(o) != null;\n }\n\n @Override\n public int size() {\n return OffHeapHashMap.this.size();\n }\n\n @Override\n public void clear() {\n OffHeapHashMap.this.clear();\n }\n }\n\n protected abstract class HashIterator<T> implements Iterator<T> {\n\n final int expectedModCount; // For fast-fail\n /*\n * We *must* keep a reference to the original table object that is the key\n * in the weak map to prevent the table from being freed\n */\n final IntBuffer table;\n final IntBuffer tableView;\n\n T next = null; // next entry to return\n\n HashIterator() {\n hasUsedIterators = true;\n table = hashtable;\n tableView = (IntBuffer) table.asReadOnlyBuffer().clear();\n expectedModCount = modCount;\n\n if (size > 0) { // advance to first entry\n while (tableView.hasRemaining()) {\n IntBuffer entry = (IntBuffer) tableView.slice().limit(ENTRY_SIZE);\n tableView.position(tableView.position() + ENTRY_SIZE);\n\n if (isPresent(entry)) {\n next = create(entry);\n break;\n }\n }\n }\n }\n\n protected abstract T create(IntBuffer entry);\n\n @Override\n public boolean hasNext() {\n return next != null;\n }\n\n @Override\n public T next() {\n checkForConcurrentModification();\n\n T e = next;\n if (e == null) {\n throw new NoSuchElementException();\n }\n\n next = null;\n while (tableView.hasRemaining()) {\n IntBuffer entry = (IntBuffer) tableView.slice().limit(ENTRY_SIZE);\n tableView.position(tableView.position() + ENTRY_SIZE);\n\n if (isPresent(entry)) {\n next = create(entry);\n break;\n }\n }\n return e;\n }\n\n @Override\n public void remove() {\n throw new UnsupportedOperationException();\n }\n\n protected void checkForConcurrentModification() {\n if (modCount != expectedModCount) {\n throw new ConcurrentModificationException();\n }\n }\n }\n\n static class PendingPage {\n final Page tablePage;\n final int reprobe;\n\n PendingPage(Page tablePage, int reprobe) {\n this.tablePage = tablePage;\n this.reprobe = reprobe;\n }\n }\n\n protected void freePendingTables() {\n if (hasUsedIterators) {\n pendingTableFrees.reap();\n }\n }\n\n private void updatePendingTables(int hash, long oldEncoding, IntBuffer newEntry) {\n if (hasUsedIterators) {\n pendingTableFrees.reap();\n\n Iterator<PendingPage> it = pendingTableFrees.values();\n while (it.hasNext()) {\n PendingPage pending = it.next();\n\n IntBuffer pendingTable = pending.tablePage.asIntBuffer();\n pendingTable.position(indexFor(spread(hash), pendingTable));\n\n for (int i = 0; i < pending.reprobe; i++) {\n if (!pendingTable.hasRemaining()) {\n pendingTable.rewind();\n }\n\n IntBuffer entry = (IntBuffer) pendingTable.slice().limit(ENTRY_SIZE);\n\n if (isTerminating(entry)) {\n break;\n } else if (isPresent(entry) && (hash == entry.get(KEY_HASHCODE)) && (oldEncoding == readLong(entry, ENCODING))) {\n entry.put(newEntry.duplicate());\n break;\n } else {\n pendingTable.position(pendingTable.position() + ENTRY_SIZE);\n }\n }\n }\n }\n }\n\n private void wipePendingTables() {\n if (hasUsedIterators) {\n pendingTableFrees.reap();\n\n int[] zeros = new int[1024 >> 2];\n\n Iterator<PendingPage> it = pendingTableFrees.values();\n while (it.hasNext()) {\n PendingPage pending = it.next();\n\n IntBuffer pendingTable = pending.tablePage.asIntBuffer();\n\n pendingTable.clear();\n while (pendingTable.hasRemaining()) {\n if (pendingTable.remaining() < zeros.length) {\n pendingTable.put(zeros, 0, pendingTable.remaining());\n } else {\n pendingTable.put(zeros);\n }\n }\n pendingTable.clear();\n }\n }\n }\n\n protected class KeyIterator extends HashIterator<K> {\n KeyIterator() {\n super();\n }\n\n @Override\n @SuppressWarnings(\"unchecked\")\n protected K create(IntBuffer entry) {\n return (K) storageEngine.readKey(readLong(entry, ENCODING), entry.get(KEY_HASHCODE));\n }\n\n }\n\n protected class EntryIterator extends HashIterator<Entry<K, V>> {\n EntryIterator() {\n super();\n }\n\n @Override\n protected Entry<K, V> create(IntBuffer entry) {\n return new DirectEntry(entry);\n }\n }\n\n protected class EncodingIterator extends HashIterator<Long> {\n EncodingIterator() {\n super();\n }\n\n @Override\n protected Long create(IntBuffer entry) {\n return readLong(entry, ENCODING);\n }\n }\n\n class DirectEntry implements Entry<K, V> {\n\n private final K key;\n private final V value;\n\n @SuppressWarnings(\"unchecked\")\n DirectEntry(IntBuffer entry) {\n this.key = (K) storageEngine.readKey(readLong(entry, ENCODING), entry.get(KEY_HASHCODE));\n this.value = (V) storageEngine.readValue(readLong(entry, ENCODING));\n }\n\n @Override\n public K getKey() {\n return key;\n }\n\n @Override\n public V getValue() {\n return value;\n }\n\n @Override\n public V setValue(V value) {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public int hashCode() {\n return key.hashCode() ^ value.hashCode();\n }\n\n @Override\n public boolean equals(Object o) {\n if (o instanceof Entry<?, ?>) {\n Entry<?, ?> e = (Entry<?, ?>) o;\n return key.equals(e.getKey()) && value.equals(e.getValue());\n } else {\n return false;\n }\n }\n\n @Override\n public String toString() {\n return key + \"=\" + value;\n }\n }\n\n /*\n * remove used by EntrySet\n */\n @SuppressWarnings(\"unchecked\")\n protected boolean removeMapping(Object o) {\n freePendingTables();\n\n if (!(o instanceof Entry<?, ?>)) {\n return false;\n }\n\n Entry<K, V> e = (Entry<K, V>) o;\n\n Object key = e.getKey();\n int hash = key.hashCode();\n\n hashtable.position(indexFor(spread(hash)));\n\n for (int i = 0; i < reprobeLimit(); i++) {\n if (!hashtable.hasRemaining()) {\n hashtable.rewind();\n }\n\n IntBuffer entry = (IntBuffer) hashtable.slice().limit(ENTRY_SIZE);\n int entryPosition = hashtable.position();\n\n if (isTerminating(entry)) {\n return false;\n } else if (isPresent(entry) && keyEquals(key, hash, readLong(entry, ENCODING), entry.get(KEY_HASHCODE))\n && storageEngine.equalsValue(e.getValue(), readLong(entry, ENCODING))) {\n storageEngine.freeMapping(readLong(entry, ENCODING), entry.get(KEY_HASHCODE), true);\n\n entry.put(STATUS, STATUS_REMOVED);\n slotRemoved(entryPosition, entry);\n shrink();\n return true;\n } else {\n hashtable.position(hashtable.position() + ENTRY_SIZE);\n }\n }\n\n return false;\n }\n\n @Override\n public boolean evict(int index, boolean shrink) {\n return false;\n }\n\n protected void removeAtTableOffset(int offset, boolean shrink) {\n IntBuffer entry = ((IntBuffer) hashtable.duplicate().position(offset).limit(offset + ENTRY_SIZE)).slice();\n\n if (isPresent(entry)) {\n storageEngine.freeMapping(readLong(entry, ENCODING), entry.get(KEY_HASHCODE), true);\n\n entry.put(STATUS, STATUS_REMOVED);\n slotRemoved(offset, entry);\n if (shrink) {\n shrink();\n }\n } else {\n throw new AssertionError();\n }\n }\n\n @SuppressWarnings(\"unchecked\")\n protected V getAtTableOffset(int offset) {\n IntBuffer entry = ((IntBuffer) hashtable.duplicate().position(offset).limit(offset + ENTRY_SIZE)).slice();\n\n if (isPresent(entry)) {\n return (V) storageEngine.readValue(readLong(entry, ENCODING));\n } else {\n throw new AssertionError();\n }\n }\n\n protected Entry<K, V> getEntryAtTableOffset(int offset) {\n IntBuffer entry = ((IntBuffer) hashtable.duplicate().position(offset).limit(offset + ENTRY_SIZE)).slice();\n\n if (isPresent(entry)) {\n return new DirectEntry(entry);\n } else {\n throw new AssertionError();\n }\n }\n\n @Override\n public Integer getSlotForHashAndEncoding(int hash, long encoding, long mask) {\n IntBuffer view = (IntBuffer) hashtable.duplicate().position(indexFor(spread(hash)));\n\n int limit = reprobeLimit();\n\n for (int i = 0; i < limit; i++) {\n if (!view.hasRemaining()) {\n view.rewind();\n }\n\n IntBuffer entry = (IntBuffer) view.slice().limit(ENTRY_SIZE);\n\n if (isTerminating(entry)) {\n return null;\n } else if (isPresent(entry) && (hash == entry.get(KEY_HASHCODE)) && ((encoding & mask) == (readLong(entry, ENCODING) & mask))) {\n return view.position();\n } else {\n view.position(view.position() + ENTRY_SIZE);\n }\n }\n\n return null;\n }\n\n @Override\n public boolean updateEncoding(int hash, long oldEncoding, long newEncoding, long mask) {\n boolean updated = updateEncodingInTable(hashtable, reprobeLimit(), hash, oldEncoding, newEncoding, mask);\n\n if (hasUsedIterators) {\n pendingTableFrees.reap();\n\n Iterator<PendingPage> it = pendingTableFrees.values();\n while (it.hasNext()) {\n PendingPage pending = it.next();\n updated |= updateEncodingInTable(pending.tablePage.asIntBuffer(), pending.reprobe, hash, oldEncoding, newEncoding, mask);\n }\n }\n return updated;\n }\n\n private static boolean updateEncodingInTable(IntBuffer table, int limit, int hash, long oldEncoding, long newEncoding, long mask) {\n table.position(indexFor(spread(hash), table));\n\n for (int i = 0; i < limit; i++) {\n if (!table.hasRemaining()) {\n table.rewind();\n }\n\n IntBuffer entry = (IntBuffer) table.slice().limit(ENTRY_SIZE);\n\n if (isTerminating(entry)) {\n return false;\n } else if (isPresent(entry) && (hash == entry.get(KEY_HASHCODE)) && ((oldEncoding & mask) == (readLong(entry, ENCODING) & mask))) {\n entry.put(createEntry(hash, (readLong(entry, ENCODING) & ~mask) | newEncoding & mask, entry.get(STATUS)));\n return true;\n } else {\n table.position(table.position() + ENTRY_SIZE);\n }\n }\n return false;\n }\n\n @FindbugsSuppressWarnings(\"VO_VOLATILE_INCREMENT\")\n private void slotRemoved(int position, IntBuffer entry) {\n modCount++;\n removedSlots++;\n size--;\n updatePendingTables(entry.get(KEY_HASHCODE), readLong(entry, ENCODING), entry);\n removed(position, entry);\n }\n\n @FindbugsSuppressWarnings(\"VO_VOLATILE_INCREMENT\")\n private void slotAdded(int position, IntBuffer entry) {\n modCount++;\n size++;\n added(position, entry);\n }\n\n @FindbugsSuppressWarnings(\"VO_VOLATILE_INCREMENT\")\n private void slotUpdated(int position, IntBuffer entry, long oldEncoding) {\n modCount++;\n updatePendingTables(entry.get(KEY_HASHCODE), oldEncoding, entry);\n updated(position, entry);\n }\n\n protected void added(int position, IntBuffer entry) {\n //no-op\n }\n\n protected void hit(int position, IntBuffer entry) {\n //no-op\n }\n\n protected void removed(int position, IntBuffer entry) {\n //no-op\n }\n\n protected void updated(int position, IntBuffer entry) {\n //no-op\n }\n\n protected void tableExpansionFailure(int start, int length) {\n String msg = \"Failed to expand table.\\n\" + \"Current Table Size (slots) : \" + getTableCapacity() + '\\n' +\n \"Resize Will Require : \" + DebuggingUtils.toBase2SuffixedString(getTableCapacity() * ENTRY_SIZE * (Integer.SIZE / Byte.SIZE) * 2) + \"B\\n\" +\n \"Table Buffer Source : \" + tableSource;\n throw new OversizeMappingException(msg);\n }\n\n protected void storageEngineFailure(Object failure) {\n String msg = \"Storage engine failed to store: \" + failure + '\\n' +\n \"StorageEngine: \" + storageEngine;\n throw new OversizeMappingException(msg);\n }\n\n /* MapStatistics Methods */\n @Override\n public long getSize() {\n return size;\n }\n\n @Override\n public long getTableCapacity() {\n IntBuffer table = hashtable;\n return table == null ? 0 : table.capacity() / ENTRY_SIZE;\n }\n\n @Override\n public long getUsedSlotCount() {\n return getSize();\n }\n\n @Override\n public long getRemovedSlotCount() {\n return removedSlots;\n }\n\n @Override\n public int getReprobeLength() {\n return reprobeLimit();\n }\n\n @Override\n public long getAllocatedMemory() {\n return getDataAllocatedMemory() + (getTableCapacity() * ENTRY_SIZE * (Integer.SIZE / Byte.SIZE));\n }\n\n @Override\n public long getOccupiedMemory() {\n return getDataOccupiedMemory() + (getUsedSlotCount() * ENTRY_SIZE * (Integer.SIZE / Byte.SIZE));\n }\n\n @Override\n public long getVitalMemory() {\n return getDataVitalMemory() + (getTableCapacity() * ENTRY_SIZE * (Integer.SIZE / Byte.SIZE));\n }\n\n @Override\n public long getDataAllocatedMemory() {\n return storageEngine.getAllocatedMemory();\n }\n\n @Override\n public long getDataOccupiedMemory() {\n return storageEngine.getOccupiedMemory();\n }\n\n @Override\n public long getDataVitalMemory() {\n return storageEngine.getVitalMemory();\n }\n\n @Override\n public long getDataSize() {\n return storageEngine.getDataSize();\n }\n\n @Override\n public boolean isThiefForTableAllocations() {\n return tableAllocationsSteal;\n }\n\n @Override\n public Lock readLock() {\n return NoOpLock.INSTANCE;\n }\n\n @Override\n public Lock writeLock() {\n return NoOpLock.INSTANCE;\n }\n\n public StorageEngine<? super K, ? super V> getStorageEngine() {\n return storageEngine;\n }\n\n /*\n * JDK-8-alike metadata methods\n */\n @FindbugsSuppressWarnings(\"VO_VOLATILE_INCREMENT\")\n public MetadataTuple<V> computeWithMetadata(K key, BiFunction<? super K, ? super MetadataTuple<V>, ? extends MetadataTuple<V>> remappingFunction) {\n freePendingTables();\n\n int hash = key.hashCode();\n\n IntBuffer originalTable = hashtable;\n\n int start = indexFor(spread(hash));\n hashtable.position(start);\n\n int limit = reprobeLimit();\n\n for (int i = 0; i < limit; i++) {\n if (!hashtable.hasRemaining()) {\n hashtable.rewind();\n }\n\n IntBuffer entry = (IntBuffer) hashtable.slice().limit(ENTRY_SIZE);\n int entryPosition = hashtable.position();\n\n if (isAvailable(entry)) {\n int laterEntryPosition = entryPosition;\n for (IntBuffer laterEntry = entry; i < limit; i++) {\n if (isTerminating(laterEntry)) {\n break;\n } else if (isPresent(laterEntry) && keyEquals(key, hash, readLong(laterEntry, ENCODING), laterEntry.get(KEY_HASHCODE))) {\n long encoding = readLong(laterEntry, ENCODING);\n @SuppressWarnings(\"unchecked\")\n MetadataTuple<V> existingValue = metadataTuple(\n (V) storageEngine.readValue(encoding),\n laterEntry.get(STATUS) & ~RESERVED_STATUS_BITS);\n MetadataTuple<V> result = remappingFunction.apply(key, existingValue);\n if (result == null) {\n storageEngine.freeMapping(readLong(laterEntry, ENCODING), laterEntry.get(KEY_HASHCODE), true);\n laterEntry.put(STATUS, STATUS_REMOVED);\n slotRemoved(laterEntryPosition, laterEntry);\n shrink();\n } else if (result == existingValue) {\n //nop\n } else if (result.value() == existingValue.value()) {\n int previous = laterEntry.get(STATUS);\n laterEntry.put(STATUS, (previous & RESERVED_STATUS_BITS) | (result.metadata() & ~RESERVED_STATUS_BITS));\n } else {\n int [] newEntry = writeEntry(key, hash, result.value(), result.metadata());\n if (hashtable != originalTable || !isPresent(laterEntry)) {\n storageEngine.freeMapping(readLong(newEntry, ENCODING), newEntry[KEY_HASHCODE], false);\n return computeWithMetadata(key, remappingFunction);\n }\n storageEngine.attachedMapping(readLong(newEntry, ENCODING), hash, result.metadata());\n storageEngine.invalidateCache();\n storageEngine.freeMapping(readLong(laterEntry, ENCODING), laterEntry.get(KEY_HASHCODE), false);\n long oldEncoding = readLong(laterEntry, ENCODING);\n laterEntry.put(newEntry);\n slotUpdated(laterEntryPosition, (IntBuffer) laterEntry.flip(), oldEncoding);\n hit(laterEntryPosition, laterEntry);\n }\n return result;\n } else {\n hashtable.position(hashtable.position() + ENTRY_SIZE);\n }\n\n if (!hashtable.hasRemaining()) {\n hashtable.rewind();\n }\n\n laterEntry = (IntBuffer) hashtable.slice().limit(ENTRY_SIZE);\n laterEntryPosition = hashtable.position();\n }\n MetadataTuple<V> result = remappingFunction.apply(key, null);\n if (result != null) {\n int [] newEntry = writeEntry(key, hash, result.value(), result.metadata());\n if (hashtable != originalTable) {\n storageEngine.freeMapping(readLong(newEntry, ENCODING), newEntry[KEY_HASHCODE], false);\n return computeWithMetadata(key, remappingFunction);\n } else if (!isAvailable(entry)) {\n throw new AssertionError();\n }\n if (isRemoved(entry)) {\n removedSlots--;\n }\n storageEngine.attachedMapping(readLong(newEntry, ENCODING), hash, result.metadata());\n storageEngine.invalidateCache();\n entry.put(newEntry);\n slotAdded(entryPosition, entry);\n hit(entryPosition, entry);\n }\n return result;\n } else if (keyEquals(key, hash, readLong(entry, ENCODING), entry.get(KEY_HASHCODE))) {\n long existingEncoding = readLong(entry, ENCODING);\n int existingStatus = entry.get(STATUS);\n @SuppressWarnings(\"unchecked\")\n MetadataTuple<V> existingTuple = metadataTuple(\n (V) storageEngine.readValue(existingEncoding),\n existingStatus & ~RESERVED_STATUS_BITS);\n MetadataTuple<V> result = remappingFunction.apply(key, existingTuple);\n if (result == null) {\n storageEngine.freeMapping(existingEncoding, hash, true);\n entry.put(STATUS, STATUS_REMOVED);\n slotRemoved(entryPosition, entry);\n shrink();\n } else if (result == existingTuple) {\n //nop\n } else if (result.value() == existingTuple.value()) {\n entry.put(STATUS, (existingStatus & RESERVED_STATUS_BITS) | (result.metadata() & ~RESERVED_STATUS_BITS));\n } else {\n int [] newEntry = writeEntry(key, hash, result.value(), result.metadata());\n if (hashtable != originalTable || !isPresent(entry)) {\n storageEngine.freeMapping(readLong(newEntry, ENCODING), newEntry[KEY_HASHCODE], false);\n return computeWithMetadata(key, remappingFunction);\n }\n storageEngine.attachedMapping(readLong(newEntry, ENCODING), hash, result.metadata());\n storageEngine.invalidateCache();\n storageEngine.freeMapping(readLong(entry, ENCODING), entry.get(KEY_HASHCODE), false);\n entry.put(newEntry);\n slotUpdated(entryPosition, (IntBuffer) entry.flip(), existingEncoding);\n hit(entryPosition, entry);\n }\n return result;\n } else {\n hashtable.position(hashtable.position() + ENTRY_SIZE);\n }\n }\n\n // hit reprobe limit - must rehash\n expand(start, limit);\n\n return computeWithMetadata(key, remappingFunction);\n }\n\n @FindbugsSuppressWarnings(\"VO_VOLATILE_INCREMENT\")\n public MetadataTuple<V> computeIfAbsentWithMetadata(K key, Function<? super K,? extends MetadataTuple<V>> mappingFunction) {\n freePendingTables();\n\n int hash = key.hashCode();\n\n IntBuffer originalTable = hashtable;\n\n int start = indexFor(spread(hash));\n hashtable.position(start);\n\n int limit = reprobeLimit();\n\n for (int i = 0; i < limit; i++) {\n if (!hashtable.hasRemaining()) {\n hashtable.rewind();\n }\n\n IntBuffer entry = (IntBuffer) hashtable.slice().limit(ENTRY_SIZE);\n int entryPosition = hashtable.position();\n\n if (isAvailable(entry)) {\n for (IntBuffer laterEntry = entry; i < limit; i++) {\n if (isTerminating(laterEntry)) {\n break;\n } else if (isPresent(laterEntry) && keyEquals(key, hash, readLong(laterEntry, ENCODING), laterEntry.get(KEY_HASHCODE))) {\n @SuppressWarnings(\"unchecked\")\n MetadataTuple<V> tuple = metadataTuple(\n (V) storageEngine.readValue(readLong(laterEntry, ENCODING)),\n laterEntry.get(STATUS) & ~RESERVED_STATUS_BITS);\n return tuple;\n } else {\n hashtable.position(hashtable.position() + ENTRY_SIZE);\n }\n\n if (!hashtable.hasRemaining()) {\n hashtable.rewind();\n }\n\n laterEntry = (IntBuffer) hashtable.slice().limit(ENTRY_SIZE);\n }\n MetadataTuple<V> result = mappingFunction.apply(key);\n if (result != null) {\n int [] newEntry = writeEntry(key, hash, result.value(), result.metadata());\n if (hashtable != originalTable) {\n storageEngine.freeMapping(readLong(newEntry, ENCODING), newEntry[KEY_HASHCODE], false);\n return computeIfAbsentWithMetadata(key, mappingFunction);\n } else if (!isAvailable(entry)) {\n throw new AssertionError();\n }\n if (isRemoved(entry)) {\n removedSlots--;\n }\n storageEngine.attachedMapping(readLong(newEntry, ENCODING), hash, result.metadata());\n storageEngine.invalidateCache();\n entry.put(newEntry);\n slotAdded(entryPosition, entry);\n hit(entryPosition, entry);\n }\n return result;\n } else if (keyEquals(key, hash, readLong(entry, ENCODING), entry.get(KEY_HASHCODE))) {\n @SuppressWarnings(\"unchecked\")\n MetadataTuple<V> tuple = metadataTuple(\n (V) storageEngine.readValue(readLong(entry, ENCODING)),\n entry.get(STATUS) & ~RESERVED_STATUS_BITS);\n return tuple;\n } else {\n hashtable.position(hashtable.position() + ENTRY_SIZE);\n }\n }\n\n // hit reprobe limit - must rehash\n expand(start, limit);\n\n return computeIfAbsentWithMetadata(key, mappingFunction);\n }\n\n @FindbugsSuppressWarnings(\"VO_VOLATILE_INCREMENT\")\n public MetadataTuple<V> computeIfPresentWithMetadata(K key, BiFunction<? super K,? super MetadataTuple<V>,? extends MetadataTuple<V>> remappingFunction) {\n freePendingTables();\n\n int hash = key.hashCode();\n\n IntBuffer originalTable = hashtable;\n\n int start = indexFor(spread(hash));\n hashtable.position(start);\n\n int limit = reprobeLimit();\n\n for (int i = 0; i < limit; i++) {\n if (!hashtable.hasRemaining()) {\n hashtable.rewind();\n }\n\n IntBuffer entry = (IntBuffer) hashtable.slice().limit(ENTRY_SIZE);\n int entryPosition = hashtable.position();\n\n if (isTerminating(entry)) {\n return null;\n } else if (isPresent(entry) && keyEquals(key, hash, readLong(entry, ENCODING), entry.get(KEY_HASHCODE))) {\n long existingEncoding = readLong(entry, ENCODING);\n int existingStatus = entry.get(STATUS);\n @SuppressWarnings(\"unchecked\")\n MetadataTuple<V> existingValue = metadataTuple(\n (V) storageEngine.readValue(existingEncoding),\n existingStatus & ~RESERVED_STATUS_BITS);\n MetadataTuple<V> result = remappingFunction.apply(key, existingValue);\n if (result == null) {\n storageEngine.freeMapping(existingEncoding, hash, true);\n entry.put(STATUS, STATUS_REMOVED);\n slotRemoved(entryPosition, entry);\n shrink();\n } else if (result == existingValue) {\n //nop\n } else if (result.value() == existingValue.value()) {\n entry.put(STATUS, (existingStatus & RESERVED_STATUS_BITS) | (result.metadata() & ~RESERVED_STATUS_BITS));\n } else {\n int [] newEntry = writeEntry(key, hash, result.value(), result.metadata());\n if (hashtable != originalTable || !isPresent(entry)) {\n storageEngine.freeMapping(readLong(newEntry, ENCODING), newEntry[KEY_HASHCODE], false);\n return computeIfPresentWithMetadata(key, remappingFunction); //not exactly ideal - but technically correct\n }\n storageEngine.attachedMapping(readLong(newEntry, ENCODING), hash, result.metadata());\n storageEngine.invalidateCache();\n storageEngine.freeMapping(readLong(entry, ENCODING), entry.get(KEY_HASHCODE), false);\n entry.put(newEntry);\n slotUpdated(entryPosition, (IntBuffer) entry.flip(), readLong(entry, ENCODING));\n hit(entryPosition, entry);\n }\n return result;\n } else {\n hashtable.position(hashtable.position() + ENTRY_SIZE);\n }\n }\n\n return null;\n }\n}",
"public class WriteLockedOffHeapClockCache<K, V> extends AbstractOffHeapClockCache<K, V> {\n\n private final Lock lock = new ReentrantLock();\n\n public WriteLockedOffHeapClockCache(PageSource source, StorageEngine<? super K, ? super V> storageEngine) {\n super(source, storageEngine);\n }\n\n public WriteLockedOffHeapClockCache(PageSource source, boolean tableAllocationsSteal, StorageEngine<? super K, ? super V> storageEngine) {\n super(source, tableAllocationsSteal, storageEngine);\n }\n\n public WriteLockedOffHeapClockCache(PageSource source, StorageEngine<? super K, ? super V> storageEngine, int tableSize) {\n super(source, storageEngine, tableSize);\n }\n \n public WriteLockedOffHeapClockCache(PageSource source, boolean tableAllocationsSteal, StorageEngine<? super K, ? super V> storageEngine, int tableSize) {\n super(source, tableAllocationsSteal, storageEngine, tableSize);\n }\n \n @Override\n public Lock readLock() {\n return lock;\n }\n\n @Override\n public Lock writeLock() {\n return lock;\n }\n\n @Override\n public ReentrantReadWriteLock getLock() {\n throw new UnsupportedOperationException();\n }\n}",
"public abstract class AbstractConcurrentOffHeapCache<K, V> extends AbstractConcurrentOffHeapMap<K, V> implements PinnableCache<K, V> {\n\n private static final Comparator<Segment<?, ?>> SIZE_COMPARATOR = (o1, o2) -> (int) (o2.getSize() - o1.getSize());\n\n\n\n public AbstractConcurrentOffHeapCache(Factory<? extends PinnableSegment<K, V>> segmentFactory) {\n super(segmentFactory);\n }\n\n public AbstractConcurrentOffHeapCache(Factory<? extends Segment<K, V>> segmentFactory, int concurrency) {\n super(segmentFactory, concurrency);\n }\n\n @Override\n public V fill(K key, V value) {\n try {\n return super.fill(key, value);\n } catch (OversizeMappingException e) {\n return null;\n }\n }\n\n @Override\n public V getAndPin(final K key) {\n return segmentFor(key).getValueAndSetMetadata(key, Metadata.PINNED, Metadata.PINNED);\n }\n\n @Override\n public V putPinned(final K key, final V value) {\n try {\n return segmentFor(key).putPinned(key, value);\n } catch (OversizeMappingException e) {\n if (handleOversizeMappingException(key.hashCode())) {\n try {\n return segmentFor(key).putPinned(key, value);\n } catch (OversizeMappingException ex) {\n //ignore\n }\n }\n\n writeLockAll();\n try {\n do {\n try {\n return segmentFor(key).putPinned(key, value);\n } catch (OversizeMappingException ex) {\n e = ex;\n }\n } while (handleOversizeMappingException(key.hashCode()));\n throw e;\n } finally {\n writeUnlockAll();\n }\n }\n }\n\n @Override\n public boolean isPinned(Object key) {\n return segmentFor(key).isPinned(key);\n }\n\n @Override\n public void setPinning(K key, boolean pinned) {\n segmentFor(key).setPinning(key, pinned);\n }\n\n @Override\n protected PinnableSegment<K, V> segmentFor(Object key) {\n return (PinnableSegment<K, V>) super.segmentFor(key);\n }\n\n public boolean shrink() {\n Segment<?, ?>[] sorted = segments.clone();\n Arrays.sort(sorted, SIZE_COMPARATOR);\n for (Segment<?, ?> s : sorted) {\n if (s.shrink()) {\n return true;\n }\n }\n return false;\n }\n\n public boolean shrinkOthers(final int excludedHash) {\n boolean evicted = false;\n\n Segment<?, ?> target = segmentFor(excludedHash);\n for (Segment<?, ?> s : segments) {\n if (s == target) {\n continue;\n }\n evicted |= s.shrink();\n }\n\n return evicted;\n }\n}",
"public class IntegerStorageEngine implements HalfStorageEngine<Integer> {\n\n private static final IntegerStorageEngine SINGLETON = new IntegerStorageEngine();\n private static final Factory<IntegerStorageEngine> FACTORY = () -> SINGLETON;\n\n public static IntegerStorageEngine instance() {\n return SINGLETON;\n }\n\n public static Factory<IntegerStorageEngine> createFactory() {\n return FACTORY;\n }\n\n @Override\n public Integer read(int address) {\n return address;\n }\n\n @Override\n public Integer write(Integer value, int hash) {\n return value;\n }\n\n @Override\n public void free(int address) {\n //no-op\n }\n\n @Override\n public boolean equals(Object key, int address) {\n return key instanceof Integer && ((Integer) key) == address;\n }\n\n @Override\n public void clear() {\n //no-op\n }\n\n @Override\n public long getAllocatedMemory() {\n return 0;\n }\n\n @Override\n public long getOccupiedMemory() {\n return 0;\n }\n\n @Override\n public long getVitalMemory() {\n return 0;\n }\n\n @Override\n public long getDataSize() {\n return 0;\n }\n\n @Override\n public void invalidateCache() {\n //no-op\n }\n\n @Override\n public void bind(Owner owner, long mask) {\n //no-op\n }\n\n @Override\n public void destroy() {\n //no-op\n }\n\n @Override\n public boolean shrink() {\n return false;\n }\n}",
"public class OffHeapBufferHalfStorageEngine<T> extends PortabilityBasedHalfStorageEngine<T> implements OffHeapStorageArea.Owner {\n\n private static final int KEY_HASH_OFFSET = 0;\n private static final int LENGTH_OFFSET = 4;\n private static final int DATA_OFFSET = 8;\n private static final int HEADER_LENGTH = DATA_OFFSET;\n\n public static <T> Factory<OffHeapBufferHalfStorageEngine<T>> createFactory(final PageSource source, final int pageSize, final Portability<? super T> portability) {\n return createFactory(source, pageSize, portability, false, false);\n }\n\n public static <T> Factory<OffHeapBufferHalfStorageEngine<T>> createFactory(final PageSource source, final int pageSize, final Portability<? super T> portability, final boolean thief, final boolean victim) {\n return createFactory(source, pageSize, pageSize, portability, thief, victim);\n }\n\n public static <T> Factory<OffHeapBufferHalfStorageEngine<T>> createFactory(final PageSource source, final int initialPageSize, final int maximalPageSize, final Portability<? super T> portability, final boolean thief, final boolean victim) {\n return () -> new OffHeapBufferHalfStorageEngine<>(source, initialPageSize, maximalPageSize, portability, thief, victim);\n }\n\n private volatile Owner owner;\n private volatile long mask;\n private final OffHeapStorageArea storageArea;\n\n public OffHeapBufferHalfStorageEngine(PageSource source, int pageSize, Portability<? super T> portability) {\n this(source, pageSize, portability, false, false);\n }\n\n public OffHeapBufferHalfStorageEngine(PageSource source, int pageSize, Portability<? super T> portability, boolean thief, boolean victim) {\n this(source, pageSize, pageSize, portability, thief, victim);\n }\n\n public OffHeapBufferHalfStorageEngine(PageSource source, int initialPageSize, int maximalPageSize, Portability<? super T> portability, boolean thief, boolean victim) {\n super(portability);\n this.storageArea = new OffHeapStorageArea(PointerSize.INT, this, source, initialPageSize, maximalPageSize, thief, victim);\n }\n\n @Override\n public void clear() {\n storageArea.clear();\n }\n\n @Override\n public void free(int address) {\n storageArea.free(address);\n }\n\n @Override\n protected ByteBuffer readBuffer(int address) {\n int length = storageArea.readInt(address + LENGTH_OFFSET);\n return storageArea.readBuffer(address + DATA_OFFSET, length);\n }\n\n @Override\n protected Integer writeBuffer(ByteBuffer buffer, int hash) {\n int length = buffer.remaining();\n int address = (int) storageArea.allocate(length + HEADER_LENGTH);\n\n if (address >= 0) {\n storageArea.writeInt(address + KEY_HASH_OFFSET, hash);\n storageArea.writeInt(address + LENGTH_OFFSET, length);\n storageArea.writeBuffer(address + DATA_OFFSET, buffer);\n return address;\n } else {\n return null;\n }\n }\n\n @Override\n public long getAllocatedMemory() {\n return storageArea.getAllocatedMemory();\n }\n\n @Override\n public long getOccupiedMemory() {\n return storageArea.getOccupiedMemory();\n }\n\n @Override\n public long getVitalMemory() {\n return getAllocatedMemory();\n }\n\n @Override\n public long getDataSize() {\n //TODO This is an overestimate.\n return getOccupiedMemory();\n }\n\n @Override\n public String toString() {\n return \"OffHeapBufferStorageEngine \" + \"allocated=\" + DebuggingUtils.toBase2SuffixedString(getAllocatedMemory()) + \"B \" +\n \"occupied=\" + DebuggingUtils.toBase2SuffixedString(getOccupiedMemory()) + \"B\\n\" +\n \"Allocator: \" + storageArea;\n }\n\n @Override\n public void bind(Owner o, long m) {\n if (owner != null) {\n throw new AssertionError();\n }\n owner = o;\n mask = m;\n }\n\n @Override\n public void destroy() {\n storageArea.destroy();\n }\n\n @Override\n public boolean shrink() {\n return storageArea.shrink();\n }\n\n @Override\n public Collection<Long> evictAtAddress(long address, boolean shrink) {\n int hash = storageArea.readInt(address + KEY_HASH_OFFSET);\n int slot = owner.getSlotForHashAndEncoding(hash, address, mask);\n if (owner.evict(slot, shrink)) {\n return singleton(address);\n } else {\n return emptyList();\n }\n }\n\n @Override\n public Lock writeLock() {\n return owner.writeLock();\n }\n\n @Override\n public boolean isThief() {\n return owner.isThiefForTableAllocations();\n }\n\n @Override\n public boolean moved(long from, long to) {\n int hash = storageArea.readInt(to + KEY_HASH_OFFSET);\n return owner.updateEncoding(hash, from, to, mask);\n }\n\n @Override\n public int sizeOf(long address) {\n int length = storageArea.readInt(address + LENGTH_OFFSET);\n return HEADER_LENGTH + length;\n }\n}",
"public interface StorageEngine<K, V> {\n\n /**\n * Converts the supplied key and value objects into their encoded form.\n *\n * @param key a key object\n * @param value a value object\n * @param hash the key hash\n * @param metadata the metadata bits\n * @return the encoded mapping\n */\n Long writeMapping(K key, V value, int hash, int metadata);\n\n void attachedMapping(long encoding, int hash, int metadata);\n\n /**\n * Called to indicate that the associated encoded value is no longer needed.\n * <p>\n * This call can be used to free any associated resources tied to the\n * lifecycle of the supplied encoded value.\n *\n * @param encoding encoded value\n * @param hash hash of the freed mapping\n * @param removal marks removal from a map\n */\n void freeMapping(long encoding, int hash, boolean removal);\n\n /**\n * Converts the supplied encoded value into its correct object form.\n *\n * @param encoding encoded value\n * @return a decoded value object\n */\n V readValue(long encoding);\n\n /**\n * Called to determine the equality of the given Java object value against the\n * given encoded form.\n * <p>\n * Simple implementations will probably perform a decode on the given encoded\n * form in order to do a regular {@code Object.equals(Object)} comparison.\n * This method is provided to allow implementations to optimize this\n * comparison if possible.\n *\n * @param value a value object\n * @param encoding encoded value\n * @return {@code true} if the value and the encoding are equal\n */\n boolean equalsValue(Object value, long encoding);\n\n /**\n * Converts the supplied encoded key into its correct object form.\n *\n * @param encoding encoded key\n * @param hashCode hash-code of the decoded key\n * @return a decoded key object\n */\n K readKey(long encoding, int hashCode);\n\n /**\n * Called to determine the equality of the given object against the\n * given encoded form.\n * <p>\n * Simple implementations will probably perform a decode on the given encoded\n * form in order to do a regular {@code Object.equals(Object)} comparison.\n * This method is provided to allow implementations to optimize this\n * comparison if possible.\n *\n * @param key a key object\n * @param encoding encoded value\n * @return {@code true} if the key and the encoding are equal\n */\n boolean equalsKey(Object key, long encoding);\n\n /**\n * Called to indicate that all keys and values are now free.\n */\n void clear();\n\n /**\n * Returns a measure of the amount of memory allocated for this storage engine.\n *\n * @return memory allocated for this engine in bytes\n */\n long getAllocatedMemory();\n\n /**\n * Returns a measure of the amount of memory consumed by this storage engine.\n *\n * @return memory occupied by this engine in bytes\n */\n long getOccupiedMemory();\n\n /**\n * Returns a measure of the amount of vital memory allocated for this storage engine.\n *\n * @return vital memory allocated for this engine in bytes\n */\n long getVitalMemory();\n\n /**\n * Returns a measure of the total size of the keys and values stored in this storage engine.\n *\n * @return size of the stored keys and values in bytes\n */\n long getDataSize();\n\n /**\n * Invalidate any local key/value caches.\n * <p>\n * This is called to indicate the termination of a map write \"phase\". Caching\n * is permitted within a write operation (i.e. to cache around allocation\n * failures during eviction processes).\n */\n void invalidateCache();\n\n void bind(Owner owner);\n\n void destroy();\n\n boolean shrink();\n\n interface Owner extends ReadWriteLock {\n\n Long getEncodingForHashAndBinary(int hash, ByteBuffer offHeapBinaryKey);\n\n long getSize();\n\n long installMappingForHashAndEncoding(int pojoHash, ByteBuffer offheapBinaryKey, ByteBuffer offheapBinaryValue, int metadata);\n\n Iterable<Long> encodingSet();\n\n boolean updateEncoding(int hashCode, long lastAddress, long compressed, long mask);\n\n Integer getSlotForHashAndEncoding(int hash, long address, long mask);\n\n boolean evict(int slot, boolean b);\n\n boolean isThiefForTableAllocations();\n\n }\n}"
] | import org.terracotta.offheapstore.paging.UnlimitedPageSource;
import org.terracotta.offheapstore.paging.UpfrontAllocatingPageSource;
import org.terracotta.offheapstore.paging.PageSource;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.junit.Assert;
import org.junit.Test;
import org.terracotta.offheapstore.OffHeapHashMap;
import org.terracotta.offheapstore.ReadWriteLockedOffHeapClockCache;
import org.terracotta.offheapstore.WriteLockedOffHeapClockCache;
import org.terracotta.offheapstore.buffersource.HeapBufferSource;
import org.terracotta.offheapstore.concurrent.AbstractConcurrentOffHeapCache;
import org.terracotta.offheapstore.concurrent.ConcurrentOffHeapHashMap;
import org.terracotta.offheapstore.exceptions.OversizeMappingException;
import org.terracotta.offheapstore.storage.IntegerStorageEngine;
import org.terracotta.offheapstore.storage.OffHeapBufferHalfStorageEngine;
import org.terracotta.offheapstore.storage.SplitStorageEngine;
import org.terracotta.offheapstore.storage.StorageEngine;
import org.terracotta.offheapstore.storage.portability.ByteArrayPortability;
import org.terracotta.offheapstore.util.Factory; | /*
* Copyright 2015 Terracotta, Inc., a Software AG company.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.terracotta.offheapstore.paging;
public class EvictionRefusalStealingIT {
@Test
public void testDataSpaceIsStolen() {
long seed = System.nanoTime();
System.out.println("EvictionRefusalStealingTest.testDataSpaceIsStolen seed = " + seed);
Random rndm = new Random(seed); | PageSource source = new UpfrontAllocatingPageSource(new HeapBufferSource(), 1024 * 1024, 1024 * 1024); | 0 |
ralscha/wampspring | src/test/java/ch/rasc/wampspring/method/WampMessageTypeMessageConditionTest.java | [
"public class CallMessage extends WampMessage {\n\tprivate final String callID;\n\n\tprivate final String procURI;\n\n\tprivate final List<Object> arguments;\n\n\tpublic CallMessage(String callID, String procURI, Object... arguments) {\n\t\tsuper(WampMessageType.CALL);\n\t\tthis.callID = callID;\n\t\tthis.procURI = procURI;\n\t\tif (arguments != null) {\n\t\t\tthis.arguments = Arrays.asList(arguments);\n\t\t}\n\t\telse {\n\t\t\tthis.arguments = null;\n\t\t}\n\n\t}\n\n\tpublic CallMessage(JsonParser jp) throws IOException {\n\t\tthis(jp, null);\n\t}\n\n\tpublic CallMessage(JsonParser jp, WampSession wampSession) throws IOException {\n\t\tsuper(WampMessageType.CALL);\n\n\t\tif (jp.nextToken() != JsonToken.VALUE_STRING) {\n\t\t\tthrow new IOException();\n\t\t}\n\t\tthis.callID = jp.getValueAsString();\n\n\t\tif (jp.nextToken() != JsonToken.VALUE_STRING) {\n\t\t\tthrow new IOException();\n\t\t}\n\t\tthis.procURI = replacePrefix(jp.getValueAsString(), wampSession);\n\n\t\tList<Object> args = new ArrayList<>();\n\t\twhile (jp.nextToken() != JsonToken.END_ARRAY) {\n\t\t\targs.add(jp.readValueAs(Object.class));\n\t\t}\n\n\t\tif (!args.isEmpty()) {\n\t\t\tthis.arguments = Collections.unmodifiableList(args);\n\t\t}\n\t\telse {\n\t\t\tthis.arguments = null;\n\t\t}\n\t}\n\n\tpublic String getCallID() {\n\t\treturn this.callID;\n\t}\n\n\tpublic String getProcURI() {\n\t\treturn this.procURI;\n\t}\n\n\tpublic List<Object> getArguments() {\n\t\treturn this.arguments;\n\t}\n\n\t@Override\n\tpublic String getDestination() {\n\t\treturn this.procURI;\n\t}\n\n\t@Override\n\tpublic String toJson(JsonFactory jsonFactory) throws IOException {\n\t\ttry (StringWriter sw = new StringWriter();\n\t\t\t\tJsonGenerator jg = jsonFactory.createGenerator(sw)) {\n\t\t\tjg.writeStartArray();\n\t\t\tjg.writeNumber(getTypeId());\n\t\t\tjg.writeString(this.callID);\n\t\t\tjg.writeString(this.procURI);\n\t\t\tif (this.arguments != null) {\n\t\t\t\tfor (Object argument : this.arguments) {\n\t\t\t\t\tjg.writeObject(argument);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tjg.writeEndArray();\n\t\t\tjg.close();\n\t\t\treturn sw.toString();\n\t\t}\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"CallMessage [callID=\" + this.callID + \", procURI=\" + this.procURI\n\t\t\t\t+ \", arguments=\" + this.arguments + \"]\";\n\t}\n\n}",
"public class PublishMessage extends PubSubMessage {\n\tprivate final Object event;\n\n\tprivate final Boolean excludeMe;\n\n\tprivate final Set<String> exclude;\n\n\tprivate final Set<String> eligible;\n\n\tpublic PublishMessage(String topicURI, Object event) {\n\t\tthis(topicURI, event, null, null, null);\n\t}\n\n\tpublic PublishMessage(String topicURI, Object event, Boolean excludeMe) {\n\t\tthis(topicURI, event, excludeMe, null, null);\n\t}\n\n\tpublic PublishMessage(String topicURI, Object event, Set<String> exclude) {\n\t\tthis(topicURI, event, null, exclude, null);\n\t}\n\n\tpublic PublishMessage(String topicURI, Object event, Set<String> exclude,\n\t\t\tSet<String> eligible) {\n\t\tthis(topicURI, event, null, exclude, eligible);\n\t}\n\n\tprivate PublishMessage(String topicURI, Object event, Boolean excludeMe,\n\t\t\tSet<String> exclude, Set<String> eligible) {\n\t\tsuper(WampMessageType.PUBLISH, topicURI);\n\t\tthis.event = event;\n\t\tthis.excludeMe = excludeMe;\n\t\tthis.exclude = exclude;\n\t\tthis.eligible = eligible;\n\t}\n\n\tpublic PublishMessage(JsonParser jp) throws IOException {\n\t\tthis(jp, null);\n\t}\n\n\tpublic PublishMessage(JsonParser jp, WampSession wampSession) throws IOException {\n\t\tsuper(WampMessageType.PUBLISH);\n\n\t\tif (jp.nextToken() != JsonToken.VALUE_STRING) {\n\t\t\tthrow new IOException();\n\t\t}\n\t\tsetTopicURI(replacePrefix(jp.getValueAsString(), wampSession));\n\n\t\tjp.nextToken();\n\t\tthis.event = jp.readValueAs(Object.class);\n\n\t\tif (jp.nextToken() != JsonToken.END_ARRAY) {\n\t\t\tif (jp.getCurrentToken() == JsonToken.VALUE_TRUE\n\t\t\t\t\t|| jp.getCurrentToken() == JsonToken.VALUE_FALSE) {\n\t\t\t\tthis.excludeMe = jp.getValueAsBoolean();\n\n\t\t\t\tthis.exclude = null;\n\n\t\t\t\tthis.eligible = null;\n\n\t\t\t\tif (jp.nextToken() != JsonToken.END_ARRAY) {\n\t\t\t\t\t// Wrong message format, excludeMe should not be followed by\n\t\t\t\t\t// any value\n\t\t\t\t\tthrow new IOException();\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthis.excludeMe = null;\n\n\t\t\t\tTypeReference<Set<String>> typRef = new TypeReference<Set<String>>() {\n\t\t\t\t\t// nothing here\n\t\t\t\t};\n\n\t\t\t\tif (jp.getCurrentToken() != JsonToken.START_ARRAY) {\n\t\t\t\t\tthrow new IOException();\n\t\t\t\t}\n\t\t\t\tthis.exclude = jp.readValueAs(typRef);\n\n\t\t\t\tif (jp.nextToken() == JsonToken.START_ARRAY) {\n\t\t\t\t\tthis.eligible = jp.readValueAs(typRef);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tthis.eligible = null;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tthis.excludeMe = null;\n\t\t\tthis.exclude = null;\n\t\t\tthis.eligible = null;\n\t\t}\n\n\t}\n\n\tpublic Object getEvent() {\n\t\treturn this.event;\n\t}\n\n\t@Override\n\tpublic Object getPayload() {\n\t\treturn this.event != null ? this.event : EMPTY_OBJECT;\n\t}\n\n\tpublic Boolean getExcludeMe() {\n\t\treturn this.excludeMe;\n\t}\n\n\tpublic Set<String> getExclude() {\n\t\treturn this.exclude;\n\t}\n\n\tpublic Set<String> getEligible() {\n\t\treturn this.eligible;\n\t}\n\n\t@Override\n\tpublic String toJson(JsonFactory jsonFactory) throws IOException {\n\t\ttry (StringWriter sw = new StringWriter();\n\t\t\t\tJsonGenerator jg = jsonFactory.createGenerator(sw)) {\n\t\t\tjg.writeStartArray();\n\t\t\tjg.writeNumber(getTypeId());\n\t\t\tjg.writeString(getTopicURI());\n\n\t\t\tjg.writeObject(this.event);\n\t\t\tif (this.excludeMe != null && this.excludeMe) {\n\t\t\t\tjg.writeBoolean(true);\n\t\t\t}\n\t\t\telse if (this.exclude != null) {\n\t\t\t\tjg.writeObject(this.exclude);\n\t\t\t\tif (this.eligible != null) {\n\t\t\t\t\tjg.writeObject(this.eligible);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tjg.writeEndArray();\n\t\t\tjg.close();\n\t\t\treturn sw.toString();\n\t\t}\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"PublishMessage [topicURI=\" + getTopicURI() + \", event=\" + this.event\n\t\t\t\t+ \", excludeMe=\" + this.excludeMe + \", exclude=\" + this.exclude\n\t\t\t\t+ \", eligible=\" + this.eligible + \"]\";\n\t}\n\n}",
"public class SubscribeMessage extends PubSubMessage {\n\n\tpublic SubscribeMessage(String topicURI) {\n\t\tsuper(WampMessageType.SUBSCRIBE, topicURI);\n\t}\n\n\tpublic SubscribeMessage(JsonParser jp) throws IOException {\n\t\tthis(jp, null);\n\t}\n\n\tpublic SubscribeMessage(JsonParser jp, WampSession wampSession) throws IOException {\n\t\tsuper(WampMessageType.SUBSCRIBE);\n\n\t\tif (jp.nextToken() != JsonToken.VALUE_STRING) {\n\t\t\tthrow new IOException();\n\t\t}\n\t\tsetTopicURI(replacePrefix(jp.getValueAsString(), wampSession));\n\t}\n\n\t@Override\n\tpublic String toJson(JsonFactory jsonFactory) throws IOException {\n\t\ttry (StringWriter sw = new StringWriter();\n\t\t\t\tJsonGenerator jg = jsonFactory.createGenerator(sw)) {\n\t\t\tjg.writeStartArray();\n\t\t\tjg.writeNumber(getTypeId());\n\t\t\tjg.writeString(getTopicURI());\n\t\t\tjg.writeEndArray();\n\t\t\tjg.close();\n\t\t\treturn sw.toString();\n\t\t}\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"SubscribeMessage [topicURI=\" + getTopicURI() + \"]\";\n\t}\n\n}",
"public class UnsubscribeMessage extends PubSubMessage {\n\n\tprivate boolean cleanup = false;\n\n\tpublic UnsubscribeMessage(String topicURI) {\n\t\tsuper(WampMessageType.UNSUBSCRIBE, topicURI);\n\t}\n\n\tpublic UnsubscribeMessage(JsonParser jp) throws IOException {\n\t\tthis(jp, null);\n\t}\n\n\tpublic UnsubscribeMessage(JsonParser jp, WampSession wampSession) throws IOException {\n\t\tsuper(WampMessageType.UNSUBSCRIBE);\n\t\tif (jp.nextToken() != JsonToken.VALUE_STRING) {\n\t\t\tthrow new IOException();\n\t\t}\n\t\tsetTopicURI(replacePrefix(jp.getValueAsString(), wampSession));\n\t}\n\n\t/**\n\t * Creates an internal unsubscribe message. The system creates this message when the\n\t * WebSocket session ends and sends it to the subscribed message handlers for cleaning\n\t * up\n\t *\n\t * @param sessionId the WebSocket session id\n\t **/\n\tpublic static UnsubscribeMessage createCleanupMessage(WebSocketSession session) {\n\t\tUnsubscribeMessage msg = new UnsubscribeMessage(\"**\");\n\n\t\tmsg.setWebSocketSessionId(session.getId());\n\t\tmsg.setPrincipal(session.getPrincipal());\n\t\tmsg.setWampSession(new WampSession(session));\n\n\t\tmsg.cleanup = true;\n\n\t\treturn msg;\n\t}\n\n\tpublic boolean isCleanup() {\n\t\treturn this.cleanup;\n\t}\n\n\t@Override\n\tpublic String toJson(JsonFactory jsonFactory) throws IOException {\n\t\ttry (StringWriter sw = new StringWriter();\n\t\t\t\tJsonGenerator jg = jsonFactory.createGenerator(sw)) {\n\t\t\tjg.writeStartArray();\n\t\t\tjg.writeNumber(getTypeId());\n\t\t\tjg.writeString(getTopicURI());\n\t\t\tjg.writeEndArray();\n\t\t\tjg.close();\n\t\t\treturn sw.toString();\n\t\t}\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"UnsubscribeMessage [topicURI=\" + getTopicURI() + \"]\";\n\t}\n\n}",
"public enum WampMessageType {\n\n\t// Server-to-client Auxiliary\n\tWELCOME(0),\n\n\t// Client-to-server Auxiliary\n\tPREFIX(1),\n\n\t// Client-to-server RPC\n\tCALL(2),\n\n\t// Server-to-client RPC\n\tCALLRESULT(3),\n\n\t// Server-to-client RPC\n\tCALLERROR(4),\n\n\t// Client-to-server PubSub\n\tSUBSCRIBE(5),\n\n\t// Client-to-server PubSub\n\tUNSUBSCRIBE(6),\n\n\t// Client-to-server PubSub\n\tPUBLISH(7),\n\n\t// Server-to-client PubSub\n\tEVENT(8);\n\n\tprivate final int typeId;\n\n\tprivate WampMessageType(int typeId) {\n\t\tthis.typeId = typeId;\n\t}\n\n\tpublic int getTypeId() {\n\t\treturn this.typeId;\n\t}\n\n\tpublic static WampMessageType fromTypeId(int typeId) {\n\t\tswitch (typeId) {\n\t\tcase 0:\n\t\t\treturn WELCOME;\n\t\tcase 1:\n\t\t\treturn PREFIX;\n\t\tcase 2:\n\t\t\treturn CALL;\n\t\tcase 3:\n\t\t\treturn CALLRESULT;\n\t\tcase 4:\n\t\t\treturn CALLERROR;\n\t\tcase 5:\n\t\t\treturn SUBSCRIBE;\n\t\tcase 6:\n\t\t\treturn UNSUBSCRIBE;\n\t\tcase 7:\n\t\t\treturn PUBLISH;\n\t\tcase 8:\n\t\t\treturn EVENT;\n\t\tdefault:\n\t\t\treturn null;\n\t\t}\n\n\t}\n}"
] | import static org.assertj.core.api.Assertions.assertThat;
import java.util.Collection;
import org.junit.Test;
import ch.rasc.wampspring.message.CallMessage;
import ch.rasc.wampspring.message.PublishMessage;
import ch.rasc.wampspring.message.SubscribeMessage;
import ch.rasc.wampspring.message.UnsubscribeMessage;
import ch.rasc.wampspring.message.WampMessageType; | /**
* Copyright 2014-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ch.rasc.wampspring.method;
public class WampMessageTypeMessageConditionTest {
@Test
public void testGetMessageType() {
assertThat(WampMessageTypeMessageCondition.CALL.getMessageType())
.isEqualTo(WampMessageType.CALL);
assertThat(WampMessageTypeMessageCondition.PUBLISH.getMessageType())
.isEqualTo(WampMessageType.PUBLISH);
assertThat(WampMessageTypeMessageCondition.SUBSCRIBE.getMessageType())
.isEqualTo(WampMessageType.SUBSCRIBE);
assertThat(WampMessageTypeMessageCondition.UNSUBSCRIBE.getMessageType())
.isEqualTo(WampMessageType.UNSUBSCRIBE);
WampMessageTypeMessageCondition cond = new WampMessageTypeMessageCondition(
WampMessageType.CALL);
assertThat(cond.getMessageType()).isEqualTo(WampMessageType.CALL);
}
@SuppressWarnings("unchecked")
@Test
public void testGetContent() {
assertThat((Collection<WampMessageType>) WampMessageTypeMessageCondition.CALL
.getContent()).hasSize(1).containsExactly(WampMessageType.CALL);
assertThat((Collection<WampMessageType>) WampMessageTypeMessageCondition.PUBLISH
.getContent()).hasSize(1).containsExactly(WampMessageType.PUBLISH);
assertThat((Collection<WampMessageType>) WampMessageTypeMessageCondition.SUBSCRIBE
.getContent()).hasSize(1).containsExactly(WampMessageType.SUBSCRIBE);
assertThat(
(Collection<WampMessageType>) WampMessageTypeMessageCondition.UNSUBSCRIBE
.getContent()).hasSize(1)
.containsExactly(WampMessageType.UNSUBSCRIBE);
WampMessageTypeMessageCondition cond = new WampMessageTypeMessageCondition(
WampMessageType.CALL);
assertThat((Collection<WampMessageType>) cond.getContent()).hasSize(1)
.containsExactly(WampMessageType.CALL);
}
@Test
public void testGetMatchingCondition() {
CallMessage cm = new CallMessage("1", "proc"); | SubscribeMessage sm = new SubscribeMessage("proc"); | 2 |
lemberg/d8androidsdk | sample/src/main/java/com/ls/drupal8demo/adapters/CategoryArticlesListAdapter.java | [
"public abstract class AbstractBaseDrupalEntity implements DrupalClient.OnResponseListener, ICharsetItem\n{\n\ttransient private DrupalClient drupalClient; \n\n\ttransient private Snapshot snapshot;\n\n\t/**\n\t * In case of request canceling - no method will be triggered.\n\t * \n\t * @author lemberg\n\t * \n\t */\n\tpublic interface OnEntityRequestListener\n\t{\n\t\tvoid onRequestCompleted(AbstractBaseDrupalEntity entity, Object tag, ResponseData data);\n\t\tvoid onRequestFailed(AbstractBaseDrupalEntity entity, Object tag, ResponseData data);\n\t\tvoid onRequestCanceled(AbstractBaseDrupalEntity entity, Object tag);\n\t}\t\n\t\t\t\n\t/**\n\t * @return path to resource. Shouldn't include base URL(domain).\n\t */\n\tprotected abstract String getPath();\n\n\t/**\n\t * Called for post requests only\n\t * \n\t * @return post parameters to be published on server or null if default\n\t * object serialization has to be performed.\n\t */\n\tprotected abstract Map<String, String> getItemRequestPostParameters();\n\n\n\t/**\t \n\t * @param method is instance od {@link com.ls.http.base.BaseRequest.RequestMethod} enum, this method is called for. it can be \"GET\", \"POST\", \"PUT\" ,\"PATCH\" or \"DELETE\".\n\t * @return parameters for the request method specified. In case if collection is passed as map entry value - all entities will be added under corresponding key. Object.toString will be called otherwise.\n\t */\n\tprotected abstract Map<String, Object> getItemRequestGetParameters(RequestMethod method);\n\n\t/** Get data object, used to perform perform get/post/patch/delete requests.\n\t * @return data object. Can implement {@link com.ls.http.base.IPostableItem} or {@link com.ls.http.base.IResponseItem} in order to handle json/xml serialization/deserialization manually.\n\t */\n\tabstract @NonNull\n Object getManagedData();\n\n /**\n * @param method is instance od {@link com.ls.http.base.BaseRequest.RequestMethod} enum, this method is called for. it can be \"GET\", \"POST\", \"PUT\" ,\"PATCH\" or \"DELETE\".\n * @return headers for the request method specified.\n */\n protected Map<String, String> getItemRequestHeaders(RequestMethod method){\n return new HashMap<String, String>();\n };\n\n\t@Override\n\tpublic String getCharset()\n\t{\n\t\treturn null;\n\t}\n\n\tpublic AbstractBaseDrupalEntity(DrupalClient client)\n\t{\n\t\tthis.drupalClient = client;\t\n\t}\n\t\n\t@Deprecated\n\t/**\n * Method is deprecated. Use {@link #postToServer(boolean, Class, Object, com.ls.drupal.AbstractBaseDrupalEntity.OnEntityRequestListener)} method. instead\n\t * @param synchronous\n\t * if true - request will be performed synchronously.\n\t * @param resultClass\n\t * class of result or null if no result needed.\n\t * @param tag Object tag, passer to listener after request was finished or failed because of exception.\n * Tag object can contain some additional data you may require while handling response and may appear useful in case if you are using same listener for multiple requests.\n * You can pass null if no tag is needed\n\t * @param listener \n\t * @return @class ResponseData entity, containing server response string and\n\t * code or error in case of synchronous request, null otherwise\n\t */\n\tpublic ResponseData pushToServer(boolean synchronous, Class<?> resultClass, Object tag, OnEntityRequestListener listener)\n\t{\n\t\treturn postToServer(synchronous,resultClass,tag,listener);\n\t}\n\n /**\n * @param synchronous\n * if true - request will be performed synchronously.\n * @param resultClass\n * class of result or null if no result needed.\n * @param tag Object tag, passer to listener after request was finished or failed because of exception.\n * Tag object can contain some additional data you may require while handling response and may appear useful in case if you are using same listener for multiple requests.\n * You can pass null if no tag is needed\n * @param listener\n * @return @class ResponseData entity, containing server response string and\n * code or error in case of synchronous request, null otherwise\n */\n public ResponseData postToServer(boolean synchronous, Class<?> resultClass, Object tag, OnEntityRequestListener listener)\n {\n Assert.assertNotNull(\"You have to specify drupal client in order to perform requests\", this.drupalClient);\n DrupalEntityTag drupalTag = new DrupalEntityTag(false, tag, listener);\n ResponseData result = this.drupalClient.postObject(this, getRequestConfig(RequestMethod.POST,resultClass), drupalTag, this, synchronous);\n return result;\n }\n\n /**\n * @param synchronous\n * if true - request will be performed synchronously.\n * @param resultClass\n * class of result or null if no result needed.\n * @param tag Object tag, passer to listener after request was finished or failed because of exception.\n * Tag object can contain some additional data you may require while handling response and may appear useful in case if you are using same listener for multiple requests.\n * You can pass null if no tag is needed\n * @param listener\n * @return @class ResponseData entity, containing server response string and\n * code or error in case of synchronous request, null otherwise\n */\n public ResponseData putToServer(boolean synchronous, Class<?> resultClass, Object tag, OnEntityRequestListener listener)\n {\n Assert.assertNotNull(\"You have to specify drupal client in order to perform requests\", this.drupalClient);\n DrupalEntityTag drupalTag = new DrupalEntityTag(false, tag, listener);\n ResponseData result = this.drupalClient.putObject(this, getRequestConfig(RequestMethod.PUT,resultClass), drupalTag, this, synchronous);\n return result;\n }\n\n\t/**\n\t * @param synchronous\n\t * if true - request will be performed synchronously.\n * @param tag Object tag, passer to listener after request was finished or failed because of exception.\n * Tag object can contain some additional data you may require while handling response and may appear useful in case if you are using same listener for multiple requests.\n * You can pass null if no tag is needed\n\t * @param listener \n\t * @return @class ResponseData entity, containing server response or error\n\t * in case of synchronous request, null otherwise\n\t */\n\tpublic ResponseData pullFromServer(boolean synchronous, Object tag, OnEntityRequestListener listener)\n\t{\n\t\tAssert.assertNotNull(\"You have to specify drupal client in order to perform requests\", this.drupalClient);\n\t\tDrupalEntityTag drupalTag = new DrupalEntityTag(true, tag, listener);\n\t\tResponseData result;\n Map postParams = this.getItemRequestPostParameters();\n if(postParams == null || postParams.isEmpty()) {\n result = this.drupalClient.getObject(this, getRequestConfig(RequestMethod.GET,this.getManagedDataClassSpecifyer()), drupalTag, this, synchronous);\n }else{\n result = this.drupalClient.postObject(this, getRequestConfig(RequestMethod.POST,this.getManagedDataClassSpecifyer()), drupalTag, this, synchronous);\n }\n\t\t;\t\t\n\t\treturn result;\n\t}\n\n\t/**\n\t * @param synchronous\n\t * if true - request will be performed synchronously.\n\t * @param resultClass\n\t * class of result or null if no result needed. \n * @param tag Object tag, passer to listener after request was finished or failed because of exception.\n * Tag object can contain some additional data you may require while handling response and may appear useful in case if you are using same listener for multiple requests.\n * You can pass null if no tag is needed\n\t * @param listener \n\t * @return @class ResponseData entity, containing server response or error\n\t * in case of synchronous request, null otherwise\n\t */\n\tpublic ResponseData deleteFromServer(boolean synchronous, Class<?> resultClass, Object tag, OnEntityRequestListener listener)\n\t{\n\t\tAssert.assertNotNull(\"You have to specify drupal client in order to perform requests\", this.drupalClient);\n\t\tDrupalEntityTag drupalTag = new DrupalEntityTag(false, tag, listener);\n\t\tResponseData result = this.drupalClient.deleteObject(this,getRequestConfig(RequestMethod.DELETE,resultClass), drupalTag, this, synchronous);\n\t\treturn result;\n\t}\n\n\t// OnResponseListener methods\n\t\n\t@Override\n\tpublic void onResponseReceived(ResponseData data, Object tag)\n\t{\t\t\n\t\tDrupalEntityTag entityTag = (DrupalEntityTag)tag;\n\t\tif (entityTag.consumeResponse)\n\t\t{\n\t\t\tthis.consumeObject(data);\n\t\t}\n\n\t\tif(entityTag.listener != null)\n\t\t{\n\t\t\tentityTag.listener.onRequestCompleted(this, entityTag.requestTag, data);\n\t\t}\n ConnectionManager.instance().setConnected(true);\n\t}\n\t\n\t@Override\n\tpublic void onError(ResponseData data, Object tag)\n\t{\n\t\tDrupalEntityTag entityTag = (DrupalEntityTag)tag;\n\t\tif(entityTag.listener != null)\n\t\t{\n\t\t\tentityTag.listener.onRequestFailed(this,entityTag.requestTag,data);\n\t\t}\n\n if(VolleyResponseUtils.isNetworkingError(data.getError()))\n {\n ConnectionManager.instance().setConnected(false);\n }\n\t}\n\n\t@Override\n\tpublic void onCancel(Object tag)\n\t{\n\t\tDrupalEntityTag entityTag = (DrupalEntityTag)tag;\n\t\tif(entityTag.listener != null)\n\t\t{\n\t\t\tentityTag.listener.onRequestCanceled(this,entityTag.requestTag);\n\t\t}\t\n\t}\n\n\t/**\n\t * Method is used in order to apply server response result object to current instance \n\t * and clone all fields of object specified to current one You can override this\n\t * method in order to perform custom cloning.\n\t * \n\t * @param data\n\t * response data, containing object to be consumed\n\t */\n\tprotected void consumeObject(ResponseData data)\n\t{\n\t\tObject consumer = this.getManagedDataChecked();\n\t\tAbstractBaseDrupalEntity.consumeObject(consumer, data.getData());\n\t}\n\n /**\n * Method is used in order to apply server error response result object to current instance\n * You can override this method in order to perform custom cloning. Default implementation does nothing\n * @param data\n */\n protected void consumeError(ResponseData data)\n {\n //Just a method stub to be overriden with children.\n }\n\n /**\n * @param method\n * @param resultClass\n * class of result or null if no result needed.\n\n */\n protected RequestConfig getRequestConfig(RequestMethod method,Object resultClass)\n {\n RequestConfig config = new RequestConfig(resultClass);\n config.setRequestFormat(getItemRequestFormat(method));\n config.setResponseFormat(getItemResponseFormat(method));\n config.setErrorResponseClassSpecifier(getItemErrorResponseClassSpecifier(method));\n return config;\n }\n\n\t\n\t/**\n\t * Utility method, used to clone all entities non-transient fields to the consumer\n\t * @param consumer\n\t * @param entity\n\t */\n\tpublic static void consumeObject(Object consumer,Object entity)\n\t{\n\t\tClass<?> currentClass = consumer.getClass();\n\t\twhile (!Object.class.equals(currentClass))\n\t\t{\n\t\t\tField[] fields = currentClass.getDeclaredFields();\n\t\t\tfor (int counter = 0; counter < fields.length; counter++)\n\t\t\t{\n\t\t\t\tField field = fields[counter];\n\t\t\t\tExpose expose = field.getAnnotation(Expose.class);\n\t\t\t\tif (expose != null && !expose.deserialize() || Modifier.isTransient(field.getModifiers()))\n\t\t\t\t{\n\t\t\t\t\tcontinue;// We don't have to copy ignored fields.\n\t\t\t\t}\n\t\t\t\tfield.setAccessible(true);\n\t\t\t\tObject value;\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tvalue = field.get(entity);\n\t\t\t\t\t// if(value != null)\n\t\t\t\t\t// {\n\t\t\t\t\tfield.set(consumer, value);\n\t\t\t\t\t// }\n\t\t\t\t} catch (IllegalAccessException e)\n\t\t\t\t{\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t} catch (IllegalArgumentException e)\n\t\t\t\t{\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\t\t\tcurrentClass = currentClass.getSuperclass();\n\t\t}\n\t}\n\n\t/**\n\t * You can override this method in order to gain custom classes from \"GET\"\n\t * Note: you will also have to override {@link AbstractBaseDrupalEntity#consumeObject(com.ls.http.base.ResponseData)} method in order to apply modified response class\n\t * request response.\n\t * \n\t * @return Class or type of managed object.\n\t */\n\tprotected Object getManagedDataClassSpecifyer()\n\t{\n\t\treturn this.getManagedData().getClass();\n\t}\n\n /**\n * @param method is instance of {@link com.ls.http.base.BaseRequest.RequestMethod} enum, this method is called for. it can be \"GET\", \"POST\", \"PUT\" ,\"PATCH\" or \"DELETE\".\n * @return the format entity will be serialized to. You can override this method in order to customize return. If null returned - default client format will be performed.\n */\n protected BaseRequest.RequestFormat getItemRequestFormat(RequestMethod method){\n return null;\n };\n\n /**\n * @param method is instance of {@link com.ls.http.base.BaseRequest.RequestMethod} enum, this method is called for. it can be \"GET\", \"POST\", \"PUT\" ,\"PATCH\" or \"DELETE\".\n * @return the format response entity will be formatted to. You can override this method in order to customize return. If null returned - default client format will be performed.\n */\n protected BaseRequest.ResponseFormat getItemResponseFormat(RequestMethod method){\n return null;\n };\n\n /**\n * @param method is instance of {@link com.ls.http.base.BaseRequest.RequestMethod} enum, this method is called for. it can be \"GET\", \"POST\", \"PUT\" ,\"PATCH\" or \"DELETE\".\n * @return Class or Type, returned as parsedError field of ResultData object, can be null if you don't need one.\n */\n protected Object getItemErrorResponseClassSpecifier(RequestMethod method){\n return null;\n };\n\n\tpublic DrupalClient getDrupalClient()\n\t{\n\t\treturn drupalClient;\n\t}\n\n\tpublic void setDrupalClient(DrupalClient drupalClient)\n\t{\n\t\tthis.drupalClient = drupalClient;\n\t}\n\n\t// Request canceling\n\tpublic void cancellAllRequests()\n\t{\n\t\tthis.drupalClient.cancelAllRequestsForListener(this, null);\n\t}\n\n\t// Patch method management\n\n\t/**\n\t * Creates snapshot to be used later in order to calculate differences for\n\t * patch request.\n\t */\n\tpublic void createSnapshot()\n\t{\n\t\tthis.snapshot = getCurrentStateSnapshot();\n\t}\n\t\n\t/**\n\t * Release current snapshot (is recommended to perform after successful patch request)\n\t */\n\tpublic void clearSnapshot()\n\t{\n\t\tthis.snapshot = null;\n\t}\n\n\tprotected Snapshot getCurrentStateSnapshot()\n\t{\n\t\tObjectComparator comparator = new ObjectComparator();\n\t\treturn comparator.createSnapshot(this.getManagedDataChecked());\n\t}\n\n\t/**\n\t * \n\t * @param synchronous\n\t * if true - request will be performed synchronously.\n\t * @param resultClass\n\t * class of result or null if no result needed.\n\t * @param tag Object tag, passer to listener after request was finished or failed because of exception\n\t * @param listener \n\t * @return @class ResponseData entity, containing server response and\n\t * resultClass instance or error in case of synchronous request,\n\t * null otherwise\n\t * @throws IllegalStateException\n\t * in case if there are no changes to post. You can check if\n\t * there are ones, calling <code>isModified()</code> method.\n\t */\n\tpublic ResponseData patchServerData(boolean synchronous, Class<?> resultClass, Object tag, OnEntityRequestListener listener) throws IllegalStateException\n\t{\n\t\tDrupalEntityTag drupalTag = new DrupalEntityTag(false, tag, listener);\n\t\tResponseData result = this.drupalClient.patchObject(this, getRequestConfig(RequestMethod.PATCH,resultClass), drupalTag, this, synchronous);\n\t\treturn result;\n\t}\n\n\tpublic Object getPatchObject()\n\t{\n\t\tObjectComparator comparator = new ObjectComparator();\n\t\tSnapshot currentState = comparator.createSnapshot(this.getManagedDataChecked());\n\n\t\t@SuppressWarnings(\"null\")\n Object difference = this.getDifference(this.snapshot, currentState, comparator);\n\t\tif (difference != null)\n\t\t{\n\t\t\treturn difference;\n\t\t} else\n\t\t{\n\t\t\tthrow new IllegalStateException(\"There are no changes to post, check isModified() call before\");\n\t\t}\n\t}\n\n\t/**\n\t * @return true if there are changes to post, false otherwise\n\t */\n\t@SuppressWarnings(\"null\")\n\tpublic boolean isModified()\n\t{\n\t\tObjectComparator comparator = new ObjectComparator();\n\t\treturn this.isModified(this.snapshot, comparator.createSnapshot(this), comparator);\n\t}\n\n\tprivate boolean isModified(@NonNull Snapshot origin, @NonNull Snapshot current, @NonNull ObjectComparator comparator)\n\t{\n\t\tObject difference = this.getDifference(origin, current, comparator);\n\t\treturn (difference != null);\n\t}\n\n\tprivate Object getDifference(@NonNull Snapshot origin, @NonNull Snapshot current, ObjectComparator comparator)\n\t{\n\t\tAssert.assertNotNull(\"You have to specify drupal client in order to perform requests\", this.drupalClient);\n\t\tAssert.assertNotNull(\"You have to make initial objects snapshot in order to calculate changes\", origin);\n\t\treturn comparator.getDifferencesJSON(origin, current);\n\t}\n\t\n\t@NonNull\n\tprivate Object getManagedDataChecked()\n\t{\n\t\tAssert.assertNotNull(\"You have to specify non null data object\", this.getManagedData());\n\t\treturn getManagedData();\n\t}\n\t\n\tprotected final class DrupalEntityTag\n\t{\n\t\tpublic OnEntityRequestListener listener;\n\t\tpublic Object requestTag;\n\t\tpublic boolean consumeResponse;\n\t\t\n\t\tpublic DrupalEntityTag(boolean consumeResponse,Object requestTag,OnEntityRequestListener listener)\n\t\t{\n\t\t\tthis.consumeResponse = consumeResponse;\n\t\t\tthis.requestTag = requestTag;\n\t\t\tthis.listener = listener;\n\t\t}\n\t}\n}",
"public interface OnEntityRequestListener\n{\n\tvoid onRequestCompleted(AbstractBaseDrupalEntity entity, Object tag, ResponseData data);\n\tvoid onRequestFailed(AbstractBaseDrupalEntity entity, Object tag, ResponseData data);\n\tvoid onRequestCanceled(AbstractBaseDrupalEntity entity, Object tag);\n}\t",
"public class DrupalClient implements OnResponseListener {\n public enum DuplicateRequestPolicy {ALLOW,ATTACH,REJECT}\n\n private final RequestFormat requestFormat;\n private String baseURL;\n private RequestQueue queue;\n private ResponseListenersSet listeners;\n private String defaultCharset;\n\n private ILoginManager loginManager;\n private RequestProgressListener progressListener;\n\n private int requestTimeout = 1500;\n\n private DuplicateRequestPolicy duplicateRequestPolicy = DuplicateRequestPolicy.ATTACH;\n\n public static interface OnResponseListener {\n\n void onResponseReceived(ResponseData data, Object tag);\n\n void onError(ResponseData data, Object tag);\n\n void onCancel(Object tag);\n }\n\n /**\n * Can be used in order to react on request count changes (start/success/failure or canceling).\n *\n * @author lemberg\n */\n public interface RequestProgressListener {\n\n /**\n * Called after new request was added to queue\n *\n * @param activeRequests number of requests pending\n */\n void onRequestStarted(DrupalClient theClient, int activeRequests);\n\n /**\n * Called after current request was complete\n *\n * @param activeRequests number of requests pending\n */\n void onRequestFinished(DrupalClient theClient, int activeRequests);\n }\n\n /**\n * @param theBaseURL this URL will be appended with {@link AbstractBaseDrupalEntity#getPath()}\n * @param theContext application context, used to create request queue\n */\n public DrupalClient(@NonNull String theBaseURL, @NonNull Context theContext) {\n this(theBaseURL, theContext, null);\n }\n\n /**\n * @param theBaseURL this URL will be appended with {@link AbstractBaseDrupalEntity#getPath()}\n * @param theContext application context, used to create request queue\n * @param theFormat server request/response format. Defines format of serialized objects and server response format, see {@link com.ls.http.base.BaseRequest.RequestFormat}\n */\n public DrupalClient(@NonNull String theBaseURL, @NonNull Context theContext, @Nullable RequestFormat theFormat) {\n this(theBaseURL, theContext, theFormat, null);\n }\n\n /**\n * @param theBaseURL this URL will be appended with {@link AbstractBaseDrupalEntity#getPath()}\n * @param theContext application context, used to create request queue\n * @param theFormat server request/response format. Defines format of serialized objects and server response format, see {@link com.ls.http.base.BaseRequest.RequestFormat}\n * @param theLoginManager contains user profile data and can update request parameters and headers in order to apply it.\n */\n public DrupalClient(@NonNull String theBaseURL, @NonNull Context theContext, @Nullable RequestFormat theFormat, @Nullable ILoginManager theLoginManager) {\n this(theBaseURL, getDefaultQueue(theContext), theFormat, theLoginManager);\n }\n\n @SuppressWarnings(\"null\")\n private static\n @NonNull\n RequestQueue getDefaultQueue(@NonNull Context theContext) {\n return Volley.newRequestQueue(theContext.getApplicationContext());\n }\n\n /**\n * @param theBaseURL this URL will be appended with {@link AbstractBaseDrupalEntity#getPath()}\n * @param theQueue queue to execute requests. You can customize cache management, by setting custom queue\n * @param theFormat server request/response format. Defines format of serialized objects and server response format, see {@link com.ls.http.base.BaseRequest.RequestFormat}\n * @param theLoginManager contains user profile data and can update request parameters and headers in order to apply it.\n */\n public DrupalClient(@NonNull String theBaseURL, @NonNull RequestQueue theQueue, @Nullable RequestFormat theFormat, @Nullable ILoginManager theLoginManager) {\n this.listeners = new ResponseListenersSet();\n this.queue = theQueue;\n this.setBaseURL(theBaseURL);\n\n if (theFormat != null) {\n this.requestFormat = theFormat;\n } else {\n this.requestFormat = RequestFormat.JSON;\n }\n\n if (theLoginManager != null) {\n this.setLoginManager(theLoginManager);\n } else {\n this.setLoginManager(new AnonymousLoginManager());\n }\n }\n\n /**\n * @param request Request object to be performed\n * @param synchronous if true request result will be returned synchronously\n * @return {@link com.ls.http.base.ResponseData} object, containing request result code and string or error and deserialized object, specified in request.\n */\n public ResponseData performRequest(BaseRequest request, boolean synchronous) {\n return performRequest(request, null, null, synchronous);\n }\n\n /**\n * @param request Request object to be performed\n * @param tag will be applied to the request and returned in listener\n * @param synchronous if true request result will be returned synchronously\n * @return {@link com.ls.http.base.ResponseData} object, containing request result code and string or error and deserialized object, specified in request.\n */\n public ResponseData performRequest(BaseRequest request, Object tag, final OnResponseListener listener, boolean synchronous) {\n request.setRetryPolicy(new DefaultRetryPolicy(requestTimeout, 1, 1));\n if (!loginManager.shouldRestoreLogin()) {\n return performRequestNoLoginRestore(request, tag, listener, synchronous);\n } else {\n return performRequestLoginRestore(request, tag, listener, synchronous);\n }\n }\n\n protected ResponseData performRequestNoLoginRestore(BaseRequest request, Object tag, OnResponseListener listener, boolean synchronous) {\n request.setTag(tag);\n request.setResponseListener(this);\n this.loginManager.applyLoginDataToRequest(request);\n request.setSmartComparisonEnabled(this.duplicateRequestPolicy !=DuplicateRequestPolicy.ALLOW);\n\n boolean wasRegisterred ;\n boolean skipDuplicateRequestListeners = this.duplicateRequestPolicy == DrupalClient.DuplicateRequestPolicy.REJECT;\n synchronized (listeners) {\n wasRegisterred = this.listeners.registerListenerForRequest(request, listener,tag,skipDuplicateRequestListeners);\n }\n\n if(wasRegisterred||synchronous) {\n this.onNewRequestStarted();\n return request.performRequest(synchronous, queue);\n }else{\n if(skipDuplicateRequestListeners && listener != null)\n {\n listener.onCancel(tag);\n }\n return null;\n }\n }\n\n private ResponseData performRequestLoginRestore(final BaseRequest request, Object tag, final OnResponseListener listener, final boolean synchronous) {\n if (synchronous) {\n return performRequestLoginRestoreSynchrounous(request, tag, listener);\n } else {\n return performRequestLoginRestoreAsynchrounous(request, tag, listener);\n }\n }\n\n private ResponseData performRequestLoginRestoreAsynchrounous(final BaseRequest request, Object tag, final OnResponseListener listener) {\n final OnResponseListener loginRestoreResponseListener = new OnResponseListener() {\n @Override\n public void onResponseReceived(ResponseData data, Object tag) {\n if (listener != null) {\n listener.onResponseReceived(data, tag);\n }\n }\n\n @Override\n public void onError(ResponseData data, Object tag) {\n if (VolleyResponseUtils.isAuthError(data.getError())) {\n if (loginManager.canRestoreLogin()) {\n new RestoreLoginAttemptTask(request, listener, tag, data).execute();\n } else {\n loginManager.onLoginRestoreFailed();\n if (listener != null) {\n listener.onError(data, tag);\n }\n }\n } else {\n if (listener != null) {\n listener.onError(data, tag);\n }\n }\n }\n\n @Override\n public void onCancel(Object tag) {\n if (listener != null) {\n listener.onCancel(tag);\n }\n }\n };\n\n return performRequestNoLoginRestore(request, tag, loginRestoreResponseListener, false);\n }\n\n private ResponseData performRequestLoginRestoreSynchrounous(final BaseRequest request, Object tag, final OnResponseListener listener) {\n final OnResponseListener loginRestoreResponseListener = new OnResponseListener() {\n @Override\n public void onResponseReceived(ResponseData data, Object tag) {\n if (listener != null) {\n listener.onResponseReceived(data, tag);\n }\n }\n\n @Override\n public void onError(ResponseData data, Object tag) {\n if (VolleyResponseUtils.isAuthError(data.getError())) {\n if (!loginManager.canRestoreLogin()) {\n if (listener != null) {\n listener.onError(data, tag);\n }\n }\n } else {\n if (listener != null) {\n listener.onError(data, tag);\n }\n }\n }\n\n @Override\n public void onCancel(Object tag) {\n if (listener != null) {\n listener.onCancel(tag);\n }\n }\n };\n\n ResponseData result = performRequestNoLoginRestore(request, tag, loginRestoreResponseListener, true);\n if (VolleyResponseUtils.isAuthError(result.getError())) {\n if (loginManager.canRestoreLogin()) {\n boolean restored = loginManager.restoreLoginData(queue);\n if (restored) {\n result = performRequestNoLoginRestore(request, tag, new OnResponseAuthListenerDecorator(listener), true);\n } else {\n listener.onError(result, tag);\n }\n } else {\n loginManager.onLoginRestoreFailed();\n }\n }\n return result;\n }\n\n\n /**\n * @param entity Object, specifying request parameters, retrieved data will be merged to this object.\n * @param config Entity, containing additional request parameters\n * @param tag will be attached to request and returned in listener callback, can be used in order to cancel request\n * @param synchronous if true - result will be returned synchronously.\n * @return ResponseData object or null if request was asynchronous.\n */\n public ResponseData getObject(AbstractBaseDrupalEntity entity, RequestConfig config, Object tag, OnResponseListener listener, boolean synchronous) {\n BaseRequest request = new BaseRequest(RequestMethod.GET, getURLForEntity(entity), applyDefaultFormat(config));\n request.setGetParameters(entity.getItemRequestGetParameters(RequestMethod.GET));\n request.addRequestHeaders(entity.getItemRequestHeaders(RequestMethod.GET));\n return this.performRequest(request, tag, listener, synchronous);\n }\n\n /**\n * @param entity Object, specifying request parameters\n * @param config Entity, containing additional request parameters\n * @param tag will be attached to request and returned in listener callback, can be used in order to cancel request\n * @param synchronous if true - result will be returned synchronously.\n * @return ResponseData object or null if request was asynchronous.\n */\n public ResponseData postObject(AbstractBaseDrupalEntity entity, RequestConfig config, Object tag, OnResponseListener listener, boolean synchronous) {\n BaseRequest request = new BaseRequest(RequestMethod.POST, getURLForEntity(entity), applyDefaultFormat(config));\n Map<String, String> postParams = entity.getItemRequestPostParameters();\n if (postParams == null || postParams.isEmpty()) {\n request.setObjectToPost(entity.getManagedData());\n } else {\n request.setPostParameters(postParams);\n }\n request.setGetParameters(entity.getItemRequestGetParameters(RequestMethod.POST));\n request.addRequestHeaders(entity.getItemRequestHeaders(RequestMethod.POST));\n return this.performRequest(request, tag, listener, synchronous);\n }\n\n /**\n * @param entity Object, specifying request parameters\n * @param config Entity, containing additional request parameters\n * @param tag will be attached to request and returned in listener callback, can be used in order to cancel request\n * @param synchronous if true - result will be returned synchronously.\n * @return ResponseData object or null if request was asynchronous.\n */\n public ResponseData putObject(AbstractBaseDrupalEntity entity, RequestConfig config, Object tag, OnResponseListener listener, boolean synchronous) {\n BaseRequest request = new BaseRequest(RequestMethod.PUT, getURLForEntity(entity), applyDefaultFormat(config));\n Map<String, String> postParams = entity.getItemRequestPostParameters();\n if (postParams == null || postParams.isEmpty()) {\n request.setObjectToPost(entity.getManagedData());\n } else {\n request.setPostParameters(postParams);\n }\n request.setGetParameters(entity.getItemRequestGetParameters(RequestMethod.PUT));\n request.addRequestHeaders(entity.getItemRequestHeaders(RequestMethod.PUT));\n return this.performRequest(request, tag, listener, synchronous);\n }\n\n\n /**\n * @param entity Object, specifying request parameters, must have \"createFootPrint\" called before.\n * @param config Entity, containing additional request parameters\n * @param tag will be attached to request and returned in listener callback, can be used in order to cancel request\n * @param synchronous if true - result will be returned synchronously.\n * @return ResponseData object or null if request was asynchronous.\n */\n public ResponseData patchObject(AbstractBaseDrupalEntity entity, RequestConfig config, Object tag, OnResponseListener listener, boolean synchronous) {\n BaseRequest request = new BaseRequest(RequestMethod.PATCH, getURLForEntity(entity), applyDefaultFormat(config));\n request.setGetParameters(entity.getItemRequestGetParameters(RequestMethod.PATCH));\n request.setObjectToPost(entity.getPatchObject());\n request.addRequestHeaders(entity.getItemRequestHeaders(RequestMethod.PATCH));\n return this.performRequest(request, tag, listener, synchronous);\n }\n\n /**\n * @param entity Object, specifying request parameters\n * @param config Entity, containing additional request parameters\n * @param tag will be attached to request and returned in listener callback, can be used in order to cancel request\n * @param synchronous if true - result will be returned synchronously.\n * @return ResponseData object or null if request was asynchronous.\n */\n public ResponseData deleteObject(AbstractBaseDrupalEntity entity, RequestConfig config, Object tag, OnResponseListener listener,\n boolean synchronous) {\n BaseRequest request = new BaseRequest(RequestMethod.DELETE, getURLForEntity(entity), applyDefaultFormat(config));\n request.setGetParameters(entity.getItemRequestGetParameters(RequestMethod.DELETE));\n request.addRequestHeaders(entity.getItemRequestHeaders(RequestMethod.DELETE));\n return this.performRequest(request, tag, listener, synchronous);\n }\n\n /**\n * @return request timeout millis\n */\n public int getRequestTimeout() {\n return requestTimeout;\n }\n\n /**\n * @param requestTimeout request timeout millis\n */\n public void setRequestTimeout(int requestTimeout) {\n this.requestTimeout = requestTimeout;\n }\n\n private RequestConfig applyDefaultFormat(RequestConfig config)\n {\n if(config == null)\n {\n config = new RequestConfig();\n }\n\n if(config.getRequestFormat()==null)\n {\n config.setRequestFormat(this.requestFormat);\n }\n\n return config;\n }\n\n private String getURLForEntity(AbstractBaseDrupalEntity entity) {\n String path = entity.getPath();\n\n if(TextUtils.isEmpty(baseURL))\n {\n return path;\n }else {\n if (!TextUtils.isEmpty(path) && path.charAt(0) == '/') {\n path = path.substring(1);\n }\n return this.baseURL + path;\n }\n }\n\n /**\n * This request is always synchronous and has no callback\n */\n public final Object login(final String userName, final String password) {\n return this.loginManager.login(userName, password, queue);\n }\n\n /**\n * This request is always synchronous\n */\n public final void logout() {\n this.loginManager.logout(queue);\n }\n\n /**\n * @return true all necessary user id data is fetched and login can be restored automatically\n */\n public boolean isLogged() {\n return this.loginManager.canRestoreLogin();\n }\n\n public ILoginManager getLoginManager() {\n return loginManager;\n }\n\n public void setLoginManager(ILoginManager loginManager) {\n this.loginManager = loginManager;\n }\n\n /**\n * Synchronous login restore attempt\n *\n * @return false if login restore failed.\n */\n public boolean restoreLogin() {\n if (this.loginManager.canRestoreLogin()) {\n return this.loginManager.restoreLoginData(queue);\n }\n return false;\n }\n\n @Override\n public void onResponseReceived(ResponseData data, BaseRequest request) {\n synchronized (listeners) {\n List<ResponseListenersSet.ListenerHolder> listenerList = this.listeners.getListenersForRequest(request);\n this.listeners.removeListenersForRequest(request);\n this.onRequestComplete();\n if (listenerList != null) {\n for (ResponseListenersSet.ListenerHolder holder : listenerList) {\n holder.getListener().onResponseReceived(data, holder.getTag());\n }\n }\n }\n }\n\n @Override\n public void onError(ResponseData data, BaseRequest request) {\n synchronized (listeners) {\n List<ResponseListenersSet.ListenerHolder> listenerList = this.listeners.getListenersForRequest(request);\n this.listeners.removeListenersForRequest(request);\n this.onRequestComplete();\n if (listenerList != null) {\n for (ResponseListenersSet.ListenerHolder holder : listenerList) {\n holder.getListener().onError(data, holder.getTag());\n }\n }\n }\n }\n\n /**\n * @return Charset, used to encode/decode server request post body and response.\n */\n public String getDefaultCharset() {\n return defaultCharset;\n }\n\n /**\n * @param defaultCharset Charset, used to encode/decode server request post body and response.\n */\n public void setDefaultCharset(String defaultCharset) {\n this.defaultCharset = defaultCharset;\n }\n\n /**\n * @param tag Cancel all requests, containing given tag. If no tag is specified - all requests are canceled.\n */\n public void cancelByTag(final @NonNull Object tag) {\n this.cancelAllRequestsForListener(null, tag);\n }\n\n /**\n * Cancel all requests\n */\n public void cancelAll() {\n this.cancelAllRequestsForListener(null, null);\n }\n\n /**\n * @return current duplicate request policy\n */\n public DuplicateRequestPolicy getDuplicateRequestPolicy() {\n return duplicateRequestPolicy;\n }\n\n /**\n * Sets duplicate request handling policy according to parameter provided. Only simultaneous requests are compared (executing at the same time).\n * @param duplicateRequestPolicy in case if\n * \"ALLOW\" - all requests are performed\n * \"ATTACH\" - only first unique request from queue will be performed all other listeners will be attached to this request and triggered.\n * \"REJECT\" - only first unique request from queue will be performed and it's listener triggered. \"onCancel()\" listener method will be called for all requests skipped.\n * Default value is \"ALLOW\"\n */\n public void setDuplicateRequestPolicy(DuplicateRequestPolicy duplicateRequestPolicy) {\n this.duplicateRequestPolicy = duplicateRequestPolicy;\n }\n\n /**\n * Cancel all requests for given listener with tag\n *\n * @param theListener listener to cancel requests for in case if null passed- all requests for given tag will be canceled\n * @param theTag to cancel requests for, in case if null passed- all requests for given listener will be canceled\n */\n public void cancelAllRequestsForListener(final @Nullable OnResponseListener theListener, final @Nullable Object theTag) {\n this.queue.cancelAll(new RequestQueue.RequestFilter() {\n @Override\n public boolean apply(Request<?> request) {\n if (theTag == null || theTag.equals(request.getTag())) {\n synchronized (listeners) {\n List<ResponseListenersSet.ListenerHolder> listenerList = listeners.getListenersForRequest(request);\n\n if (theListener == null || (listenerList != null && holderListContainsListener(listenerList,theListener))) {\n if (listenerList != null) {\n listeners.removeListenersForRequest(request);\n for (ResponseListenersSet.ListenerHolder holder : listenerList) {\n holder.getListener().onCancel(holder.getTag());\n }\n DrupalClient.this.onRequestComplete();\n }\n return true;\n }\n }\n }\n\n return false;\n }\n });\n }\n\n protected static boolean holderListContainsListener( List<ResponseListenersSet.ListenerHolder> listenerList,OnResponseListener theListener)\n {\n if(theListener == null)\n {\n return false;\n }\n\n boolean listContainsListener = false;\n for(ResponseListenersSet.ListenerHolder holder:listenerList)\n {\n if(theListener.equals(holder.getListener()))\n {\n listContainsListener = true;\n }\n }\n\n return listContainsListener;\n }\n\n // Manage request progress\n\n /**\n * @return number of requests pending\n */\n public int getActiveRequestsCount() {\n synchronized (listeners) {\n return this.listeners.registeredRequestCount();\n }\n }\n\n public RequestProgressListener getProgressListener() {\n return progressListener;\n }\n\n public void setProgressListener(RequestProgressListener progressListener) {\n this.progressListener = progressListener;\n }\n\n public void setBaseURL(String theBaseURL) {\n if (!TextUtils.isEmpty(theBaseURL) && theBaseURL.charAt(theBaseURL.length() - 1) != '/') {\n theBaseURL += '/';\n }\n ;\n this.baseURL = theBaseURL;\n }\n\n public String getBaseURL() {\n return baseURL;\n }\n\n\n private void onNewRequestStarted() {\n if (this.progressListener != null) {\n\n int requestCount = this.getActiveRequestsCount();\n this.progressListener.onRequestStarted(this, requestCount);\n\n }\n }\n\n private void onRequestComplete() {\n if (this.progressListener != null) {\n int requestCount = this.getActiveRequestsCount();\n this.progressListener.onRequestFinished(this, requestCount);\n }\n }\n\n private class OnResponseAuthListenerDecorator implements OnResponseListener {\n\n private OnResponseListener listener;\n\n OnResponseAuthListenerDecorator(OnResponseListener listener) {\n this.listener = listener;\n }\n\n @Override\n public void onResponseReceived(ResponseData data, Object tag) {\n if (listener != null) {\n this.listener.onResponseReceived(data, tag);\n }\n }\n\n @Override\n public void onError(ResponseData data, Object tag) {\n if (VolleyResponseUtils.isAuthError(data.getError())) {\n loginManager.onLoginRestoreFailed();\n }\n if (listener != null) {\n this.listener.onError(data, tag);\n }\n }\n\n @Override\n public void onCancel(Object tag) {\n if (listener != null) {\n this.listener.onCancel(tag);\n }\n }\n }\n\n private class RestoreLoginAttemptTask {\n\n private final BaseRequest request;\n private final OnResponseListener listener;\n private final Object tag;\n private final ResponseData originData;\n\n RestoreLoginAttemptTask(BaseRequest request, OnResponseListener listener, Object tag, ResponseData originData) {\n this.request = request;\n this.listener = listener;\n this.tag = tag;\n this.originData = originData;\n }\n\n public void execute() {\n new Thread() {\n @Override\n public void run() {\n\n boolean restored = loginManager.restoreLoginData(queue);\n if (restored) {\n performRequestNoLoginRestore(request, tag, new OnResponseAuthListenerDecorator(listener), false);\n } else {\n listener.onError(originData, tag);\n }\n }\n }.start();\n }\n }\n\n}",
"public class ArticlePreview {\n\n\tprivate String nid;\n\tprivate String title;\n\tprivate String field_blog_date;\n\tprivate String field_image;\n\tprivate String field_blog_author;\n\tprivate String field_blog_category;\n\tprivate String body;\n\n\tpublic String getNid() {\n\t\treturn nid;\n\t}\n\n\tpublic String getTitle() {\n\t\treturn title;\n\t}\n\n\tpublic String getDate() {\n\t\treturn field_blog_date;\n\t}\n\n\tpublic String getAuthor() {\n\t\treturn field_blog_author;\n\t}\n\n\tpublic String getBody() {\n\t\treturn body;\n\t}\n\n\tpublic String getImage() {\n\t\treturn ModelUtils.trimImageURL(this.field_image);\n\t}\n\n\tpublic String getCategory() {\n\t\treturn field_blog_category;\n\t}\n}",
"public class Page extends AbstractDrupalArrayEntity<ArticlePreview> {\n\n\ttransient private int mPageNumber;\n\ttransient private String mCategoryId;\n\n\tpublic Page(DrupalClient client, int thePageNumber, String theCategoryId) {\n\t\tsuper(client, 5);\n\t\tmPageNumber = thePageNumber;\n\t\tmCategoryId = theCategoryId;\n\t}\n\n\t@Override\n\tpublic String getPath() {\n\t\tif (mCategoryId == null) {\n\t\t\treturn \"blog-rest\";\n\t\t} else {\n\t\t\treturn \"category/\" + mCategoryId;\n\t\t}\n\t}\n\n\t@Override\n\tprotected Map<String, String> getItemRequestPostParameters() {\n\t\treturn null;\n\t}\n\n\t@Override\n\tprotected Map<String, Object> getItemRequestGetParameters(RequestMethod method) {\n\t\tswitch (method) {\n\t\t\tcase GET:\n\t\t\t\tMap<String, Object> result = new HashMap<String, Object>();\n\t\t\t\tresult.put(\"page\", Integer.toString(mPageNumber));\n\t\t\t\treturn result;\n\t\t\tdefault:\n\t\t\t\treturn null;\n\t\t}\n\t}\n\n\tpublic int getPageNumber() {\n\t\treturn mPageNumber;\n\t}\n\n}",
"public class ResponseData {\n\tprotected Object data;\n\tprotected Map<String, String> headers;\n\tprotected int statusCode;\n\tprotected VolleyError error;\n protected Object parsedErrorResponse;\n\n\t\n\t/**\t \n\t * @return Instance of class, specified in response or null if no such class was specified.\n\t */\n\tpublic Object getData() {\n\t\treturn data;\n\t}\n\n\tpublic Map<String, String> getHeaders() {\n\t\treturn headers;\n\t}\n\n\tpublic int getStatusCode() {\n\t\treturn statusCode;\n\t}\n\n\tpublic VolleyError getError() {\n\t\treturn error;\n\t}\n\n /**\n *\n * @return parsed error response is errorResponseSpecifier was provided and error received.\n */\n public Object getParsedErrorResponse() {\n return parsedErrorResponse;\n }\n\n public void cloneTo(ResponseData target)\n {\n target.data = data;\n target.headers = headers;\n target.statusCode = statusCode;\n target.error = error;\n target.parsedErrorResponse = parsedErrorResponse;\n }\n\n}",
"public final class L {\n\n\tpublic static String LOG_TAG = \"Drupal 8 Android SDK\";\n\n\tstatic {\n\t\tThread.setDefaultUncaughtExceptionHandler(new DefaultUncaughtExceptionHandler());\n\t}\n\n\tstatic class DefaultUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {\n\n\t\tprivate Thread.UncaughtExceptionHandler defaultUEH;\n\n\t\tpublic DefaultUncaughtExceptionHandler() {\n\t\t\tthis.defaultUEH = Thread.getDefaultUncaughtExceptionHandler();\n\t\t}\n\n\t\t@Override\n\t\tpublic void uncaughtException(Thread thread, Throwable cause) {\n\t\t\tL.e(\"UncaughtException\", cause);\n\t\t\tdefaultUEH.uncaughtException(thread, cause);\n\t\t}\n\t}\n\n\t/**\n\t * <p><b>ERROR:</b> This level of logging should be used when something fatal has happened, i.e. something that will\n\t * have user-visible consequences and won't be recoverable without explicitly deleting some data, uninstalling\n\t * applications, wiping the data partitions or reflashing the entire phone (or worse). Issues that justify some\n\t * logging at the ERROR level are typically good candidates to be reported to a statistics-gathering server.</p>\n\t *\n\t * <p><b>This level is always logged.</b></p>\n\t */\n\tpublic static void e(String message, Throwable cause) {\n\t\tLog.e(LOG_TAG, \"[\" + message + \"]\", cause);\n\t}\n\n\t/**\n\t * @see #e(String, Throwable)\n\t */\n\tpublic static void e(String msg) {\n\t\tThrowable t = new Throwable();\n\t\tStackTraceElement[] elements = t.getStackTrace();\n\n\t\tString callerClassName = elements[1].getFileName();\n\t\tLog.e(LOG_TAG, \"[\" + callerClassName + \"] \" + msg);\n\t}\n\n\t/**\n\t * <p><b>WARNING:</b> This level of logging should used when something serious and unexpected happened, i.e.\n\t * something that will have user-visible consequences but is likely to be recoverable without data loss by\n\t * performing some explicit action, ranging from waiting or restarting an app all the way to re-downloading a new\n\t * version of an application or rebooting the device. Issues that justify some logging at the WARNING level might\n\t * also be considered for reporting to a statistics-gathering server.</p>\n\t *\n\t * <p><b>This level is always logged.</b></p>\n\t */\n\tpublic static void w(String message, Throwable cause) {\n\t\tLog.w(LOG_TAG, \"[\" + message + \"]\", cause);\n\t}\n\n\t/**\n\t * @see #w(String, Throwable)\n\t */\n\tpublic static void w(String msg) {\n\t\tThrowable t = new Throwable();\n\t\tStackTraceElement[] elements = t.getStackTrace();\n\n\t\tString callerClassName = elements[1].getFileName();\n\t\tLog.w(LOG_TAG, \"[\" + callerClassName + \"] \" + msg);\n\t}\n\n\t/**\n\t * @see #w(String, Throwable)\n\t */\n\tpublic static void w(Throwable cause) {\n\t\tLog.w(LOG_TAG, cause);\n\t}\n\n\t/**\n\t * <p><b>INFORMATIVE:</b> This level of logging should used be to note that something interesting to most people\n\t * happened, i.e. when a situation is detected that is likely to have widespread impact, though isn't necessarily an\n\t * error. Such a condition should only be logged by a module that reasonably believes that it is the most\n\t * authoritative in that domain (to avoid duplicate logging by non-authoritative components).</p>\n\t *\n\t * <p><b>This level is always logged.</b></p>\n\t */\n\tpublic static void i(String message, Throwable cause) {\n\t\tLog.i(LOG_TAG, \"[\" + message + \"]\", cause);\n\t}\n\n\t/**\n\t * @see #i(String, Throwable)\n\t */\n\tpublic static void i(String msg) {\n\t\tThrowable t = new Throwable();\n\t\tStackTraceElement[] elements = t.getStackTrace();\n\n\t\tString callerClassName = elements[1].getFileName();\n\t\tLog.i(LOG_TAG, \"[\" + callerClassName + \"] \" + msg);\n\t}\n\n\t/**\n\t * <p><b>DEBUG:</b> This level of logging should be used to further note what is happening on the device that could\n\t * be relevant to investigate and debug unexpected behaviors. You should log only what is needed to gather enough\n\t * information about what is going on about your component. If your debug logs are dominating the log then you\n\t * probably should be using verbose logging.</p>\n\t *\n\t * <p><b>This level is NOT logged in release build.</b></p>\n\t */\n\tpublic static void d(String msg, Throwable cause) {\n\t\tif (BuildConfig.DEBUG) {\n\t\t\tLog.d(LOG_TAG, msg, cause);\n\t\t}\n\t}\n\n\t/**\n\t * @see #d(String, Throwable)\n\t */\n\tpublic static void d(String msg) {\n\t\tif (BuildConfig.DEBUG) {\n\t\t\tThrowable t = new Throwable();\n\t\t\tStackTraceElement[] elements = t.getStackTrace();\n\n\t\t\tString callerClassName = elements[1].getFileName();\n\t\t\tLog.d(LOG_TAG, \"[\" + callerClassName + \"] \" + msg);\n\t\t}\n\t}\n\n\t/**\n\t * <p><b>VERBOSE:</b> This level of logging should be used for everything else.</p>\n\t *\n\t * <p><b>This level is NOT logged in release build.</b></p>\n\t */\n\tpublic static void v(String msg, Throwable cause) {\n\t\tif (BuildConfig.DEBUG) {\n\t\t\tLog.v(LOG_TAG, msg, cause);\n\t\t}\n\t}\n\n\t/**\n\t * @see #v(String, Throwable)\n\t */\n\tpublic static void v(String msg) {\n\t\tif (BuildConfig.DEBUG) {\n\t\t\tThrowable t = new Throwable();\n\t\t\tStackTraceElement[] elements = t.getStackTrace();\n\n\t\t\tString callerClassName = elements[1].getFileName();\n\t\t\tLog.v(LOG_TAG, \"[\" + callerClassName + \"] \" + msg);\n\t\t}\n\t}\n\n}",
"public class DrupalImageView extends ImageView {\n\n private static DrupalClient sharedClient;\n\n private static DrupalClient getSharedClient(Context context)\n {\n synchronized (DrupalImageView.class) {\n if (sharedClient == null) {\n sharedClient = new DrupalClient(null, context);\n }\n }\n\n return sharedClient;\n }\n\n /**\n * Use this method to provide default drupal client, used by all image views.\n * @param client to be used in order to load images.\n */\n public static void setupSharedClient(DrupalClient client)\n {\n synchronized (DrupalImageView.class) {\n DrupalImageView.sharedClient = client;\n }\n }\n\n private DrupalClient localClient;\n\n private ImageContainer imageContainer;\n\n private Drawable noImageDrawable;\n\n private ImageLoadingListener imageLoadingListener;\n\n private boolean fixedBounds;\n\n public DrupalImageView(Context context) {\n super(context);\n initView(context,null);\n }\n\n public DrupalImageView(Context context, AttributeSet attrs) {\n this(context, attrs, 0);\n }\n\n public DrupalImageView(Context context, AttributeSet attrs, int defStyle) {\n super(context, attrs, defStyle);\n initView(context,attrs);\n }\n\n public void initView(Context context, AttributeSet attrs)\n {\n if (this.isInEditMode()) {\n return;\n }\n TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.DrupalImageView);\n\n Drawable noImageDrawable = array.getDrawable(R.styleable.DrupalImageView_noImageResource);\n if (noImageDrawable != null) {\n this.setNoImageDrawable(noImageDrawable);\n }\n\n String imagePath = array.getString(R.styleable.DrupalImageView_srcPath);\n if (!TextUtils.isEmpty(imagePath)) {\n this.setImageWithURL(imagePath);\n }\n\n this.fixedBounds = array.getBoolean(R.styleable.DrupalImageView_fixedBounds,false);\n\n array.recycle();\n }\n\n public void setImageWithURL(String imagePath)\n {\n if (this.isInEditMode()) {\n return;\n }\n\n DrupalClient client = this.getClient();\n if(client == null)\n {\n throw new IllegalStateException(\"No DrupalClient set. Please provide local or shared DrupalClient to perform loading\");\n }\n\n if(this.imageContainer != null && this.imageContainer.url.equals(imagePath))\n {\n return;\n }\n\n this.setImageDrawable(null);\n this.applyNoImageDrawableIfNeeded();\n\n if(TextUtils.isEmpty(imagePath))\n {\n return;\n }\n\n this.imageContainer = new ImageContainer(imagePath,client);\n this.startLoading();\n }\n\n public String getImageURL()\n {\n if(this.imageContainer!= null)\n {\n return this.imageContainer.url;\n }\n return null;\n }\n\n @Override\n public void setImageDrawable(Drawable drawable) {\n cancelLoading();\n this.imageContainer = null;\n superSetImageDrawable(drawable);\n }\n\n\n /**\n * Layout update skipping workaround\n */\n private boolean skipLayoutUpdate = false;\n /**\n * Layout update skipping workaround\n */\n protected void superSetDrawableSkippingLayoutUpdate(Drawable drawable)\n {\n if(fixedBounds) {\n skipLayoutUpdate = true;\n superSetImageDrawable(drawable);\n skipLayoutUpdate = false;\n }else{\n superSetImageDrawable(drawable);\n }\n }\n\n /**\n * Layout update skipping workaround\n */\n @Override\n public void requestLayout() {\n if(!skipLayoutUpdate) {\n super.requestLayout();\n }\n }\n\n /**\n * Method is calling original ImageView setDrawable method directly\n * @param drawable\n */\n protected void superSetImageDrawable(Drawable drawable) {\n super.setImageDrawable(drawable);\n }\n\n public Drawable getNoImageDrawable() {\n return noImageDrawable;\n }\n\n public void setNoImageDrawableResource(int resource)\n {\n this.setImageDrawable(this.getContext().getResources().getDrawable(resource));\n }\n\n public void setNoImageDrawable(Drawable noImageDrawable) {\n if(this.noImageDrawable != noImageDrawable) {\n if(this.getDrawable()==this.noImageDrawable)\n {\n superSetImageDrawable(noImageDrawable);\n }\n this.noImageDrawable = noImageDrawable;\n }\n }\n\n public ImageLoadingListener getImageLoadingListener() {\n return imageLoadingListener;\n }\n\n public void setImageLoadingListener(ImageLoadingListener imageLoadingListener) {\n this.imageLoadingListener = imageLoadingListener;\n }\n\n\n public DrupalClient getLocalClient() {\n return localClient;\n }\n\n public void setLocalClient(DrupalClient localClient) {\n this.localClient = localClient;\n }\n\n public void cancelLoading()\n {\n if(this.imageContainer != null)\n {\n this.imageContainer.cancelLoad();\n }\n }\n\n public void startLoading()\n {\n if(this.imageContainer != null)\n {\n this.imageContainer.loadImage(getInternalImageLoadingListenerForContainer(this.imageContainer));\n }\n }\n\n /**\n * @return true if drawable bounds are predefined and there is no need in onLayout call after drawable loading is complete\n */\n public boolean isFixedBounds() {\n return fixedBounds;\n }\n\n /**\n * @param fixedBounds if true drawable bounds are predefined and there is no need in onLayout call after drawable loading is complete\n */\n public void setFixedBounds(boolean fixedBounds) {\n this.fixedBounds = fixedBounds;\n }\n\n @Override\n protected void onDetachedFromWindow() {\n super.onDetachedFromWindow();\n this.cancelLoading();\n }\n//\n// @Override\n// protected void onAttachedToWindow() {\n// super.onAttachedToWindow();\n// this.startLoading();\n// }\n\n protected void applyNoImageDrawableIfNeeded()\n {\n if(this.getDrawable()==null)\n {\n superSetDrawableSkippingLayoutUpdate(noImageDrawable);\n }\n }\n\n private DrupalClient getClient()\n {\n if(this.localClient != null)\n {\n return this.localClient;\n }\n\n return DrupalImageView.getSharedClient(this.getContext());\n }\n\n private InternalImageLoadingListener getInternalImageLoadingListenerForContainer(ImageContainer container)\n {\n return new InternalImageLoadingListener(container.url);\n }\n\n private static class ImageContainer\n {\n DrupalImageEntity image;\n String url;\n DrupalClient client;\n\n ImageContainer(String url,DrupalClient client)\n {\n this.url = url;\n this.client = client;\n image = new DrupalImageEntity(client);\n image.setImagePath(url);\n }\n\n void cancelLoad()\n {\n image.cancellAllRequests();\n }\n\n void loadImage(InternalImageLoadingListener listener)\n {\n if(image.getManagedData() == null) {\n image.pullFromServer(false, url, listener);\n }\n }\n }\n\n private class InternalImageLoadingListener implements AbstractBaseDrupalEntity.OnEntityRequestListener\n {\n private String acceptableURL;\n InternalImageLoadingListener(String url)\n {\n this.acceptableURL = url;\n }\n\n @Override\n public void onRequestCompleted(AbstractBaseDrupalEntity entity, Object tag, ResponseData data) {\n Drawable image = ((DrupalImageEntity) entity).getManagedData();\n if(checkCurrentURL())\n {\n superSetDrawableSkippingLayoutUpdate(image);\n applyNoImageDrawableIfNeeded();\n }\n\n if(imageLoadingListener != null)\n {\n imageLoadingListener.onImageLoadingComplete(DrupalImageView.this,image);\n }\n }\n\n @Override\n public void onRequestFailed(AbstractBaseDrupalEntity entity, Object tag, ResponseData data) {\n if(checkCurrentURL()) {\n applyNoImageDrawableIfNeeded();\n }\n if(imageLoadingListener != null)\n {\n imageLoadingListener.onImageLoadingFailed(DrupalImageView.this, data);\n }\n }\n\n @Override\n public void onRequestCanceled(AbstractBaseDrupalEntity entity, Object tag) {\n if(checkCurrentURL()) {\n applyNoImageDrawableIfNeeded();\n }\n if(imageLoadingListener != null)\n {\n imageLoadingListener.onImageLoadingCancelled(DrupalImageView.this, this.acceptableURL);\n }\n }\n\n private boolean checkCurrentURL()\n {\n return imageContainer != null && imageContainer.url != null && imageContainer.url.equals(acceptableURL);\n }\n }\n\n public static interface ImageLoadingListener{\n void onImageLoadingComplete(DrupalImageView view, Drawable image);\n void onImageLoadingFailed(DrupalImageView view,ResponseData data);\n void onImageLoadingCancelled(DrupalImageView view,String path);\n }\n\n}"
] | import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageLoader.ImageCache;
import com.android.volley.toolbox.Volley;
import com.ls.drupal.AbstractBaseDrupalEntity;
import com.ls.drupal.AbstractBaseDrupalEntity.OnEntityRequestListener;
import com.ls.drupal.DrupalClient;
import com.ls.drupal8demo.R;
import com.ls.drupal8demo.article.ArticlePreview;
import com.ls.drupal8demo.article.Page;
import com.ls.http.base.ResponseData;
import com.ls.util.L;
import com.ls.util.image.DrupalImageView;
import android.content.Context;
import android.graphics.Bitmap;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List; | /**
* The MIT License (MIT)
* Copyright (c) 2014 Lemberg Solutions Limited
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.ls.drupal8demo.adapters;
public class CategoryArticlesListAdapter extends BaseAdapter implements OnEntityRequestListener {
private final static int PRE_LOADING_PAGE_OFFSET = 4;
private int mPagesLoaded = 0;
private boolean mCanLoadMore;
private Page mArticlePreviews;
private final DrupalClient mDrupalClient;
private final LayoutInflater mInflater;
private ImageLoader mImageLoader;
private String mCategoryId;
private View mEmptyView;
private final List<ArticlePreview> mArticlePreviewList;
public CategoryArticlesListAdapter(String theCategoryId, DrupalClient theClient, Context theContext,
View emptyView) {
mEmptyView = emptyView;
mArticlePreviewList = new ArrayList<ArticlePreview>();
mInflater = LayoutInflater.from(theContext);
mDrupalClient = theClient;
setCanLoadMore(true);
mCategoryId = theCategoryId;
initImageLoader(theContext);
loadNextPage();
}
private void initImageLoader(Context theContext) {
RequestQueue queue = Volley.newRequestQueue(theContext);
mImageLoader = new ImageLoader(queue, new ImageCache() {
@Override
public void putBitmap(String url, Bitmap bitmap) {
}
@Override
public Bitmap getBitmap(String url) {
return null;
}
});
}
@Override
public int getCount() {
return mArticlePreviewList.size();
}
@Override
public ArticlePreview getItem(int position) {
return mArticlePreviewList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
public void setCanLoadMore(boolean canLoadMore) {
mCanLoadMore = canLoadMore;
if (!mCanLoadMore && mArticlePreviewList.isEmpty()) {
mEmptyView.setVisibility(View.VISIBLE);
} else {
mEmptyView.setVisibility(View.INVISIBLE);
}
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (position > mArticlePreviewList.size() - PRE_LOADING_PAGE_OFFSET) {
loadNextPage();
}
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item_article, null);
}
ArticlePreview item = mArticlePreviewList.get(position);
if (item != null) {
TextView title = (TextView) convertView.findViewById(R.id.title);
title.setText(Html.fromHtml(item.getTitle()).toString());
TextView author = (TextView) convertView.findViewById(R.id.author);
View byView = convertView.findViewById(R.id.by);
String authorName = item.getAuthor();
if (authorName != null && !authorName.isEmpty()) {
author.setText(authorName);
byView.setVisibility(View.VISIBLE);
author.setVisibility(View.VISIBLE);
} else {
byView.setVisibility(View.INVISIBLE);
author.setVisibility(View.INVISIBLE);
}
TextView date = (TextView) convertView.findViewById(R.id.date);
date.setText(item.getDate());
TextView description = (TextView) convertView.findViewById(R.id.description);
String body = item.getBody();
CharSequence spannedBody = null;
if(body != null)
{
spannedBody = Html.fromHtml(body);
}
description.setText(spannedBody);
| DrupalImageView imageView = (DrupalImageView) convertView.findViewById(R.id.image); | 7 |
tecsinapse/tecsinapse-data-io | src/main/java/br/com/tecsinapse/dataio/type/FileType.java | [
"public static final String MIME_XLS = \"application/vnd.ms-excel\";",
"public static final String MIME_XLSM = \"application/vnd.ms-excel.sheet.macroEnabled.12\";",
"public static final String MIME_XLSX = \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\";",
"public static final String MSG_IGNORED = \"Ignored\";",
"@Slf4j\n@UtilityClass\npublic final class ExporterDateUtils {\n\n private static final Date DATETIME_BIGBANG_PLUS_24H = new Date(-2208977612000L);\n private static final String TIME_ISO_FORMAT = \"HH:mm:ss\";\n private static final String DATE_ISO_FORMAT = \"yyyy-MM-dd\";\n private static final String DATETIME_ISO_FORMAT = \"yyyy-MM-dd'T'HH:mm:ss\";\n private static final String DATETIME_FILE_FORMAT = \"yyyy-MM-dd_HH-mm\";\n\n public static DateType getDateType(Date date) {\n if (date == null) {\n return DateType.NO_DATE;\n }\n if (date instanceof java.sql.Date) {\n return DateType.DATE;\n }\n if (DATETIME_BIGBANG_PLUS_24H.after(date)) {\n return DateType.TIME;\n }\n\n if (isTimeFieldEqualZero(date)) {\n return DateType.DATE;\n }\n return DateType.DATETIME;\n }\n\n private static boolean isTimeFieldEqualZero(Date date) {\n Calendar calendar = Calendar.getInstance();\n calendar.setTime(date);\n return calendar.get(Calendar.SECOND) == 0 && calendar.get(Calendar.MINUTE) == 0 && calendar.get(Calendar.HOUR) == 0;\n }\n\n public static String formatWithIsoByDateType(Date date) {\n DateType dateType = getDateType(date);\n if (dateType == DateType.NO_DATE) {\n return null;\n }\n if (dateType == DateType.TIME) {\n return formatDate(TIME_ISO_FORMAT, date);\n }\n if (dateType == DateType.DATE) {\n return formatDate(DATE_ISO_FORMAT, date);\n }\n return formatDate(DATETIME_ISO_FORMAT, date);\n }\n\n public static String formatAsFileDateTime(Date date) {\n return formatDate(DATETIME_FILE_FORMAT, date);\n }\n\n public static Date parseDate(String strDate) {\n if (strDate == null) {\n return null;\n }\n try {\n return new SimpleDateFormat(DATETIME_ISO_FORMAT).parse(strDate);\n } catch (ParseException e) {\n log.error(\"Parse date '{}' error.\", strDate, e);\n return null;\n }\n }\n\n public enum DateType {\n TIME, DATE, DATETIME, NO_DATE\n }\n\n private static String formatDate(String format, Date date) {\n return new SimpleDateFormat(format).format(date);\n }\n\n}"
] | import static br.com.tecsinapse.dataio.util.Constants.MIME_XLS;
import static br.com.tecsinapse.dataio.util.Constants.MIME_XLSM;
import static br.com.tecsinapse.dataio.util.Constants.MIME_XLSX;
import static br.com.tecsinapse.dataio.util.Constants.MSG_IGNORED;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import lombok.AllArgsConstructor;
import lombok.Getter;
import br.com.tecsinapse.dataio.util.ExporterDateUtils; | /*
* Tecsinapse Data Input and Output
*
* License: GNU Lesser General Public License (LGPL), version 3 or later
* See the LICENSE file in the root directory or <http://www.gnu.org/licenses/lgpl-3.0.html>.
*/
package br.com.tecsinapse.dataio.type;
@Getter
@AllArgsConstructor
public enum FileType {
| XLS("MS Excel file (.xls)", MIME_XLS, ".xls") { | 0 |
cloud-software-foundation/c5-replicator | c5-replicator-log/src/test/java/c5db/log/LogFileServiceTest.java | [
"public class C5CommonTestUtil {\n protected static final Logger LOG = LoggerFactory.getLogger(C5CommonTestUtil.class);\n\n public C5CommonTestUtil() {\n }\n\n /**\n * System property key to get base test directory value\n */\n public static final String BASE_TEST_DIRECTORY_KEY =\n \"test.build.data.basedirectory\";\n\n /**\n * Default base directory for test output.\n */\n public static final String DEFAULT_BASE_TEST_DIRECTORY = \"target/test-data\";\n\n /**\n * Directory where we put the data for this instance of C5CommonTestUtil\n */\n private File dataTestDir = null;\n\n /**\n * @return Where to write test data on local filesystem, specific to\n * the test. Useful for tests that do not use a cluster.\n * Creates it if it does not exist already.\n */\n public Path getDataTestDir() {\n if (this.dataTestDir == null) {\n setupDataTestDir();\n }\n return Paths.get(this.dataTestDir.getAbsolutePath());\n }\n\n /**\n * @param subdirName Test subdir name\n * @return Path to a subdirectory named <code>subdirName</code> under\n * {@link #getDataTestDir()}.\n * Does *NOT* create it if it does not exist.\n */\n public Path getDataTestDir(final String subdirName) {\n return Paths.get(getDataTestDir().toString(), subdirName);\n }\n\n /**\n * Sets up a directory for a test to use.\n *\n * @return New directory path, if created.\n */\n protected Path setupDataTestDir() {\n if (this.dataTestDir != null) {\n LOG.warn(\"Data test dir already setup in \" +\n dataTestDir.getAbsolutePath());\n return null;\n }\n\n String randomStr = UUID.randomUUID().toString();\n Path testPath = Paths.get(getBaseTestDir().toString(), randomStr);\n\n this.dataTestDir = new File(testPath.toString()).getAbsoluteFile();\n // Set this property so if mapreduce jobs run, they will use this as their home dir.\n System.setProperty(\"test.build.dir\", this.dataTestDir.toString());\n if (deleteOnExit()) {\n this.dataTestDir.deleteOnExit();\n }\n\n createSubDir(\"c5.local.dir\", testPath, \"c5-local-dir\");\n\n return testPath;\n }\n\n protected void createSubDir(String propertyName, Path parent, String subDirName) {\n Path newPath = Paths.get(parent.toString(), subDirName);\n File newDir = new File(newPath.toString()).getAbsoluteFile();\n if (deleteOnExit()) {\n newDir.deleteOnExit();\n }\n }\n\n /**\n * @return True if we should delete testing dirs on exit.\n */\n boolean deleteOnExit() {\n String v = System.getProperty(\"c5.testing.preserve.testdir\");\n // Let default be true, to delete on exit.\n return v == null || !Boolean.parseBoolean(v);\n }\n\n /**\n * @return True if we removed the test dirs\n * @throws java.io.IOException\n */\n public boolean cleanupTestDir() throws IOException {\n if (deleteDir(this.dataTestDir)) {\n this.dataTestDir = null;\n return true;\n }\n return false;\n }\n\n /**\n * @param subdir Test subdir name.\n * @return True if we removed the test dir\n * @throws java.io.IOException\n */\n boolean cleanupTestDir(final String subdir) throws IOException {\n if (this.dataTestDir == null) {\n return false;\n }\n return deleteDir(new File(this.dataTestDir, subdir));\n }\n\n /**\n * @return Where to write test data on local filesystem; usually\n * {@link #DEFAULT_BASE_TEST_DIRECTORY}\n * Should not be used by the unit tests, hence it's private.\n * Unit test will use a subdirectory of this directory.\n * @see #setupDataTestDir()\n */\n private Path getBaseTestDir() {\n String PathName = System.getProperty(\n BASE_TEST_DIRECTORY_KEY, DEFAULT_BASE_TEST_DIRECTORY);\n\n return Paths.get(PathName);\n }\n\n /**\n * @param dir Directory to delete\n * @return True if we deleted it.\n * @throws java.io.IOException\n */\n boolean deleteDir(final File dir) throws IOException {\n if (dir == null || !dir.exists()) {\n return true;\n }\n try {\n if (deleteOnExit()) {\n Files.delete(dir.toPath());\n }\n return true;\n } catch (IOException ex) {\n LOG.warn(\"Failed to delete \" + dir.getAbsolutePath());\n return false;\n }\n }\n}",
"public final class QuorumConfiguration {\n\n public final boolean isTransitional;\n\n private final Set<Long> allPeers;\n private final Set<Long> prevPeers;\n private final Set<Long> nextPeers;\n\n public static final QuorumConfiguration EMPTY = new QuorumConfiguration(new HashSet<>());\n\n public static QuorumConfiguration of(Collection<Long> peerCollection) {\n return new QuorumConfiguration(peerCollection);\n }\n\n public static QuorumConfiguration fromProtostuff(c5db.replication.generated.QuorumConfigurationMessage message) {\n if (message.getTransitional()) {\n return new QuorumConfiguration(message.getPrevPeersList(), message.getNextPeersList());\n } else {\n return new QuorumConfiguration(message.getAllPeersList());\n }\n }\n\n public QuorumConfiguration getTransitionalConfiguration(Collection<Long> newPeerCollection) {\n if (isTransitional) {\n return new QuorumConfiguration(prevPeers, newPeerCollection);\n } else {\n return new QuorumConfiguration(allPeers, newPeerCollection);\n }\n }\n\n public QuorumConfiguration getCompletedConfiguration() {\n assert isTransitional;\n\n return new QuorumConfiguration(nextPeers);\n }\n\n public QuorumConfigurationMessage toProtostuff() {\n return new QuorumConfigurationMessage(\n isTransitional,\n Lists.newArrayList(allPeers),\n Lists.newArrayList(prevPeers),\n Lists.newArrayList(nextPeers));\n }\n\n public Set<Long> allPeers() {\n return allPeers;\n }\n\n public Set<Long> prevPeers() {\n return prevPeers;\n }\n\n public Set<Long> nextPeers() {\n return nextPeers;\n }\n\n public boolean isEmpty() {\n return allPeers.size() == 0\n && prevPeers.size() == 0\n && nextPeers.size() == 0;\n }\n\n /**\n * Determine if the peers in sourceSet include a majority of the peers in this configuration.\n */\n public boolean setContainsMajority(Set<Long> sourceSet) {\n if (isTransitional) {\n return setComprisesMajorityOfAnotherSet(sourceSet, prevPeers)\n && setComprisesMajorityOfAnotherSet(sourceSet, nextPeers);\n } else {\n return setComprisesMajorityOfAnotherSet(sourceSet, allPeers);\n }\n }\n\n /**\n * Given a map which tells the last acknowledged entry index for different peers, find the maximum\n * index value which is less than or equal to a majority of this configuration's peers' indexes.\n */\n public long calculateCommittedIndex(Map<Long, Long> peersLastAckedIndex) {\n if (isTransitional) {\n return Math.min(\n getGreatestIndexCommittedByMajority(prevPeers, peersLastAckedIndex),\n getGreatestIndexCommittedByMajority(nextPeers, peersLastAckedIndex));\n } else {\n return getGreatestIndexCommittedByMajority(allPeers, peersLastAckedIndex);\n }\n }\n\n\n private QuorumConfiguration(Collection<Long> peers) {\n this.isTransitional = false;\n allPeers = ImmutableSet.copyOf(peers);\n prevPeers = nextPeers = ImmutableSet.of();\n }\n\n private QuorumConfiguration(Collection<Long> prevPeers, Collection<Long> nextPeers) {\n this.isTransitional = true;\n this.prevPeers = ImmutableSet.copyOf(prevPeers);\n this.nextPeers = ImmutableSet.copyOf(nextPeers);\n this.allPeers = Sets.union(this.prevPeers, this.nextPeers).immutableCopy();\n }\n\n\n private static long getGreatestIndexCommittedByMajority(Set<Long> peers, Map<Long, Long> peersLastAckedIndex) {\n SortedMultiset<Long> committedIndexes = TreeMultiset.create();\n committedIndexes.addAll(peers.stream().map(peerId\n -> peersLastAckedIndex.getOrDefault(peerId, 0L)).collect(Collectors.toList()));\n return Iterables.get(committedIndexes.descendingMultiset(), calculateNumericalMajority(peers.size()) - 1);\n }\n\n private static <T> boolean setComprisesMajorityOfAnotherSet(Set<T> sourceSet, Set<T> destinationSet) {\n return Sets.intersection(sourceSet, destinationSet).size() >= calculateNumericalMajority(destinationSet.size());\n }\n\n private static int calculateNumericalMajority(int setSize) {\n return (setSize / 2) + 1;\n }\n\n @Override\n public String toString() {\n return \"QuorumConfiguration{\" +\n \"isTransitional=\" + isTransitional +\n \", allPeers=\" + allPeers +\n \", prevPeers=\" + prevPeers +\n \", nextPeers=\" + nextPeers +\n '}';\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n\n QuorumConfiguration that = (QuorumConfiguration) o;\n\n return isTransitional == that.isTransitional\n && allPeers.equals(that.allPeers)\n && nextPeers.equals(that.nextPeers)\n && prevPeers.equals(that.prevPeers);\n }\n\n @Override\n public int hashCode() {\n int result = (isTransitional ? 1 : 0);\n result = 31 * result + allPeers.hashCode();\n result = 31 * result + prevPeers.hashCode();\n result = 31 * result + nextPeers.hashCode();\n return result;\n }\n}",
"public interface CheckedSupplier<T, E extends Throwable> {\n\n T get() throws E;\n}",
"public static <T> T decodeAndCheckCrc(InputStream inputStream, Schema<T> schema)\n throws IOException, CrcError {\n // TODO this should check the length first and compare it with a passed-in maximum length\n final T message = schema.newMessage();\n final CrcInputStream crcStream = new CrcInputStream(inputStream, new Adler32());\n ProtobufIOUtil.mergeDelimitedFrom(crcStream, message, schema);\n\n final long computedCrc = crcStream.getValue();\n final long diskCrc = readCrc(inputStream);\n if (diskCrc != computedCrc) {\n throw new CrcError(\"CRC mismatch on deserialized message \" + message.toString());\n }\n\n return message;\n}",
"public static <T> List<ByteBuffer> encodeWithLengthAndCrc(Schema<T> schema, T message) {\n final LinkBuffer messageBuf = new LinkBuffer();\n final LowCopyProtobufOutput lcpo = new LowCopyProtobufOutput(messageBuf);\n\n try {\n schema.writeTo(lcpo, message);\n\n final int length = Ints.checkedCast(lcpo.buffer.size());\n final LinkBuffer lengthBuf = new LinkBuffer().writeVarInt32(length);\n\n return appendCrcToBufferList(\n Lists.newArrayList(\n Iterables.concat(lengthBuf.finish(), messageBuf.finish()))\n );\n } catch (IOException e) {\n // This method performs no IO, so it should not actually be possible for an IOException to be thrown.\n // But just in case...\n throw new RuntimeException(e);\n }\n}",
"static Matcher<OLogHeader> equalToHeader(OLogHeader header) {\n return new TypeSafeMatcher<OLogHeader>() {\n @Override\n protected boolean matchesSafely(OLogHeader item) {\n return item.getBaseSeqNum() == header.getBaseSeqNum()\n && item.getBaseTerm() == header.getBaseTerm()\n && QuorumConfiguration.fromProtostuff(item.getBaseConfiguration())\n .equals(QuorumConfiguration.fromProtostuff(header.getBaseConfiguration()));\n }\n\n @Override\n public void describeTo(Description description) {\n description.appendText(\" equal to \").appendValue(header);\n }\n };\n}",
"interface BytePersistence extends AutoCloseable {\n /**\n * Determine if the store is empty.\n *\n * @return True if empty, otherwise false.\n * @throws IOException\n */\n boolean isEmpty() throws IOException;\n\n /**\n * Get the size in bytes of the data, equal to the position/address of\n * next byte to be appended.\n *\n * @return Size in bytes.\n * @throws IOException\n */\n long size() throws IOException;\n\n /**\n * Append data.\n *\n * @param buffers Data to append.\n * IOException if the persistence is closed, or if the underlying object is inaccessible.\n */\n void append(ByteBuffer[] buffers) throws IOException;\n\n /**\n * Get a new reader of the data. Each reader is independent of any other,\n * and the caller takes responsibility for releasing associated resources.\n *\n * @return A new reader instance.\n * @throws IOException\n */\n PersistenceReader getReader() throws IOException;\n\n /**\n * Truncate data from the end, to a certain size.\n *\n * @param size New size of the data, equal to the position/address of the next\n * byte to be appended after the truncation. After calling this method,\n * the size() method will return this value of size.\n * @throws IOException if the persistence is closed, or if the underlying object is inaccessible.\n */\n void truncate(long size) throws IOException;\n\n /**\n * Sync previous operations to the underlying medium.\n *\n * @throws IOException if the persistence is closed, or if the underlying object is inaccessible.\n */\n void sync() throws IOException;\n\n /**\n * Release held resources.\n *\n * @throws IOException\n */\n void close() throws IOException;\n}",
"public static long term(long term) {\n return term;\n}"
] | import c5db.C5CommonTestUtil;
import c5db.MiscMatchers;
import c5db.interfaces.replication.QuorumConfiguration;
import c5db.log.generated.OLogHeader;
import c5db.replication.generated.QuorumConfigurationMessage;
import c5db.util.CheckedSupplier;
import com.google.common.collect.Iterables;
import com.google.common.primitives.Longs;
import org.hamcrest.Matcher;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.file.Path;
import java.util.List;
import static c5db.log.EntryEncodingUtil.decodeAndCheckCrc;
import static c5db.log.EntryEncodingUtil.encodeWithLengthAndCrc;
import static c5db.log.LogMatchers.equalToHeader;
import static c5db.log.LogPersistenceService.BytePersistence;
import static c5db.log.ReplicatorLogGenericTestUtil.term;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue; | /*
* Copyright 2014 WANdisco
*
* WANdisco licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package c5db.log;
public class LogFileServiceTest {
private static final String QUORUM_ID = "q";
private final Path testDirectory = (new C5CommonTestUtil()).getDataTestDir("log-file-service-test");
private LogFileService logFileService;
@Before
public void createTestObject() throws Exception {
logFileService = new LogFileService(testDirectory);
}
@Test(expected = IOException.class)
public void throwsAnIOExceptionIfAttemptingToAppendToTheFileAfterClosingIt() throws Exception {
try (FilePersistence persistence = logFileService.create(QUORUM_ID)) {
persistence.close();
persistence.append(serializedHeader(anOLogHeader()));
}
}
@Test
public void returnsNullWhenCallingGetCurrentWhenThereAreNoLogs() throws Exception {
assertThat(logFileService.getCurrent(QUORUM_ID), nullValue());
}
@Test
public void returnsTheLatestAppendedPersistenceForAGivenQuorum() throws Exception {
final OLogHeader header = anOLogHeader();
havingAppendedAPersistenceContainingHeader(header);
try (BytePersistence persistence = logFileService.getCurrent(QUORUM_ID)) {
assertThat(deserializedHeader(persistence), is(equalToHeader(header)));
}
}
@Test
public void returnsANewEmptyPersistenceOnEachCallToCreate() throws Exception {
havingAppendedAPersistenceContainingHeader(anOLogHeader());
try (BytePersistence aSecondPersistence = logFileService.create(QUORUM_ID)) {
assertThat(aSecondPersistence, isEmpty());
}
}
@Test
public void appendsANewPersistenceSoThatItWillBeReturnedByFutureCallsToGetCurrent() throws Exception {
final OLogHeader secondHeader;
final long anArbitrarySeqNum = 1210;
final long aGreaterArbitrarySeqNum = 1815;
havingAppendedAPersistenceContainingHeader(anOLogHeaderWithSeqNum(anArbitrarySeqNum));
havingAppendedAPersistenceContainingHeader(secondHeader = anOLogHeaderWithSeqNum(aGreaterArbitrarySeqNum));
try (BytePersistence primaryPersistence = logFileService.getCurrent(QUORUM_ID)) {
assertThat(deserializedHeader(primaryPersistence), is(equalToHeader(secondHeader)));
}
}
@Test
public void anExistingPersistenceRemainsUsableAfterBeingAppended() throws Exception {
final OLogHeader header = anOLogHeader();
try (FilePersistence persistence = logFileService.create(QUORUM_ID)) {
persistence.append(serializedHeader(header));
logFileService.append(QUORUM_ID, persistence);
assertThat(deserializedHeader(persistence), is(equalToHeader(header)));
}
}
@Test
public void removesTheMostRecentAppendedDataStoreWhenTruncateIsCalled() throws Exception {
final OLogHeader firstHeader;
final long anArbitrarySeqNum = 1210;
final long aGreaterArbitrarySeqNum = 1815;
havingAppendedAPersistenceContainingHeader(firstHeader = anOLogHeaderWithSeqNum(anArbitrarySeqNum));
havingAppendedAPersistenceContainingHeader(anOLogHeaderWithSeqNum(aGreaterArbitrarySeqNum));
logFileService.truncate(QUORUM_ID);
try (FilePersistence persistence = logFileService.getCurrent(QUORUM_ID)) {
assertThat(deserializedHeader(persistence), is(equalToHeader(firstHeader)));
}
}
@Test
public void listsDataStoresInOrderOfMostRecentToLeastRecent() throws Exception {
havingAppendedAPersistenceContainingHeader(anOLogHeaderWithSeqNum(1));
havingAppendedAPersistenceContainingHeader(anOLogHeaderWithSeqNum(2));
havingAppendedAPersistenceContainingHeader(anOLogHeaderWithSeqNum(3));
assertThat(logFileService.getList(QUORUM_ID), is(aListOfPersistencesWithSeqNums(3, 2, 1)));
}
@Test
public void canArchiveAllButTheMostRecentFile() throws Exception {
havingAppendedAPersistenceContainingHeader(anOLogHeaderWithSeqNum(1));
havingAppendedAPersistenceContainingHeader(anOLogHeaderWithSeqNum(2));
havingAppendedAPersistenceContainingHeader(anOLogHeaderWithSeqNum(3));
logFileService.archiveAllButCurrent(QUORUM_ID);
assertThat(logFileService.getList(QUORUM_ID), is(aListOfPersistencesWithSeqNums(3)));
}
private void havingAppendedAPersistenceContainingHeader(OLogHeader header) throws Exception {
try (FilePersistence persistenceToReplacePrimary = logFileService.create(QUORUM_ID)) {
persistenceToReplacePrimary.append(serializedHeader(header));
logFileService.append(QUORUM_ID, persistenceToReplacePrimary);
}
}
private static OLogHeader anOLogHeader() {
return anOLogHeaderWithSeqNum(1);
}
private static OLogHeader anOLogHeaderWithSeqNum(long seqNum) {
return new OLogHeader(term(1), seqNum, configurationOf(1, 2, 3));
}
private ByteBuffer[] serializedHeader(OLogHeader header) { | List<ByteBuffer> buffers = encodeWithLengthAndCrc(OLogHeader.getSchema(), header); | 4 |
PreibischLab/BigStitcher | src/main/java/net/preibisch/stitcher/gui/popup/RefineWithICPPopup.java | [
"public class SpimDataFilteringAndGrouping < AS extends AbstractSpimData< ? > >\n{\n\n\tpublic static List<Class<? extends Entity>> entityClasses = new ArrayList<>();\n\tstatic \n\t{\n\t\tentityClasses.add( TimePoint.class );\n\t\tentityClasses.add( Channel.class );\n\t\tentityClasses.add( Illumination.class );\n\t\tentityClasses.add( Angle.class );\n\t\tentityClasses.add( Tile.class );\n\t}\n\n\tSet<Class<? extends Entity>> groupingFactors; // attributes by which views are grouped first\n\tSet<Class<? extends Entity>> axesOfApplication; // axes of application -> we want to process within single instances (e.g. each TimePoint separately)\n\tSet<Class<? extends Entity>> axesOfComparison; // axes we want to compare\n\tMap<Class<? extends Entity>, List<? extends Entity>> filters; // filters for the different attributes\n\tAS data;\n\tGroupedViewAggregator gva;\n\n\tpublic boolean requestExpertSettingsForGlobalOpt = true;\n\tboolean dialogWasCancelled = false;\n\n\tpublic SpimDataFilteringAndGrouping(AS data)\n\t{\n\t\tgroupingFactors = new HashSet<>();\n\t\taxesOfApplication = new HashSet<>();\n\t\taxesOfComparison = new HashSet<>();\n\t\tfilters = new HashMap<>();\n\t\tthis.data = data;\n\t\tgva = new GroupedViewAggregator();\n\t}\n\n\tpublic AS getSpimData()\n\t{\n\t\treturn data;\n\t}\n\n\tpublic GroupedViewAggregator getGroupedViewAggregator()\n\t{\n\t\treturn gva;\n\t}\n\n\tpublic void addGroupingFactor(Class<? extends Entity> factor ) {\n\t\tgroupingFactors.add(factor);\n\t}\n\n\tpublic void addFilter(Class<? extends Entity> cl, List<? extends Entity> instances){\n\t\tfilters.put(cl, instances);\n\t}\n\n\tpublic void addFilters(Collection<? extends BasicViewDescription< ? extends BasicViewSetup >> selected)\n\t{\n\t\tfor (Class<? extends Entity> cl : entityClasses)\n\t\t\tfilters.put( cl, new ArrayList<>(getInstancesOfAttribute( selected, cl ) ) );\n\t}\n\n\tpublic void addApplicationAxis(Class<? extends Entity> axis ) {\n\t\taxesOfApplication.add(axis);\n\t}\n\n\tpublic void addComparisonAxis(Class<? extends Entity> axis ) {\n\t\taxesOfComparison.add(axis);\n\t}\n\n\tpublic void clearGroupingFactors()\n\t{\n\t\tgroupingFactors.clear();\n\t}\n\n\tpublic void clearFilters()\n\t{\n\t\tfilters.clear();\n\t}\n\n\tpublic void clearApplicationAxes()\n\t{\n\t\taxesOfApplication.clear();\n\t}\n\n\tpublic void clearComparisonAxes()\n\t{\n\t\taxesOfComparison.clear();\n\t}\n\n\tpublic Set< Class< ? extends Entity > > getGroupingFactors()\n\t{\n\t\treturn groupingFactors;\n\t}\n\n\tpublic Set< Class< ? extends Entity > > getAxesOfApplication()\n\t{\n\t\treturn axesOfApplication;\n\t}\n\n\tpublic Set< Class< ? extends Entity > > getAxesOfComparison()\n\t{\n\t\treturn axesOfComparison;\n\t}\n\n\tpublic Map< Class< ? extends Entity >, List< ? extends Entity > > getFilters()\n\t{\n\t\treturn filters;\n\t}\n\n\tpublic List<? extends BasicViewDescription< ? > > getFilteredViews()\n\t{\n\t\treturn SpimDataTools.getFilteredViewDescriptions( data.getSequenceDescription(), filters);\n\t}\n\n\tpublic List< Group< BasicViewDescription< ? > >> getGroupedViews(boolean filtered)\n\t{\n\t\tfinal List<BasicViewDescription< ? > > ungroupedElements =\n\t\t\t\tSpimDataTools.getFilteredViewDescriptions( data.getSequenceDescription(), filtered? filters : new HashMap<>(), false );\n\t\treturn Group.combineBy( ungroupedElements, groupingFactors);\n\t}\n\n\tpublic List<Pair<? extends Group< ? extends BasicViewDescription< ? extends BasicViewSetup > >, ? extends Group< ? extends BasicViewDescription< ? extends BasicViewSetup >>>> getComparisons()\n\t{\n\t\tfinal List<Pair<? extends Group< ? extends BasicViewDescription< ? extends BasicViewSetup > >, ? extends Group< ? extends BasicViewDescription< ? extends BasicViewSetup >>>> res = new ArrayList<>();\n\t\t\n\t\t// filter first\n\t\tfinal List<BasicViewDescription< ? > > ungroupedElements =\n\t\t\t\tSpimDataTools.getFilteredViewDescriptions( data.getSequenceDescription(), filters);\n\t\t// then group\n\t\tfinal List< Group< BasicViewDescription< ? > >> groupedElements = \n\t\t\t\tGroup.combineBy(ungroupedElements, groupingFactors);\n\t\t\n\t\t// go through possible group pairs\n\t\tfor (int i = 0; i < groupedElements.size(); ++i)\n\t\t\tfor(int j = i+1; j < groupedElements.size(); ++j)\n\t\t\t{\n\t\t\t\t// we will want to process the pair if:\n\t\t\t\t// the groups do not differ along an axis along which we want to treat elements individually (e.g. Angle)\n\t\t\t\t// but they differ along an axis that we want to register (e.g Tile)\n\t\t\t\tif (!groupsDifferByAny( groupedElements.get( i ), groupedElements.get( j ), axesOfApplication ) \n\t\t\t\t\t\t&& groupsDifferByAny( groupedElements.get( i ), groupedElements.get( j ), axesOfComparison ))\n\t\t\t\t\tres.add(new ValuePair<>(groupedElements.get( i ), groupedElements.get( j )));\n\t\t\t}\n\t\treturn res;\n\t}\n\t\n\tprivate static boolean groupsDifferByAny(Iterable< BasicViewDescription< ? > > vds1, Iterable< BasicViewDescription< ? > > vds2, Set<Class<? extends Entity>> entities)\n\t{\n\t\tfor (Class<? extends Entity> entity : entities)\n\t\t{\n\t\t\tfor ( BasicViewDescription< ? > vd1 : vds1)\n\t\t\t\tfor ( BasicViewDescription< ? > vd2 : vds2)\n\t\t\t\t{\n\t\t\t\t\tif (entity == TimePoint.class)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (!vd1.getTimePoint().equals( vd2.getTimePoint() ))\n\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tif (!vd1.getViewSetup().getAttribute( entity ).equals( vd2.getViewSetup().getAttribute( entity ) ) )\n\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t}\n\t\t}\n\t\t\n\t\treturn false;\n\t}\n\n\n\t/**\n\t * get all instances of the attribute class cl in the (grouped) views vds. \n\t * @param vds collection of view description lists\n\t * @param cl Class of entity to get instances of\n\t * @return all instances of cl in the views in vds\n\t */\n\tpublic static Set<Entity> getInstancesOfAttributeGrouped(Collection< List< BasicViewDescription< ? extends BasicViewSetup > > > vds, Class<? extends Entity> cl)\n\t{\t\n\t\t// make one List out of the nested Collection and getInstancesOfAttribute\n\t\treturn getInstancesOfAttribute( vds.stream().reduce( new ArrayList<>(), (x, y) -> {x.addAll(y); return x;} ), cl );\n\t}\n\n\tpublic static Set<Entity> getInstancesOfAttribute(Collection<? extends BasicViewDescription< ? extends BasicViewSetup >> vds, Class<? extends Entity> cl)\n\t{\n\t\tSet<Entity> res = new HashSet<>();\n\t\tfor (BasicViewDescription< ? extends BasicViewSetup > vd : vds)\n\t\t\tif (cl == TimePoint.class)\n\t\t\t\tres.add( vd.getTimePoint() );\n\t\t\telse\n\t\t\t\tres.add( vd.getViewSetup().getAttribute( cl ) );\n\t\treturn res;\n\t}\n\n\t/**\n\t * get the instances of class cl that are present in at least one ViewDescription of each of the groups in vds.\n\t * @param vds collection of view description iterables\n\t * @param cl Class of entity to get instances of\n\t * @return all instances of cl in the views in vds\n\t */\n\tpublic static List<? extends Entity> getInstancesInAllGroups(Collection< ? extends Iterable< BasicViewDescription< ? extends BasicViewSetup > > > vds, Class<? extends Entity> cl)\n\t{\n\t\tSet<Entity> res = new HashSet<>();\n\t\tIterator< ? extends Iterable< BasicViewDescription< ? extends BasicViewSetup > > > it = vds.iterator();\n\t\tfor (BasicViewDescription< ? extends BasicViewSetup > vd : it.next())\n\t\t\tif (cl == TimePoint.class)\n\t\t\t\tres.add( vd.getTimePoint() );\n\t\t\telse\n\t\t\t\tres.add( vd.getViewSetup().getAttribute( cl ) );\n\n\t\twhile (it.hasNext()) \n\t\t{\n\t\t\tIterable< BasicViewDescription< ? extends BasicViewSetup > > vdli = it.next();\n\t\t\tSet<Entity> resI = new HashSet<>();\n\t\t\tfor (BasicViewDescription< ? extends BasicViewSetup > vd : vdli)\n\t\t\t\tif (cl == TimePoint.class)\n\t\t\t\t\tresI.add( vd.getTimePoint() );\n\t\t\t\telse\n\t\t\t\t\tresI.add( vd.getViewSetup().getAttribute( cl ) );\n\n\t\t\tSet<Entity> newRes = new HashSet<>();\n\t\t\tfor (Entity e : resI)\n\t\t\t{\n\t\t\t\tif(res.contains( e ))\n\t\t\t\t\tnewRes.add( e );\n\t\t\t}\n\t\t\tres = newRes;\n\t\t}\n\n\t\treturn new ArrayList<>(res);\n\t}\n\n\tpublic boolean getDialogWasCancelled()\n\t{\n\t\treturn dialogWasCancelled;\n\t}\n\n\t// convenience method if we do not know selected views\n\tpublic SpimDataFilteringAndGrouping< AS> askUserForFiltering()\n\t{\n\t\t// select all\n\t\treturn askUserForFiltering( data.getSequenceDescription().getViewDescriptions().values() );\n\t}\n\n\t// convenience method if have a panel (which can give us selected views)\n\tpublic SpimDataFilteringAndGrouping< AS> askUserForFiltering(FilteredAndGroupedExplorerPanel< AS, ?> panel)\n\t{\n\t\tList< BasicViewDescription< ? extends BasicViewSetup > > views;\n\t\t\n\t\tif (panel instanceof GroupedRowWindow)\n\t\t{\n\t\t\tCollection< List< BasicViewDescription< ? extends BasicViewSetup > > > selectedRowsGroups = ((GroupedRowWindow)panel).selectedRowsGroups();\n\t\t\tviews = selectedRowsGroups.stream().reduce( new ArrayList<>(), (x, y) -> {x.addAll(y); return x;} );\n\t\t}\n\t\telse\n\t\t\tviews = panel.selectedRows();\n\t\t\n\t\tSpimDataFilteringAndGrouping< AS > res = askUserForFiltering( views );\n\t\treturn res;\n\t\t\n\t}\n\n\tpublic SpimDataFilteringAndGrouping< AS> askUserForFiltering(Collection<? extends BasicViewDescription< ? extends BasicViewSetup > > views)\n\t{\n\n\t\tGenericDialogPlus gdp1 = new GenericDialogPlus( \"Select Views To Process\" );\n\t\t\n\t\tfinal String msg = ( \"<html><strong>Select wether you want to process all instances of an attribute <br>\"\n\t\t\t\t+ \" or just the currently selected Views</strong> </html>\" ) ;\n\t\tFileListDatasetDefinition.addMessageAsJLabel(msg, gdp1);\n\t\t\n\t\tString[] viewSelectionChoices = new String[] {\"all\", \"selected\"};\n\t\t\n\t\tfor (Class<? extends Entity> cl : entityClasses)\n\t\t{\n\t\t\tboolean allSelected = (getInstancesOfAttribute(views, cl ).containsAll(SpimDataTools.getInstancesOfAttribute( data.getSequenceDescription(), cl )));\n\t\t\tgdp1.addChoice( cl.getSimpleName(), viewSelectionChoices, allSelected ? viewSelectionChoices[0] : viewSelectionChoices[1] );\t\t\t\n\t\t}\n\t\t\n\t\tgdp1.showDialog();\n\t\tif (gdp1.wasCanceled())\n\t\t{\n\t\t\tdialogWasCancelled = true;\n\t\t\treturn this;\n\t\t}\n\t\t\n\t\tfor (Class<? extends Entity> cl : entityClasses)\n\t\t{\n\t\t\tboolean useCurrent = gdp1.getNextChoiceIndex() == 1;\n\t\t\tif (useCurrent)\n\t\t\t\taddFilter( cl, new ArrayList<>(getInstancesOfAttribute(views, cl )) );\n\t\t}\n\t\t\n\t\treturn this;\n\t\n\t}\n\n\tpublic SpimDataFilteringAndGrouping< AS> askUserForGrouping()\n\t{\n\t\t// use the current filtering as preset\n\t\treturn askUserForGrouping( SpimDataTools.getFilteredViewDescriptions( data.getSequenceDescription(), getFilters() ), new ArrayList<>(), new HashSet<>() );\n\t}\n\n\tpublic SpimDataFilteringAndGrouping< AS> askUserForGrouping( FilteredAndGroupedExplorerPanel< AS, ?> panel)\n\t{\n\t\tList< BasicViewDescription< ? extends BasicViewSetup > > views;\n\n\t\tif (panel instanceof GroupedRowWindow)\n\t\t{\n\t\t\tCollection< List< BasicViewDescription< ? extends BasicViewSetup > > > selectedRowsGroups = ((GroupedRowWindow)panel).selectedRowsGroups();\n\t\t\tviews = selectedRowsGroups.stream().reduce( new ArrayList<>(), (x, y) -> {x.addAll(y); return x;} );\n\t\t}\n\t\telse\n\t\t\tviews = panel.selectedRows();\n\n\t\tfinal HashSet< Class<? extends Entity> > comparisonsRequested = new HashSet<>();\n\t\tif (StitchingExplorerPanel.class.isInstance( panel ) )\n\t\t{\n\t\t\tif (!panel.channelsGrouped())\n\t\t\t\tcomparisonsRequested.add( Channel.class );\n\t\t\tif (!panel.illumsGrouped())\n\t\t\t\tcomparisonsRequested.add( Illumination.class );\n\t\t\tif (!panel.tilesGrouped())\n\t\t\t\tcomparisonsRequested.add( Tile.class );\n\t\t}\n\t\treturn askUserForGrouping( views, panel.getTableModel().getGroupingFactors(), comparisonsRequested);\n\t}\n\n\tpublic SpimDataFilteringAndGrouping< AS> askUserForGrouping( \n\t\t\t\t\tCollection<? extends BasicViewDescription< ? > > views,\n\t\t\t\t\tCollection<Class<? extends Entity>> groupingFactors,\n\t\t\t\t\tCollection<Class<? extends Entity>> comparisionFactors)\n\t{\n\t\tGenericDialogPlus gdp2 = new GenericDialogPlus( \"Select How to Process Views\" );\n\t\t\n\t\tfinal String msg = ( \"<html><strong>Select how to process the different attributes </strong> <br>\"\n\t\t\t\t+ \"<strong>COMPARE:</strong> calculate pairwise shift between instances <br>\"\n\t\t\t\t+ \"<strong>GROUP:</strong> combine all instances into one view<br>\"\n\t\t\t\t+ \"<strong>TREAT INDIVIDUALLY:</strong> process instances one after the other, but do not compare or group <br> </html>\");\n\t\tFileListDatasetDefinition.addMessageAsJLabel(msg, gdp2);\n\n\t\tString[] computeChoices = new String[] {\"compare\", \"group\", \"treat individually\"};\n\t\tfor (Class<? extends Entity> cl : entityClasses)\n\t\t{\n\t\t\tboolean isGrouping = groupingFactors.contains( cl );\n\t\t\tboolean isFilterOrSingleton = getFilters().keySet().contains( cl ) || getInstancesOfAttribute(views, cl ).size() <= 1;\n\t\t\tboolean isComparison = comparisionFactors.contains( cl );\n\t\t\tint idx = isGrouping ? 1 : isComparison || !isFilterOrSingleton ? 0 : 2;\n\t\t\tgdp2.addChoice( \"How_to_treat_\" + cl.getSimpleName() + \"s:\", computeChoices, computeChoices[idx] );\n\t\t}\n\n\t\tgdp2.showDialog();\n\t\tif (gdp2.wasCanceled())\n\t\t{\n\t\t\tdialogWasCancelled = true;\n\t\t\treturn this;\n\t\t}\n\n\t\tfor (Class<? extends Entity> cl : entityClasses)\n\t\t{\n\t\t\tint selection = gdp2.getNextChoiceIndex();\n\t\t\tif (selection == 0)\n\t\t\t\taddComparisonAxis( cl );\n\t\t\telse if (selection == 1)\n\t\t\t\taddGroupingFactor( cl );\n\t\t\telse\n\t\t\t\taddApplicationAxis( cl );\n\t\t}\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * ask user how to aggregate grouped views (for all the entity classes we group by)\n\t * if a default choice for a class is provided, the user will not be asked for that class\n\t * @param defaultChoices pre-set choices for specific classes (NB: may not be 'pick specific')\n\t * @return self\n\t */\n\tpublic SpimDataFilteringAndGrouping< AS> askUserForGroupingAggregator(final Map<Class<? extends Entity>, ActionType> defaultChoices)\n\t{\n\t\t// ask what to do with grouped views\n\t\tGenericDialogPlus gdp = new GenericDialogPlus( \"Select How to Treat Grouped Views\" );\t\t\n\n//\t\tFileListDatasetDefinition.addMessageAsJLabel(\"<html><strong>Select which instances of attributes to use in Grouped Views </strong> <br></html>\", gdp3);\n\t\tgdp.addMessage( \"Please specify how to deal with grouped Views.\", new Font( Font.SANS_SERIF, Font.BOLD, 14 ), GUIHelper.neutral );\n\n\t\t// filter first\n\t\tfinal List<BasicViewDescription< ? > > ungroupedElements =\n\t\t\t\t\t\tSpimDataTools.getFilteredViewDescriptions( data.getSequenceDescription(), getFilters());\n\t\t// then group\n\t\tfinal List< Group< BasicViewDescription< ? > >> groupedElements = \n\t\t\t\t\t\tGroup.combineBy( ungroupedElements, getGroupingFactors());\n\n\t\tboolean dialogNecessary = false;\n\t\tfor (Class<? extends Entity> cl : getGroupingFactors())\n\t\t{\n\t\t\tif (defaultChoices != null && defaultChoices.containsKey( cl ))\n\t\t\t\tcontinue;\n\n\t\t\tList<String> selection = new ArrayList<>();\n\t\t\tselection.add( \"Average \" + cl.getSimpleName() +\"s\" );\n//\t\t\tselection.add( \"pick brightest\" );\n\t\t\tList< ? extends Entity > instancesInAllGroups = getInstancesInAllGroups( groupedElements, cl );\n\n\t\t\t// we only have one instance of entity, do not ask for aggregation in that case\n\t\t\tif (instancesInAllGroups.size() < 2)\n\t\t\t\tcontinue;\n\t\t\t// we have more than one instance of any entity -> we have to display dialog\n\t\t\tdialogNecessary = true;\n\n\t\t\tinstancesInAllGroups.forEach( ( e ) -> \n\t\t\t{\n\t\t\t\tif (e instanceof NamedEntity)\n\t\t\t\t\tselection.add( \"use \" + cl.getSimpleName() + \" \" + ((NamedEntity)e).getName());\n\t\t\t\telse\n\t\t\t\t\tselection.add( \"use \" + cl.getSimpleName() + \" \" + Integer.toString( e.getId() ));\n\t\t\t});\n\t\t\t\n\t\t\tString[] selectionArray = selection.toArray( new String[selection.size()] );\n\t\t\tgdp.addChoice( cl.getSimpleName() + \"s:\", selectionArray, selectionArray[0] );\n\t\t}\n\n\t\tif (dialogNecessary)\n\t\t\tgdp.showDialog();\n\t\t\tif (gdp.wasCanceled())\n\t\t\t{\n\t\t\t\tdialogWasCancelled = true;\n\t\t\t\treturn this;\n\t\t\t}\n\n\t\tfor (Class<? extends Entity> cl : getGroupingFactors())\n\t\t{\n\t\t\tif (defaultChoices != null && defaultChoices.containsKey( cl ))\n\t\t\t{\n\t\t\t\tgetGroupedViewAggregator().addAction(defaultChoices.get( cl ), cl, null);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tList< ? extends Entity > instancesInAllGroups = getInstancesInAllGroups( groupedElements, cl );\n\n\t\t\t// we have only one instance -> \"average\" (i.e. just keep the one view)\n\t\t\tif (instancesInAllGroups.size() < 2)\n\t\t\t{\n\t\t\t\tgetGroupedViewAggregator().addAction( ActionType.AVERAGE, cl, null );\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tint nextChoiceIndex = gdp.getNextChoiceIndex();\n\t\t\tif (nextChoiceIndex == 0)\n\t\t\t\tgetGroupedViewAggregator().addAction( ActionType.AVERAGE, cl, null );\n//\t\t\telse if (nextChoiceIndex == 1)\n//\t\t\t\tgetGroupedViewAggregator().addAction( ActionType.PICK_BRIGHTEST, cl, null );\n\t\t\telse\n\t\t\t\tgetGroupedViewAggregator().addAction( ActionType.PICK_SPECIFIC, cl, instancesInAllGroups.get( nextChoiceIndex - 1 ) );\n\t\t}\n\t\t\n\t\treturn this;\n\t}\n\n\tpublic SpimDataFilteringAndGrouping< AS> askUserForGroupingAggregator()\n\t{\n\t\treturn askUserForGroupingAggregator( new HashMap<>() );\n\t}\n}",
"public class DemoLinkOverlay implements OverlayRenderer, TransformListener< AffineTransform3D >, SelectedViewDescriptionListener< AbstractSpimData<?> >\n{\n\tfinal private ArrayList< Pair< Group< ViewId >, Group< ViewId > > > lastFilteredResults, lastInconsistentResults;\n\tprivate PairwiseLinkInterface results;\n\tprivate AbstractSpimData< ? > spimData;\n\tprivate AffineTransform3D viewerTransform;\n\tpublic boolean isActive;\n\tprivate ArrayList<Pair<Group<ViewId>, Group<ViewId>>> activeLinks; //currently selected in the GUI\n\n\tfinal Stroke dashed = new BasicStroke( 1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, new float[]{4}, 0 );\n\tfinal Stroke thin = new BasicStroke( 1 );\n\tfinal Stroke thick = new BasicStroke( 1.5f );\n\n\tpublic DemoLinkOverlay( PairwiseLinkInterface results, AbstractSpimData< ? > spimData )\n\t{\n\t\tthis.results = results;\n\t\tthis.spimData = spimData;\n\t\tthis.lastFilteredResults = new ArrayList<>();\n\t\tthis.lastInconsistentResults = new ArrayList<>();\n\t\tviewerTransform = new AffineTransform3D();\n\t\tisActive = false;\n\t\tactiveLinks = new ArrayList<>();\n\t}\n\n\tpublic void setPairwiseLinkInterface( final PairwiseLinkInterface pli )\n\t{\n\t\tthis.results = pli;\n\t}\n\n\t// called by FilteredStitchingResults\n\tpublic ArrayList< Pair< Group< ViewId >, Group< ViewId > > > getFilteredResults()\n\t{\n\t\treturn lastFilteredResults;\n\t}\n\n\t// called by e.g. Global Optimization\n\tpublic ArrayList< Pair< Group< ViewId >, Group< ViewId > > > getInconsistentResults()\n\t{\n\t\treturn lastInconsistentResults;\n\t}\n\n\t@Override\n\tpublic void transformChanged(AffineTransform3D transform)\n\t{\n\t\tthis.viewerTransform = transform;\n\t}\n\n\t@Override\n\tpublic void drawOverlays(Graphics g)\n\t{\n\t\t// dont do anything if the overlay was set to inactive or we have no Tile selected (no links to display)\n\t\tif (!isActive || activeLinks.size() == 0)\n\t\t\treturn;\n\n\t\tfor ( Pair<Group<ViewId>, Group<ViewId>> p: activeLinks)\n\t\t{\n\t\t\tif ( spimData.getSequenceDescription().getMissingViews() != null )\n\t\t\t{\n\t\t\t\tp.getA().filterMissingViews( spimData.getSequenceDescription().getMissingViews().getMissingViews() );\n\t\t\t\tp.getB().filterMissingViews( spimData.getSequenceDescription().getMissingViews().getMissingViews() );\n\t\t\t}\n\n\t\t\t// local coordinates of views, without BDV transform \n\t\t\tfinal double[] lPos1 = new double[ 3 ];\n\t\t\tfinal double[] lPos2 = new double[ 3 ];\n\t\t\t// global coordianates, after BDV transform\n\t\t\tfinal double[] gPos1 = new double[ 3 ];\n\t\t\tfinal double[] gPos2 = new double[ 3 ];\n\t\t\t\n\t\t\tBasicViewDescription<?> vdA = spimData.getSequenceDescription().getViewDescriptions().get( p.getA().iterator().next() );\n\t\t\tBasicViewDescription<?> vdB = spimData.getSequenceDescription().getViewDescriptions().get( p.getB().iterator().next() );\n\t\t\tViewRegistration vrA = spimData.getViewRegistrations().getViewRegistration( p.getA().iterator().next() );\n\t\t\tViewRegistration vrB = spimData.getViewRegistrations().getViewRegistration( p.getB().iterator().next() );\n\n\t\t\tlong[] sizeA = new long[vdA.getViewSetup().getSize().numDimensions()];\n\t\t\tlong[] sizeB = new long[vdB.getViewSetup().getSize().numDimensions()];\n\t\t\tspimData.getSequenceDescription().getViewDescriptions().get( p.getA().iterator().next() ).getViewSetup().getSize().dimensions( sizeA );\n\t\t\tspimData.getSequenceDescription().getViewDescriptions().get( p.getB().iterator().next() ).getViewSetup().getSize().dimensions( sizeB );\n\t\t\t\n\t\t\t// TODO: this uses the transform of the first view in the set, maybe do something better?\n\t\t\tAffineTransform3D vt1 = spimData.getViewRegistrations().getViewRegistration( p.getA().iterator().next() ).getModel();\n\t\t\tAffineTransform3D vt2 = spimData.getViewRegistrations().getViewRegistration( p.getB().iterator().next() ).getModel();\n\t\t\t\n\t\t\tboolean overlaps = SimpleBoundingBoxOverlap.overlaps( SimpleBoundingBoxOverlap.getBoundingBox(\tvdA.getViewSetup(), vrA ), SimpleBoundingBoxOverlap.getBoundingBox( vdB.getViewSetup(), vrB ) );\n\n\t\t\tif (!overlaps)\n\t\t\t\tcontinue;\n\n\t\t\tfinal AffineTransform3D transform = new AffineTransform3D();\n\t\t\ttransform.preConcatenate( viewerTransform );\n\n\t\t\tfor( int i = 0; i < 3; i++)\n\t\t\t{\n\t\t\t\t// start from middle of view\n\t\t\t\tlPos1[i] += sizeA[i] / 2;\n\t\t\t\tlPos2[i] += sizeB[i] / 2;\n\t\t\t}\n\n\t\t\tvt1.apply( lPos1, lPos1 );\n\t\t\tvt2.apply( lPos2, lPos2 );\n\t\t\t\n\t\t\ttransform.apply( lPos1, gPos1 );\n\t\t\ttransform.apply( lPos2, gPos2 );\n\n\t\t\tGraphics2D g2d = null;\n\n\t\t\tif ( Graphics2D.class.isInstance( g ) )\n\t\t\t\tg2d = (Graphics2D) g;\n\t\t\t/*\n\t\t\tif ( lastFilteredResults.contains( p ) || lastFilteredResults.contains( TransformationTools.reversePair( p ) ) )\n\t\t\t{\n\t\t\t\tg.setColor( Color.ORANGE );\n\t\t\t\tif ( g2d != null ) g2d.setStroke( dashed );\n\t\t\t}\n\t\t\telse if ( lastInconsistentResults.contains( p ) || lastInconsistentResults.contains( TransformationTools.reversePair( p ) ) )\n\t\t\t{\n\t\t\t\tg.setColor( Color.RED );\n\t\t\t\tif ( g2d != null ) g2d.setStroke( dashed );\n\t\t\t}\n\t\t\telse if ( results.getPairwiseLinks().contains( p ) || results.getPairwiseLinks().contains( TransformationTools.reversePair( p ) ) )\n\t\t\t{\n\t\t\t\tg.setColor( Color.GREEN );\n\t\t\t\tif ( g2d != null ) g2d.setStroke( thick );\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tg.setColor( Color.GRAY );\n\t\t\t\tif ( g2d != null ) g2d.setStroke( dashed );\n\t\t\t}\n\t\t\t*/\n\n\t\t\tif ( overlapsWith( p, lastFilteredResults ) )\n\t\t\t{\n\t\t\t\tg.setColor( Color.ORANGE );\n\t\t\t\tif ( g2d != null ) g2d.setStroke( dashed );\n\t\t\t}\n\t\t\telse if ( overlapsWith( p, lastInconsistentResults ) )\n\t\t\t{\n\t\t\t\tg.setColor( Color.RED );\n\t\t\t\tif ( g2d != null ) g2d.setStroke( dashed );\n\t\t\t}\n\t\t\telse if ( overlapsWith( p, results.getPairwiseLinks() ) )\n\t\t\t{\n\t\t\t\tg.setColor( Color.GREEN );\n\t\t\t\tif ( g2d != null ) g2d.setStroke( thick );\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tg.setColor( Color.GRAY );\n\t\t\t\tif ( g2d != null ) g2d.setStroke( dashed );\n\t\t\t}\n\n\t\t\tg.drawLine((int) gPos1[0],(int) gPos1[1],(int) gPos2[0],(int) gPos2[1] );\n\t\t}\n\t}\n\n\tpublic static boolean overlapsWith( final Pair<Group<ViewId>, Group<ViewId>> p1, final Collection< Pair<Group<ViewId>, Group<ViewId>>> pairList )\n\t{\n\t\tfor ( final Pair<Group<ViewId>, Group<ViewId>> p2 : pairList )\n\t\t\tif ( overlapsWith( p1, p2 ) )\n\t\t\t\treturn true;\n\n\t\treturn false;\n\t}\n\n\tpublic static boolean overlapsWith( final Pair<Group<ViewId>, Group<ViewId>> p1, final Pair<Group<ViewId>, Group<ViewId>> p2 )\n\t{\n\t\tboolean overlap1 = false;\n\t\tboolean overlap2 = false;\n\n\t\tfor ( final ViewId v1A : p1.getA().getViews() )\n\t\t\tif ( p2.getA().contains( v1A ) )\n\t\t\t\toverlap1 = true;\n\n\t\tfor ( final ViewId v1B : p1.getB().getViews() )\n\t\t\tif ( p2.getB().contains( v1B ) )\n\t\t\t\toverlap2 = true;\n\n\t\tif ( overlap1 && overlap2 )\n\t\t\treturn true;\n\n\t\toverlap1 = false;\n\t\toverlap2 = false;\n\n\t\tfor ( final ViewId v1A : p1.getA().getViews() )\n\t\t\tif ( p2.getB().contains( v1A ) )\n\t\t\t\toverlap2 = true;\n\n\t\tfor ( final ViewId v1B : p1.getB().getViews() )\n\t\t\tif ( p2.getA().contains( v1B ) )\n\t\t\t\toverlap1 = true;\n\n\t\tif ( overlap1 && overlap2 )\n\t\t\treturn true;\n\t\telse\n\t\t\treturn false;\n\t}\n\n\tpublic void clearActiveLinks()\n\t{\n\t\tactiveLinks.clear();\n\t}\n\t\n\tpublic void setActiveLinks(List<Pair<Group<ViewId>, Group<ViewId>>> vids)\n\t{\n\t\tactiveLinks.clear();\n\t\tactiveLinks.addAll( vids );\n\t}\n\n\t@Override\n\tpublic void setCanvasSize(int width, int height){}\n\n\n\t@Override\n\tpublic void selectedViewDescriptions(\n\t\t\tList< List< BasicViewDescription< ? extends BasicViewSetup > > > viewDescriptions)\n\t{\n\t\tList<Pair<Group<ViewId>, Group<ViewId>>> res = new ArrayList<>();\n\t\tfor (int i = 0; i<viewDescriptions.size(); i++)\n\t\t\tfor (int j = i+1; j<viewDescriptions.size(); j++)\n\t\t\t{\n\t\t\t\tGroup<ViewId> groupA = new Group<>();\n\t\t\t\tgroupA.getViews().addAll( viewDescriptions.get( i ) );\n\t\t\t\tGroup<ViewId> groupB = new Group<>();\n\t\t\t\tgroupB.getViews().addAll( viewDescriptions.get( j ) );\n\t\t\t\tres.add( new ValuePair< Group<ViewId>, Group<ViewId> >( groupA, groupB ) );\n\t\t\t}\n\t\tsetActiveLinks( res );\n\t}\n\n\n\t@Override\n\tpublic void updateContent(AbstractSpimData< ? > data)\n\t{\n\t\tthis.spimData = data;\n\t}\n\n\n\t@Override\n\tpublic void save()\n\t{\n\t}\n\n\n\t@Override\n\tpublic void quit()\n\t{\n\t}\n\n}",
"public class ICPRefinement\n{\n\tpublic static enum ICPType{ TileRefine, ChromaticAbberation, All, Expert }\n\tpublic static String[] refinementType = new String[]{ \"Simple (tile registration)\", \"Simple (chromatic abberation)\", \"Simple (all together)\", \"Expert ...\" };\n\tpublic static int defaultRefinementChoice = 0;\n\n\tpublic static String[] downsampling = new String[]{ \"Downsampling 2/2/1\", \"Downsampling 4/4/2\", \"Downsampling 8/8/4\", \"Downsampling 16/16/8\" };\n\tpublic static int defaultDownsamplingChoice = 2;\n\n\tpublic static String[] threshold = new String[]{ \"Low Threshold (many points)\", \"Average Threshold\", \"High Threshold (few points)\" };\n\tpublic static int defaultThresholdChoice = 1;\n\n\tpublic static String[] distance = new String[]{ \"Fine Adjustment (<1px)\", \"Normal Adjustment (<5px)\", \"Gross Adjustment (<20px, careful)\" };\n\tpublic static int defaultDistanceChoice = 1;\n\n\tpublic static int defaultLabelDialog = 0;\n\tpublic static int defaultChannelChoice = 0;\n\tpublic static double defaultICPError = 5;\n\tpublic static int defaultModel = 2;\n\tpublic static boolean defaultRegularize = true;\n\n\tpublic static class ICPRefinementParameters\n\t{\n\t\tpublic boolean groupTiles, groupIllums, groupChannels;\n\n\t\t// some channels that should not be grouped\n\t\tpublic ArrayList< Integer > doNotGroupChannels = new ArrayList<>();\n\t\t// some illuminations that should not be grouped\n\t\t//public ArrayList< Integer > doNotGroupIllums = new ArrayList<>();\n\t\t// some tiles that should not be grouped\n\t\t//public ArrayList< Integer > doNotGroupTiles = new ArrayList<>();\n\n\t\tpublic String label, transformationDescription;\n\t\tpublic double maxError;\n\t\tpublic AbstractModel< ? > transformationModel;\n\n\t\tfinal List<ViewId > viewIds;\n\n\t\tpublic ICPRefinementParameters( final List<ViewId > viewIds )\n\t\t{\n\t\t\tthis.viewIds = viewIds;\n\t\t}\n\n\t\tpublic String toString()\n\t\t{\n\t\t\tString o = \"ICPRefinementParameters:\\n\"\n\t\t\t\t\t+ \"Interest point label: \" + label + \"\\n\"\n\t\t\t\t\t+ \"maxError: \" + maxError + \"\\n\"\n\t\t\t\t\t+ \"transformationModel: \" + transformationModel.getClass().getSimpleName() + \"\\n\"\n\t\t\t\t\t+ \"groupTiles: \" + groupTiles + \"\\n\"\n\t\t\t\t\t+ \"groupIllums: \" + groupIllums + \"\\n\"\n\t\t\t\t\t+ \"groupChannels: \" + groupChannels + \"\\n\"\n\t\t\t\t\t+ \"doNotGroupChannels: [\";\n\n\t\t\t\t\tfor ( final int ch : doNotGroupChannels )\n\t\t\t\t\t\to += ch + \", \";\n\n\t\t\t\t\to += \"]\";\n\n\t\t\t\t\treturn o;\n\t\t}\n\t}\n\n\tpublic static ICPRefinementParameters initICPRefinement( final SpimData2 data, final List<? extends BasicViewDescription< ? > > selectedViews )\n\t{\n\t\tif ( StitchingUIHelper.allViews2D( selectedViews ) )\n\t\t{\n\t\t\tIOFunctions.println( \"ICP refinement is currenty not supported for 2D: \" + RefineWithICPPopup.class.getSimpleName() );\n\t\t\treturn null;\n\t\t}\n\n\t\t// filter not present ViewIds\n\t\tfinal ArrayList< ViewId > viewIds = new ArrayList<>();\n\t\tviewIds.addAll( selectedViews );\n\n\t\tfinal List< ViewId > removed = SpimData2.filterMissingViews( data, viewIds );\n\t\tif ( removed.size() > 0 ) IOFunctions.println( new Date( System.currentTimeMillis() ) + \": Removed \" + removed.size() + \" views because they are not present.\" );\n\n\t\tif ( viewIds.size() <= 1 )\n\t\t{\n\t\t\tIOFunctions.println( \"Only \" + viewIds.size() + \" views selected, need at least two for this to make sense.\" );\n\t\t\treturn null;\n\t\t}\n\n\t\treturn new ICPRefinementParameters( viewIds );\n\t}\n\n\tpublic static boolean getGUIParametersAdvanced( final SpimData2 data, final ICPRefinementParameters params )\n\t{\n\t\t//\n\t\t// get advanced parameters\n\t\t//\n\t\tfinal GenericDialog gd = new GenericDialog( \"Expert Refine by ICP\" );\n\n\t\tfinal ArrayList< String > labels = getAllLabels( params.viewIds, data );\n\n\t\tif ( labels.size() == 0 )\n\t\t{\n\t\t\tIOFunctions.println( \"No interest point defined, please detect interest point and re-run\" );\n\t\t\tnew Interest_Point_Detection().detectInterestPoints( data, params.viewIds );\n\t\t\treturn false;\n\t\t}\n\n\t\tfinal String[] labelChoice = new String[ labels.size() ];\n\n\t\tfor ( int i = 0; i < labels.size(); ++i )\n\t\t\tlabelChoice[ i ] = labels.get( i );\n\n\t\tif ( defaultLabelDialog >= labelChoice.length )\n\t\t\tdefaultLabelDialog = 0;\n\n\t\tgd.addChoice( \"Interest_Points\", labelChoice, labelChoice[ defaultLabelDialog ] );\n\t\tgd.addNumericField( \"ICP_maximum_error\", defaultICPError, 2 );\n\t\tgd.addChoice( \"Transformation model\", TransformationModelGUI.modelChoice, TransformationModelGUI.modelChoice[ defaultModel ] );\n\t\tgd.addCheckbox( \"Regularize_model\", defaultRegularize );\n\n\t\tfinal ArrayList< Channel > channels = SpimData2.getAllChannelsSorted( data, params.viewIds );\n\t\tfinal String[] channelChoice = new String[ 2 + channels.size() ];\n\t\tchannelChoice[ 0 ] = \"Do not group\";\n\t\tchannelChoice[ 1 ] = \"Group all\";\n\t\tfor ( int i = 0; i < channels.size(); ++i )\n\t\t\tchannelChoice[ i + 2 ] = \"Only channel \" + channels.get( i ).getName();\n\t\tif ( defaultChannelChoice >= channelChoice.length )\n\t\t\tdefaultChannelChoice = 0;\n\n\t\tgd.addChoice( \"Group_channels\", channelChoice, channelChoice[ defaultChannelChoice ] );\n\t\tgd.addCheckbox( \"Group_tiles\", false );\n\t\tgd.addCheckbox( \"Group_illuminations\", false );\n\n\t\tgd.showDialog();\n\t\tif ( gd.wasCanceled() )\n\t\t\treturn false;\n\n\t\tparams.label = labels.get( defaultLabelDialog = gd.getNextChoiceIndex() );\n\t\tparams.maxError = defaultICPError = gd.getNextNumber();\n\t\tTransformationModelGUI model = new TransformationModelGUI( defaultModel = gd.getNextChoiceIndex() );\n\n\t\tif ( defaultRegularize = gd.getNextBoolean() )\n\t\t\tif ( !model.queryRegularizedModel() )\n\t\t\t\treturn false;\n\n\t\tparams.transformationModel = model.getModel();\n\n\t\tfinal int channelGroup = gd.getNextChoiceIndex();\n\t\tif ( channelGroup > 0 )\n\t\t{\n\t\t\tparams.groupChannels = true;\n\t\t\tif ( channelGroup >= 2 )\n\t\t\t{\n\t\t\t\tfor ( int i = 0; i < channels.size(); ++i )\n\t\t\t\t{\n\t\t\t\t\tif ( channelGroup - 2 != i )\n\t\t\t\t\t\tparams.doNotGroupChannels.add( channels.get( i ).getId() );\n\t\t\t\t\telse\n\t\t\t\t\t\tIOFunctions.println( \"Only grouping tiles & illuminations for channel: \" + channels.get( i ).getName() );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tparams.groupChannels = false;\n\t\t}\n\t\tparams.groupTiles = gd.getNextBoolean();\n\t\tparams.groupIllums = gd.getNextBoolean();\n\n\t\tparams.transformationDescription = \"Expert ICP Refinement\";\n\n\t\treturn true;\n\t}\n\n\tpublic static boolean getGUIParametersSimple(\n\t\t\tfinal ICPType icpType,\n\t\t\tfinal SpimData2 data,\n\t\t\tfinal ICPRefinementParameters params,\n\t\t\tfinal int downsamplingChoice,\n\t\t\tfinal int thresholdChoice,\n\t\t\tfinal int distanceChoice )\n\t{\n\t\tif ( icpType == ICPType.TileRefine )\n\t\t{\n\t\t\t// if we refine tiles only, we just group everything else together\n\t\t\tparams.groupTiles = false;\n\t\t\tparams.groupChannels = true;\n\t\t\tparams.groupIllums = true;\n\t\t\tparams.transformationDescription = \"Tile ICP Refinement\";\n\t\t}\n\t\telse if ( icpType == ICPType.ChromaticAbberation )// chromatic aberration\n\t\t{\n\t\t\t// if we do chromatic abberation correction, we should group the tiles,\n\t\t\t// but only those of one of the channels so the other channels' tiles can\n\t\t\t// float all freely around\n\t\t\tparams.groupTiles = true;\n\t\t\tparams.groupChannels = false;\n\t\t\tparams.groupIllums = true;\n\t\t\tparams.transformationDescription = \"Chromatic Aberration Correction (ICP)\";\n\n\t\t\tfinal ArrayList< Channel > channels = SpimData2.getAllChannelsSorted( data, params.viewIds );\n\t\t\tif ( channels.size() <= 1 )\n\t\t\t{\n\t\t\t\tIOFunctions.println( \"Only one channel selected, cannot do a chromatic aberration correction.\" );\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tIOFunctions.println( \"Only grouping tiles & illuminations for channel: \" + channels.get( 0 ).getName() );\n\n\t\t\tfor ( int i = 1; i < channels.size(); ++i )\n\t\t\t\tparams.doNotGroupChannels.add( channels.get( i ).getId() );\n\t\t}\n\t\telse //all\n\t\t{\n\t\t\t// if we refine tiles only, we just group everything else together\n\t\t\tparams.groupTiles = false;\n\t\t\tparams.groupChannels = false;\n\t\t\tparams.groupIllums = false;\n\t\t\tparams.transformationDescription = \"ICP Refinement (over all)\";\n\t\t}\n\n\t\tparams.label = \"forICP_\" + downsamplingChoice + \"_\" + thresholdChoice;\n\n\t\t// DoG\n\t\tif ( !presentForAll( params.label, params.viewIds, data ) )\n\t\t{\n\t\t\t// each channel get the same min/max intensity for the interestpoints\n\t\t\tfinal HashSet< Class<? extends Entity> > factors = new HashSet<>();\n\t\t\tfactors.add( Channel.class );\n\n\t\t\tfor ( final Group< ViewDescription > group : Group.splitBy( SpimData2.getAllViewDescriptionsSorted( data,params.viewIds ), factors ) )\n\t\t\t{\n\t\t\t\tIOFunctions.println( new Date( System.currentTimeMillis() ) + \": Processing channel: \" + group.getViews().iterator().next().getViewSetup().getChannel().getName() );\n\n\t\t\t\tfinal DoGParameters dog = new DoGParameters();\n\n\t\t\t\tdog.imgloader = data.getSequenceDescription().getImgLoader();\n\t\t\t\tdog.toProcess = new ArrayList< ViewDescription >();\n\t\t\t\tdog.toProcess.addAll( group.getViews() );\n\n\t\t\t\tif ( thresholdChoice == 0 )\n\t\t\t\t\tdog.threshold = 0.001;\n\t\t\t\telse if ( thresholdChoice == 1 )\n\t\t\t\t\tdog.threshold = 0.0075;\n\t\t\t\telse //if ( defaultThreshold == 2 )\n\t\t\t\t\tdog.threshold = 0.015;\n\n\t\t\t\tswitch ( downsamplingChoice )\n\t\t\t\t{\n\t\t\t\t\tcase 0:\n\t\t\t\t\t\tdog.downsampleXY = 2;\n\t\t\t\t\t\tdog.downsampleZ = 1;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 1:\n\t\t\t\t\t\tdog.downsampleXY = 4;\n\t\t\t\t\t\tdog.downsampleZ = 2;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 2:\n\t\t\t\t\t\tdog.downsampleXY = 8;\n\t\t\t\t\t\tdog.downsampleZ = 4;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 3:\n\t\t\t\t\t\tdog.downsampleXY = 16;\n\t\t\t\t\t\tdog.downsampleZ = 8;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tdog.downsampleXY = 4;\n\t\t\t\t\t\tdog.downsampleZ = 2;\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tdog.sigma = 1.6;\n\n\t\t\t\tdog.limitDetections = true;\n\t\t\t\tdog.maxDetections = 10000;\n\t\t\t\tdog.maxDetectionsTypeIndex = 0; // brightest\n\n\t\t\t\tIOFunctions.println( \"DoG Threshold = \" + dog.threshold );\n\t\t\t\tIOFunctions.println( \"DoG Sigma = \" + dog.sigma );\n\n\t\t\t\tdog.showProgress( 0, 1 );\n\n\t\t\t\tif ( group.getViews().size() > 1 )\n\t\t\t\t{\n\t\t\t\t\tfinal double[] minmax = minmax( data, dog.toProcess );\n\t\t\t\t\tdog.minIntensity = minmax[ 0 ];\n\t\t\t\t\tdog.maxIntensity = minmax[ 1 ];\n\t\t\t\t}\n\n\t\t\t\tfinal HashMap< ViewId, List< InterestPoint > > points = DoG.findInterestPoints( dog );\n\n\t\t\t\tInterestPointTools.addInterestPoints( data, params.label, points, \"DoG, sigma=1.4, downsampleXY=\" + dog.downsampleXY + \", downsampleZ=\" + dog.downsampleZ );\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tIOFunctions.println( \"Interestpoint '\" + params.label + \"' already defined for all views, using those.\" );\n\t\t}\n\n\t\tparams.transformationModel = new InterpolatedAffineModel3D< AffineModel3D, RigidModel3D >(\n\t\t\t\tnew AffineModel3D(),\n\t\t\t\tnew RigidModel3D(),\n\t\t\t\t0.1f );\n\n\t\tif ( distanceChoice == 0 )\n\t\t\tparams.maxError = defaultICPError = 1.0;\n\t\telse if ( distanceChoice == 1 )\n\t\t\tparams.maxError = defaultICPError = 5.0;\n\t\telse\n\t\t\tparams.maxError = defaultICPError = 20;\n\n\t\treturn true;\n\t}\n\n\tpublic static void refine(\n\t\t\tfinal SpimData2 data,\n\t\t\tfinal ICPRefinementParameters params,\n\t\t\tfinal DemoLinkOverlay overlay )\n\t{\n\t\tIOFunctions.println( params );\n\n\t\t//\n\t\t// run the alignment\n\t\t//\n\t\tfinal IterativeClosestPointParameters icpp =\n\t\t\t\tnew IterativeClosestPointParameters(\n\t\t\t\t\t\tparams.transformationModel,\n\t\t\t\t\t\tparams.maxError * 2,\n\t\t\t\t\t\t100,\n\t\t\t\t\t\ttrue,\n\t\t\t\t\t\tparams.maxError,\n\t\t\t\t\t\t200 );\n\n\t\tfinal Map< ViewId, String > labelMap = new HashMap<>();\n\n\t\tfor ( final ViewId viewId : params.viewIds )\n\t\t\tlabelMap.put( viewId, params.label );\n\n\t\t// load & transform all interest points\n\t\tfinal Map< ViewId, List< InterestPoint > > interestpoints =\n\t\t\t\tTransformationTools.getAllTransformedInterestPoints(\n\t\t\t\t\tparams.viewIds,\n\t\t\t\t\tdata.getViewRegistrations().getViewRegistrations(),\n\t\t\t\t\tdata.getViewInterestPoints().getViewInterestPoints(),\n\t\t\t\t\tlabelMap );\n\n\t\t// identify groups/subsets\n\t\tSet< Group< ViewId > > groups = AdvancedRegistrationParameters.getGroups( data, params.viewIds, params.groupTiles, params.groupIllums, params.groupChannels, false );\n\n\t\tif ( params.doNotGroupChannels.size() > 0 )\n\t\t{\n\t\t\tIOFunctions.println( \"Groups before: \");\n\n\t\t\tfor ( final Group< ViewId > group : groups )\n\t\t\t\tIOFunctions.println( group );\n\n\t\t\tfor ( final int channelId : params.doNotGroupChannels )\n\t\t\t\tgroups = splitGroupsForChannelOverTile( data, groups, channelId );\n\n\t\t\tIOFunctions.println( \"Groups after splitting: \");\n\n\t\t\tfor ( final Group< ViewId > group : groups )\n\t\t\t\tIOFunctions.println( group );\n\t\t}\n\n\t\tfinal PairwiseSetup< ViewId > setup = new AllToAll<>( params.viewIds, groups );\n\t\tIOFunctions.println( \"Defined pairs, removed \" + setup.definePairs().size() + \" redundant view pairs.\" );\n\t\tIOFunctions.println( \"Removed \" + setup.removeNonOverlappingPairs( new SimpleBoundingBoxOverlap<>( data ) ).size() + \" pairs because they do not overlap.\" );\n\t\tsetup.reorderPairs();\n\t\tsetup.detectSubsets();\n\t\tsetup.sortSubsets();\n\t\tfinal ArrayList< Subset< ViewId > > subsets = setup.getSubsets();\n\t\tIOFunctions.println( \"Identified \" + subsets.size() + \" subsets \" );\n\n\t\tif ( overlay != null )\n\t\t{\n\t\t\toverlay.getFilteredResults().clear();\n\t\t\toverlay.getInconsistentResults().clear();\n\t\t}\n\n\t\tfor ( final Subset< ViewId > subset : subsets )\n\t\t{\n\t\t\t// fix view(s)\n\t\t\tfinal List< ViewId > fixedViews = setup.getDefaultFixedViews();\n\t\t\tfinal ViewId fixedView = subset.getViews().iterator().next();\n\t\t\tfixedViews.add( fixedView );\n\t\t\tIOFunctions.println( \"Removed \" + subset.fixViews( fixedViews ).size() + \" views due to fixing view tpId=\" + fixedView.getTimePointId() + \" setupId=\" + fixedView.getViewSetupId() );\n\n\t\t\tHashMap< ViewId, mpicbg.models.Tile > models;\n\n\t\t\tif ( Interest_Point_Registration.hasGroups( subsets ) )\n\t\t\t\tmodels = groupedSubset( data, subset, interestpoints, labelMap, icpp, fixedViews, overlay );\n\t\t\telse\n\t\t\t\tmodels = pairSubset( data, subset, interestpoints, labelMap, icpp, fixedViews, overlay );\n\n\t\t\tif ( models == null )\n\t\t\t\tcontinue;\n\n\t\t\t// pre-concatenate models to spimdata2 viewregistrations (from SpimData(2))\n\t\t\tfor ( final ViewId viewId : subset.getViews() )\n\t\t\t{\n\t\t\t\tfinal mpicbg.models.Tile tile = models.get( viewId );\n\t\t\t\tfinal ViewRegistration vr = data.getViewRegistrations().getViewRegistrations().get( viewId );\n\n\t\t\t\tTransformationTools.storeTransformation( vr, viewId, tile, null, params.transformationDescription );\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static final HashMap< ViewId, mpicbg.models.Tile > pairSubset(\n\t\t\tfinal SpimData2 spimData,\n\t\t\tfinal Subset< ViewId > subset,\n\t\t\tfinal Map< ViewId, List< InterestPoint > > interestpoints,\n\t\t\tfinal Map< ViewId, String > labelMap,\n\t\t\tfinal IterativeClosestPointParameters icpp,\n\t\t\tfinal List< ViewId > fixedViews,\n\t\t\tfinal DemoLinkOverlay overlay )\n\t{\n\t\tfinal List< Pair< ViewId, ViewId > > pairs = subset.getPairs();\n\n\t\tif ( pairs.size() <= 0 )\n\t\t{\n\t\t\tIOFunctions.println( \"No image pair for comparison left, we need at least one pair for this to make sense.\" );\n\t\t\treturn null;\n\t\t}\n\n\t\tfor ( final Pair< ViewId, ViewId > pair : pairs )\n\t\t\tSystem.out.println( Group.pvid( pair.getA() ) + \" <=> \" + Group.pvid( pair.getB() ) );\n\n\t\t// compute all pairwise matchings\n\t\tfinal List< Pair< Pair< ViewId, ViewId >, PairwiseResult< InterestPoint > > > resultsPairs =\n\t\t\t\tMatcherPairwiseTools.computePairs( pairs, interestpoints, new IterativeClosestPointPairwise< InterestPoint >( icpp ) );\n\n\t\tif ( overlay != null )\n\t\t{\n\t\t\tfinal HashSet< Pair< Group< ViewId >, Group< ViewId > > > results = new HashSet<>();\n\n\t\t\tfor ( final Pair< Pair< ViewId, ViewId >, PairwiseResult< InterestPoint > > result : resultsPairs )\n\t\t\t{\n\t\t\t\tif ( result.getB().getInliers().size() > 0 )\n\t\t\t\t{\n\t\t\t\t\tresults.add( new ValuePair< Group<ViewId>, Group<ViewId> >( new Group< ViewId >( result.getA().getA() ), new Group< ViewId >( result.getA().getB() ) ) );\n\t\t\t\t}\n\t\t\t}\n\n\t\t\toverlay.setPairwiseLinkInterface( new PairwiseLinkImpl( results ) );\n\t\t}\n\n\t\t// clear correspondences\n\t\tMatcherPairwiseTools.clearCorrespondences( subset.getViews(), spimData.getViewInterestPoints().getViewInterestPoints(), labelMap );\n\n\t\t// add the corresponding detections and output result\n\t\tfor ( final Pair< Pair< ViewId, ViewId >, PairwiseResult< InterestPoint > > p : resultsPairs )\n\t\t{\n\t\t\tfinal ViewId vA = p.getA().getA();\n\t\t\tfinal ViewId vB = p.getA().getB();\n\n\t\t\tfinal InterestPointList listA = spimData.getViewInterestPoints().getViewInterestPoints().get( vA ).getInterestPointList( labelMap.get( vA ) );\n\t\t\tfinal InterestPointList listB = spimData.getViewInterestPoints().getViewInterestPoints().get( vB ).getInterestPointList( labelMap.get( vB ) );\n\n\t\t\tMatcherPairwiseTools.addCorrespondences( p.getB().getInliers(), vA, vB, labelMap.get( vA ), labelMap.get( vB ), listA, listB );\n\n\t\t\tIOFunctions.println( p.getB().getFullDesc() );\n\t\t}\n\n\t\tfinal ConvergenceStrategy cs = new ConvergenceStrategy( icpp.getMaxDistance() );\n\t\tfinal PointMatchCreator pmc = new InterestPointMatchCreator( resultsPairs );\n\n\t\t// run global optimization\n\t\treturn (HashMap< ViewId, mpicbg.models.Tile >)GlobalOpt.compute( (Model)icpp.getModel().copy(), pmc, cs, fixedViews, subset.getGroups() );\n\t}\n\n\tpublic static HashMap< ViewId, mpicbg.models.Tile > groupedSubset(\n\t\t\tfinal SpimData2 spimData,\n\t\t\tfinal Subset< ViewId > subset,\n\t\t\tfinal Map< ViewId, List< InterestPoint > > interestpoints,\n\t\t\tfinal Map< ViewId, String > labelMap,\n\t\t\tfinal IterativeClosestPointParameters icpp,\n\t\t\tfinal List< ViewId > fixedViews,\n\t\t\tfinal DemoLinkOverlay overlay )\n\t{\n\t\tfinal List< Pair< Group< ViewId >, Group< ViewId > > > groupedPairs = subset.getGroupedPairs();\n\t\tfinal Map< Group< ViewId >, List< GroupedInterestPoint< ViewId > > > groupedInterestpoints = new HashMap<>();\n\t\tfinal InterestPointGrouping< ViewId > ipGrouping = new InterestPointGroupingMinDistance<>( interestpoints );\n\n\t\tif ( groupedPairs.size() <= 0 )\n\t\t{\n\t\t\tIOFunctions.println( \"No pair of grouped images for comparison left, we need at least one pair for this to make sense.\" );\n\t\t\treturn null;\n\t\t}\n\n\t\t// which groups exist\n\t\tfinal Set< Group< ViewId > > groups = new HashSet<>();\n\n\t\tfor ( final Pair< Group< ViewId >, Group< ViewId > > pair : groupedPairs )\n\t\t{\n\t\t\tgroups.add( pair.getA() );\n\t\t\tgroups.add( pair.getB() );\n\n\t\t\tSystem.out.print( \"[\" + pair.getA() + \"] <=> [\" + pair.getB() + \"]\" );\n\n\t\t\tif ( !groupedInterestpoints.containsKey( pair.getA() ) )\n\t\t\t{\n\t\t\t\tSystem.out.print( \", grouping interestpoints for \" + pair.getA() );\n\n\t\t\t\tgroupedInterestpoints.put( pair.getA(), ipGrouping.group( pair.getA() ) );\n\t\t\t}\n\n\t\t\tif ( !groupedInterestpoints.containsKey( pair.getB() ) )\n\t\t\t{\n\t\t\t\tSystem.out.print( \", grouping interestpoints for \" + pair.getB() );\n\n\t\t\t\tgroupedInterestpoints.put( pair.getB(), ipGrouping.group( pair.getB() ) );\n\t\t\t}\n\n\t\t\tSystem.out.println();\n\t\t}\n\n\t\tfinal List< Pair< Pair< Group< ViewId >, Group< ViewId > >, PairwiseResult< GroupedInterestPoint< ViewId > > > > resultsGroups =\n\t\t\t\tMatcherPairwiseTools.computePairs( groupedPairs, groupedInterestpoints, new IterativeClosestPointPairwise< GroupedInterestPoint< ViewId > >( icpp ) );\n\n\t\tif ( overlay != null )\n\t\t{\n\t\t\tfinal HashSet< Pair< Group< ViewId >, Group< ViewId > > > results = new HashSet<>();\n\n\t\t\tfor ( final Pair< Pair< Group< ViewId >, Group< ViewId > >, PairwiseResult< GroupedInterestPoint< ViewId > > > result : resultsGroups )\n\t\t\t\tif ( result.getB().getInliers().size() > 0 )\n\t\t\t\t\tresults.add( result.getA() );\n\n\t\t\toverlay.setPairwiseLinkInterface( new PairwiseLinkImpl( results ) );\n\t\t}\n\n\t\t// clear correspondences and get a map linking ViewIds to the correspondence lists\n\t\tfinal Map< ViewId, List< CorrespondingInterestPoints > > cMap = MatcherPairwiseTools.clearCorrespondences( subset.getViews(), spimData.getViewInterestPoints().getViewInterestPoints(), labelMap );\n\n\t\t// add the corresponding detections and output result\n\t\tfinal List< Pair< Pair< ViewId, ViewId >, PairwiseResult< GroupedInterestPoint< ViewId > > > > resultG =\n\t\t\t\tMatcherPairwiseTools.addCorrespondencesFromGroups( resultsGroups, spimData.getViewInterestPoints().getViewInterestPoints(), labelMap, cMap );\n\n\t\t// run global optimization\n\t\tfinal ConvergenceStrategy cs = new ConvergenceStrategy( 10.0 );\n\t\tfinal PointMatchCreator pmc = new InterestPointMatchCreator( resultG );\n\n\t\treturn (HashMap< ViewId, mpicbg.models.Tile >)GlobalOpt.compute( (Model)icpp.getModel().copy(), pmc, cs, fixedViews, groups );\n\t}\n\n\t/**\n\t * TODO: this is just a hack, we need to change the original splitorcombine method in Group to support not only classes, but classed + ids\n\t * \n\t * @param spimData\n\t * @param groups\n\t * @param splitChannel\n\t */\n\tprivate static HashSet< Group< ViewId > > splitGroupsForChannelOverTile( final SpimData2 spimData, final Set< Group< ViewId > > groups, final int splitChannel )\n\t{\n\t\tfinal HashSet< Group< ViewId > > newGroups = new HashSet<>();\n\n\t\tfinal Group< ViewId > remainingGroup = new Group<>();\n\t\tfinal HashMap< Tile, Group< ViewId > > result = new HashMap<>();\n\n\t\tfor ( final Group< ViewId > group : groups )\n\t\t{\n\t\t\tfor ( final ViewId viewId : group.getViews() )\n\t\t\t{\n\t\t\t\tfinal ViewDescription vd = spimData.getSequenceDescription().getViewDescription( viewId );\n\n\t\t\t\tif ( splitChannel == vd.getViewSetup().getChannel().getId() )\n\t\t\t\t{\n\t\t\t\t\t// group the still grouped ones (e.g. illuminations)\n\t\t\t\t\tif ( result.containsKey( vd.getViewSetup().getTile() ) )\n\t\t\t\t\t\tresult.get( vd.getViewSetup().getTile() ).getViews().add( viewId );\n\t\t\t\t\telse\n\t\t\t\t\t\tresult.put( vd.getViewSetup().getTile(), new Group<>( viewId ) );\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tremainingGroup.getViews().add( viewId );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif ( remainingGroup.size() > 0 )\n\t\t\tnewGroups.add( remainingGroup );\n\n\t\tnewGroups.addAll( result.values() );\n\n\t\treturn newGroups;\n\t}\n\n\tpublic static double[] minmax( final SpimData2 spimData, final Collection< ? extends ViewId > viewIdsToProcess )\n\t{\n\t\tIOFunctions.println( \"(\" + new Date( System.currentTimeMillis() ) + \"): Determining it approximate Min & Max for all views at lowest resolution levels ... \" );\n\n\t\tIJ.showProgress( 0 );\n\n\t\tfinal ImgLoader imgLoader = spimData.getSequenceDescription().getImgLoader();\n\n\t\tdouble min = Double.MAX_VALUE;\n\t\tdouble max = -Double.MAX_VALUE;\n\n\t\tint count = 0;\n\t\tfor ( final ViewId view : viewIdsToProcess )\n\t\t{\n\t\t\tfinal double[] minmax = FusionTools.minMaxApprox( DownsampleTools.openAtLowestLevel( imgLoader, view ) );\n\t\t\tmin = Math.min( min, minmax[ 0 ] );\n\t\t\tmax = Math.max( max, minmax[ 1 ] );\n\n\t\t\tIOFunctions.println( \"(\" + new Date( System.currentTimeMillis() ) + \"): View \" + Group.pvid( view ) + \", Min=\" + minmax[ 0 ] + \" max=\" + minmax[ 1 ] );\n\n\t\t\tIJ.showProgress( (double)++count / viewIdsToProcess.size() );\n\t\t}\n\n\t\tIOFunctions.println( \"(\" + new Date( System.currentTimeMillis() ) + \"): Total Min=\" + min + \" max=\" + max );\n\n\t\treturn new double[]{ min, max };\n\t}\n\n\tpublic static boolean presentForAll( final String label, final Collection< ? extends ViewId > viewIds, final SpimData2 data )\n\t{\n\t\tfor ( final ViewId viewId : viewIds )\n\t\t\tif ( data.getViewInterestPoints().getViewInterestPointLists( viewId ).getInterestPointList( label ) == null )\n\t\t\t\treturn false;\n\n\t\treturn true;\n\t}\n\n\tpublic static ArrayList< String > getAllLabels( final Collection< ? extends ViewId > viewIds, final SpimData2 data )\n\t{\n\t\tfinal ViewId view1 = viewIds.iterator().next();\n\n\t\tfinal Set< String > labels = data.getViewInterestPoints().getViewInterestPointLists( view1 ).getHashMap().keySet();\n\t\tfinal ArrayList< String > presentLabels = new ArrayList<>();\n\n\t\tfor ( final String label : labels )\n\t\t\tif ( presentForAll( label, viewIds, data ) )\n\t\t\t\tpresentLabels.add( label );\n\n\t\tCollections.sort( presentLabels );\n\n\t\treturn presentLabels;\n\t}\n}",
"public static class ICPRefinementParameters\n{\n\tpublic boolean groupTiles, groupIllums, groupChannels;\n\n\t// some channels that should not be grouped\n\tpublic ArrayList< Integer > doNotGroupChannels = new ArrayList<>();\n\t// some illuminations that should not be grouped\n\t//public ArrayList< Integer > doNotGroupIllums = new ArrayList<>();\n\t// some tiles that should not be grouped\n\t//public ArrayList< Integer > doNotGroupTiles = new ArrayList<>();\n\n\tpublic String label, transformationDescription;\n\tpublic double maxError;\n\tpublic AbstractModel< ? > transformationModel;\n\n\tfinal List<ViewId > viewIds;\n\n\tpublic ICPRefinementParameters( final List<ViewId > viewIds )\n\t{\n\t\tthis.viewIds = viewIds;\n\t}\n\n\tpublic String toString()\n\t{\n\t\tString o = \"ICPRefinementParameters:\\n\"\n\t\t\t\t+ \"Interest point label: \" + label + \"\\n\"\n\t\t\t\t+ \"maxError: \" + maxError + \"\\n\"\n\t\t\t\t+ \"transformationModel: \" + transformationModel.getClass().getSimpleName() + \"\\n\"\n\t\t\t\t+ \"groupTiles: \" + groupTiles + \"\\n\"\n\t\t\t\t+ \"groupIllums: \" + groupIllums + \"\\n\"\n\t\t\t\t+ \"groupChannels: \" + groupChannels + \"\\n\"\n\t\t\t\t+ \"doNotGroupChannels: [\";\n\n\t\t\t\tfor ( final int ch : doNotGroupChannels )\n\t\t\t\t\to += ch + \", \";\n\n\t\t\t\to += \"]\";\n\n\t\t\t\treturn o;\n\t}\n}",
"public static enum ICPType{ TileRefine, ChromaticAbberation, All, Expert }"
] | import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JComponent;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import mpicbg.spim.data.generic.AbstractSpimData;
import mpicbg.spim.data.generic.sequence.AbstractSequenceDescription;
import net.preibisch.legacy.io.IOFunctions;
import net.preibisch.mvrecon.fiji.plugin.util.MouseOverPopUpStateChanger;
import net.preibisch.mvrecon.fiji.plugin.util.MouseOverPopUpStateChanger.StateChanger;
import net.preibisch.mvrecon.fiji.spimdata.SpimData2;
import net.preibisch.mvrecon.fiji.spimdata.explorer.ExplorerWindow;
import net.preibisch.mvrecon.fiji.spimdata.explorer.FilteredAndGroupedExplorerPanel;
import net.preibisch.mvrecon.fiji.spimdata.explorer.GroupedRowWindow;
import net.preibisch.mvrecon.fiji.spimdata.explorer.popup.ExplorerWindowSetable;
import net.preibisch.mvrecon.fiji.spimdata.explorer.popup.Separator;
import net.preibisch.stitcher.algorithm.SpimDataFilteringAndGrouping;
import net.preibisch.stitcher.gui.overlay.DemoLinkOverlay;
import net.preibisch.stitcher.process.ICPRefinement;
import net.preibisch.stitcher.process.ICPRefinement.ICPRefinementParameters;
import net.preibisch.stitcher.process.ICPRefinement.ICPType; | /*-
* #%L
* Multiview stitching of large datasets.
* %%
* Copyright (C) 2016 - 2021 Big Stitcher developers.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
package net.preibisch.stitcher.gui.popup;
public class RefineWithICPPopup extends JMenu implements ExplorerWindowSetable
{
private static final long serialVersionUID = 1L;
| DemoLinkOverlay overlay; | 1 |
i2p/i2p.itoopie | src/net/i2p/itoopie/i2pcontrol/methods/GetI2PControl.java | [
"public class InvalidParametersException extends Exception {\n\n\t/**\n\t * Signifies that the paramers we sent were invalid for the used JSONRPC2\n\t * method.\n\t */\n\tprivate static final long serialVersionUID = 4044188679464846005L;\n\n}",
"public class InvalidPasswordException extends Exception {\n\n\t/**\n\t * The remote I2PControl server is rejecting the provided password.\n\t */\n\tprivate static final long serialVersionUID = 8461972369522962046L;\n\n}",
"public class JSONRPC2Interface {\n\tprivate static Log _log;\n\tprivate static int nonce;\n\tprivate static final int MAX_NBR_RETRIES = 2;\n\tprivate static JSONRPC2Session session;\n\tprivate static String token;\n\tprivate final static String DEFAULT_PASSWORD = \"itoopie\";\n\tprivate static String pw = DEFAULT_PASSWORD;\n\t\t\n\tstatic {\n\t\t_log = LogFactory.getLog(JSONRPC2Interface.class);\n\t\tRandom rnd = new Random();\n\t\tnonce = rnd.nextInt();\n\t}\n\n\tpublic static synchronized int incrNonce() {\n\t\treturn ++nonce;\n\t}\n\n\tpublic static void setupSession(ConfigurationManager conf) {\n\t\tURL srvURL = null;\n\t\tString srvHost = conf.getConf(\"server.hostname\", \"localhost\");\n\t\tif (srvHost.contains(\":\"))\n\t\t\tsrvHost = '[' + srvHost + ']';\n\t\tint srvPort = conf.getConf(\"server.port\", 7650);\n\t\tString srvTarget = conf.getConf(\"server.target\", \"jsonrpc\");\n\t\tString method;\n\t\tif (srvPort == 7657) {\n\t\t\t// Use HTTP for the xmlrpc webapp in the HTTP router console\n\t\t\tmethod = \"http\";\n\t\t\t// target MUST contain a /, or else console will redirect\n\t\t\t// jsonrpc to jsonrpc/ which will be fetched as a GET\n\t\t\t// and will return the HTML password form.\n\t\t\tif (!srvTarget.contains(\"/\"))\n\t\t\t\tsrvTarget += \"/\";\n\t\t} else {\n\t\t\tmethod = \"https\";\n\t\t}\n\t\ttry {\n\t\t\tsrvURL = new URL(method + \"://\" + srvHost + \":\" + srvPort + \"/\"\n\t\t\t\t\t+ srvTarget);\n\t\t} catch (MalformedURLException e) {\n\t\t\t_log.error(\"Bad URL: \" + method + \"://\" + srvHost + \":\" + srvPort + \"/\"\n\t\t\t\t\t+ srvTarget, e);\n\t\t}\n\t\tpw = conf.getConf(\"server.password\", DEFAULT_PASSWORD);\n\t\tsession = new JSONRPC2Session(srvURL);\n\t\tsession.trustAllCerts(true);\n\t}\n\t\n\tpublic static void testSettings(ConfigurationManager conf) throws InvalidPasswordException, JSONRPC2SessionException{\n\t\t// set in gui/Main\n\t\t//HttpsURLConnection.setDefaultHostnameVerifier(new ItoopieHostnameVerifier());\n\t\tsetupSession(conf);\n\t\tAuthenticate.execute(pw);\n\t}\n\n\tpublic static JSONRPC2Response sendReq(JSONRPC2Request req)\n\t\t\tthrows InvalidPasswordException, UnrecoverableFailedRequestException,\n\t\t\tInvalidParametersException, JSONRPC2SessionException{\n\t\treturn sendReq(req, 1);\n\t}\n\t\n\tprivate static JSONRPC2Response sendReq(JSONRPC2Request req, int tryNbr)\n\t\t\tthrows InvalidPasswordException, UnrecoverableFailedRequestException,\n\t\t\tInvalidParametersException, JSONRPC2SessionException {\n\t\tif (tryNbr > MAX_NBR_RETRIES){\n\t\t\tthrow new UnrecoverableFailedRequestException(); // Max retries reached. Throw exception.\n\t\t}\n\t\tHashMap outParams = (HashMap) req.getParams();\n\t\toutParams.put(\"Token\", token); // Add authentication token\n\t\treq.setParams(outParams);\n\n\t\tJSONRPC2Response resp = null;\n\t\ttry {\n\t\t\tresp = session.send(req);\n\t\t\t//System.out.println(\"Request: \" + req.toString());\n\t\t\t//System.out.println(\"Response: \" + resp.toString());\n\t\t\tJSONRPC2Error err = resp.getError();\n\t\t\tif (err != null) {\n\t\t\t\tswitch (err.getCode()) {\n\t\t\t\tcase -32700:\n\t\t\t\t\t// Parse error\n\t\t\t\t\t_log.error(err.getMessage());\n\t\t\t\t\tbreak;\n\t\t\t\tcase -32600:\n\t\t\t\t\t// Invalid request\n\t\t\t\t\t_log.error(err.getMessage());\n\t\t\t\t\tbreak;\n\t\t\t\tcase -32601:\n\t\t\t\t\t// Method not found\n\t\t\t\t\t_log.error(err.getMessage());\n\t\t\t\t\tbreak;\n\t\t\t\tcase -32602:\n\t\t\t\t\t// Invalid params\n\t\t\t\t\t_log.error(err.getMessage());\n\t\t\t\t\tthrow new InvalidParametersException();\n\t\t\t\t\t//break;\n\t\t\t\tcase -32603:\n\t\t\t\t\t// Internal error\n\t\t\t\t\t_log.error(\"Remote host: \" + err.getMessage());\n\t\t\t\t\tbreak;\n\n\t\t\t\t// Custom errors (as defined by the I2PControl API)\n\t\t\t\tcase -32001:\n\t\t\t\t\t// Invalid password\n\t\t\t\t\t_log.info(\"Provided password was rejected by the remote host\");\n\t\t\t\t\tthrow new InvalidPasswordException();\n\t\t\t\t\t// break;\n\t\t\t\tcase -32002:\n\t\t\t\t\t// No token\n\t\t\t\t\ttoken = Authenticate.execute(pw);\n\t\t\t\t\tthrow new FailedRequestException();\n\t\t\t\t\t// break;\n\t\t\t\tcase -32003:\n\t\t\t\t\t// Invalid token\n\t\t\t\t\ttoken = Authenticate.execute(pw);\n\t\t\t\t\tthrow new FailedRequestException();\n\t\t\t\t\t//break;\n\t\t\t\tcase -32004:\n\t\t\t\t\t// Token expired\n\t\t\t\t\ttoken = Authenticate.execute(pw);\n\t\t\t\t\tthrow new FailedRequestException();\n\t\t\t\t\t// break;\n\t\t\t\tcase -32005:\n\t\t\t\t\t// I2PControl API version not provided\n\t\t\t\t\tthrow new InvalidI2PControlAPI(err.getMessage());\n\t\t\t\tcase -32006:\n\t\t\t\t\t// I2PControl API version not supported\n\t\t\t\t\tthrow new InvalidI2PControlAPI(err.getMessage());\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn resp;\n\t\t} catch (FailedRequestException e) {\n\t\t\treturn sendReq(req, ++tryNbr);\n\t\t} catch (InvalidI2PControlAPI e) {\n\t\t\t_log.error(e);\n\t\t\treturn null;\n\t\t}\n\t}\n}",
"public class UnrecoverableFailedRequestException extends Exception {\n\t/**\n\t * Signifies that a request has been tried thoroughly anda few times and has\n\t * not worked or returned errors.\n\t */\n\tprivate static final long serialVersionUID = 4133380969869898255L;\n}",
"public enum I2P_CONTROL implements Remote{\n\tPASSWORD { \t\t\tpublic boolean isReadable(){ return false;}\n\t\t\t\t\t\tpublic boolean isWritable(){ return true;} \n\t\t\t\t\t\tpublic String toString() { return \"i2pcontrol.password\"; }},\n\t\t\t\t\t\t\n\tPORT { \t\t\t\tpublic boolean isReadable(){ return false;}\t\n\t\t\t\t\t\tpublic boolean isWritable(){ return true;} \n\t\t\t\t\t\tpublic String toString() { return \"i2pcontrol.port\"; }},\n\t\t\t\t\t\t\t\n\tADDRESS { \t\t\tpublic boolean isReadable(){ return true;}\t\n\t\t\t\t\t\tpublic boolean isWritable(){ return true;} \n\t\t\t\t\t\tpublic String toString() { return \"i2pcontrol.address\"; }}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n};",
"public class JSONRPC2Request extends JSONRPC2Message {\n\n\t\n\t/** \n\t * The requested method name. \n\t */\n\tprivate String method;\n\t\n\t\n\t/** \n\t * The request parameters. \n\t */\n\tprivate Object params;\n\t\n\t\n\t/** \n\t * The parameters type constant. \n\t */\n\tprivate JSONRPC2ParamsType paramsType;\n\t\n\t\n\t/** \n\t * The request identifier. \n\t */\n\tprivate Object id;\n\t\n\t\n\t/** \n\t * Parses a JSON-RPC 2.0 request string. This method is thread-safe.\n\t *\n\t * <p>The member order of parsed JSON objects will not be preserved \n\t * (for efficiency reasons) and the JSON-RPC 2.0 version field must be \n\t * set to \"2.0\". To change this behaviour check the optional {@link \n\t * #parse(String,boolean,boolean)} method.\n\t *\n\t * @param jsonString The JSON-RPC 2.0 request string, UTF-8 encoded.\n\t *\n\t * @return The corresponding JSON-RPC 2.0 request object.\n\t *\n\t * @throws JSONRPC2ParseException With detailed message if the parsing \n\t * failed.\n\t */\n\tpublic static JSONRPC2Request parse(final String jsonString)\n\t\tthrows JSONRPC2ParseException {\n\t\t\n\t\treturn parse(jsonString, false, false);\n\t}\n\t\n\t\n\t/** \n\t * Parses a JSON-RPC 2.0 request string. This method is thread-safe.\n\t *\n\t * @param jsonString The JSON-RPC 2.0 request string, UTF-8 encoded.\n\t * @param preserveOrder If {@code true} the member order of JSON objects\n\t * in parameters will be preserved.\n\t * @param noStrict If {@code true} the {@code \"jsonrpc\":\"2.0\"}\n\t * version field in the JSON-RPC 2.0 message will \n\t * not be checked.\n\t *\n\t * @return The corresponding JSON-RPC 2.0 request object.\n\t *\n\t * @throws JSONRPC2ParseException With detailed message if the parsing \n\t * failed.\n\t */\n\tpublic static JSONRPC2Request parse(final String jsonString, final boolean preserveOrder, final boolean noStrict)\n\t\tthrows JSONRPC2ParseException {\n\t\t\n\t\tJSONRPC2Parser parser = new JSONRPC2Parser(preserveOrder, noStrict);\n\t\t\n\t\treturn parser.parseJSONRPC2Request(jsonString);\n\t}\n\t\n\t\n\t/** \n\t * Constructs a new JSON-RPC 2.0 request with no parameters.\n\t *\n\t * @param method The name of the requested method.\n\t * @param id The request identifier echoed back to the caller. \n\t * The value must <a href=\"#map\">map</a> to a JSON \n\t * scalar ({@code null} and fractions, however, should\n\t * be avoided).\n\t */\n\tpublic JSONRPC2Request(final String method, final Object id) {\n\t\t\n\t\tsetMethod(method);\n\t\tsetParams(null);\n\t\tsetID(id);\n\t}\n\t\n\t\n\t/** \n\t * Constructs a new JSON-RPC 2.0 request with JSON array parameters.\n\t *\n\t * @param method The name of the requested method.\n\t * @param params The request parameters packed as a JSON array\n\t * (<a href=\"#map\">maps</a> to java.util.List).\n\t * @param id The request identifier echoed back to the caller. \n\t * The value must <a href=\"#map\">map</a> to a JSON \n\t * scalar ({@code null} and fractions, however, should\n\t * be avoided).\n\t */\n\tpublic JSONRPC2Request(final String method, final List params, final Object id) {\n\t\t\n\t\tsetMethod(method);\n\t\tsetParams(params);\n\t\tsetID(id);\n\t}\n\t\t\n\t\n\t/** \n\t * Constructs a new JSON-RPC 2.0 request with JSON object parameters.\n\t *\n\t * @param method The name of the requested method.\n\t * @param params The request parameters packed as a JSON object\n\t * (<a href=\"#map\">maps</a> to java.util.Map).\n\t * @param id The request identifier echoed back to the caller. \n\t * The value must <a href=\"#map\">map</a> to a JSON \n\t * scalar ({@code null} and fractions, however, should\n\t * be avoided).\n\t */\n\tpublic JSONRPC2Request(final String method, final Map params, final Object id) {\n\t\t\n\t\tsetMethod(method);\n\t\tsetParams(params);\n\t\tsetID(id);\n\t}\n\t\n\t\n\t/** \n\t * Gets the name of the requested method.\n\t *\n\t * @return The method name.\n\t */\n\tpublic String getMethod() {\n\t\t\n\t\treturn method;\n\t}\n\t\n\t\n\t/**\n\t * Sets the name of the requested method.\n\t *\n\t * @param method The method name.\n\t */\n\tpublic void setMethod(final String method) {\n\t\t\n\t\t// The method name is mandatory\n\t\tif (method == null)\n\t\t\tthrow new NullPointerException();\n\n\t\tthis.method = method;\n\t}\n\t\n\t\n\t/** \n\t * Gets the parameters type ({@link JSONRPC2ParamsType#ARRAY}, \n\t * {@link JSONRPC2ParamsType#OBJECT} or \n\t * {@link JSONRPC2ParamsType#NO_PARAMS}).\n\t *\n\t * @return The parameters type.\n\t */\n\tpublic JSONRPC2ParamsType getParamsType() {\n\t\n\t\treturn paramsType;\n\t}\n\t\n\t\n\t/** \n\t * Gets the request parameters.\n\t *\n\t * @return The parameters as {@code List} if JSON array, {@code Map} \n\t * if JSON object, or {@code null} if none.\n\t */\n\tpublic Object getParams() {\n\t\t\n\t\treturn params;\n\t}\n\t\n\t\n\t/**\n\t * Sets the request parameters.\n\t *\n\t * @param params The parameters. For a JSON array type pass a \n\t * {@code List}. For a JSON object pass a {@code Map}. \n\t * If there are no parameters pass {@code null}.\n\t */\n\tpublic void setParams(final Object params) {\n\t\n\t\tif (params == null)\n\t\t\tparamsType = JSONRPC2ParamsType.NO_PARAMS;\n\t\t\t\n\t\telse if (params instanceof List)\n\t\t\tparamsType = JSONRPC2ParamsType.ARRAY;\n\t\t\t\n\t\telse if (params instanceof Map)\n\t\t\tparamsType = JSONRPC2ParamsType.OBJECT;\n\t\t\t\n\t\telse\n\t\t\tthrow new IllegalArgumentException(\"The request parameters must be of type List, Map or null\");\n\t\t\t\n\t\tthis.params = params;\n\t}\n\t\n\t\n\t/** \n\t * Gets the request identifier.\n\t *\n\t * @return The request identifier ({@code Number}, {@code Boolean},\n\t * {@code String}) or {@code null}.\n\t */\n\tpublic Object getID() {\n\t\t\n\t\treturn id;\n\t}\n\t\n\t\n\t/**\n\t * Sets the request identifier (ID).\n\t *\n\t * @param id The request identifier echoed back to the caller. \n\t * The value must <a href=\"#map\">map</a> to a JSON \n\t * scalar ({@code null} and fractions, however, should\n\t * be avoided).\n\t */\n\tpublic void setID(final Object id) {\n\t\t\n\t\tif ( id != null &&\n\t\t ! (id instanceof Boolean) &&\n\t\t ! (id instanceof Number ) &&\n\t\t ! (id instanceof String ) )\n\t\t\tthrow new IllegalArgumentException(\"The request identifier must map to a JSON scalar\");\n\t\tthis.id = id;\n\t}\n\t\n\t\n\t/** \n\t * Gets a JSON representation of this JSON-RPC 2.0 request.\n\t *\n\t * @return A JSON object representing the request.\n\t */\n\tpublic JSONObject toJSON() {\n\t\n\t\tJSONObject req = new JSONObject();\n\t\t\n\t\treq.put(\"method\", method);\n\t\t\n\t\t// the params can be omitted if empty\n\t\tif (params != null && paramsType != JSONRPC2ParamsType.NO_PARAMS)\n\t\t\treq.put(\"params\", params);\n\t\t\n\t\treq.put(\"id\", id);\n\t\t\n\t\treq.put(\"jsonrpc\", \"2.0\");\n\t\t\n\t\treturn req;\n\t}\n}",
"public class JSONRPC2Response extends JSONRPC2Message {\n\t\n\t\n\t/** \n\t * The result. \n\t */\n\tprivate Object result = null;\n\t\n\t\n\t/** \n\t * The error object.\n\t */\n\tprivate JSONRPC2Error error = null;\n\t\n\t\n\t/** \n\t * The request identifier. \n\t */\n\tprivate Object id = null;\n\t\n\t\n\t/** \n\t * Parses a JSON-RPC 2.0 response string. This method is thread-safe.\n\t *\n\t * <p>The member order of parsed JSON objects will not be preserved \n\t * (for efficiency reasons) and the JSON-RPC 2.0 version field must be \n\t * set to \"2.0\". To change this behaviour check the optional {@link \n\t * #parse(String,boolean,boolean)} method.\n\t *\n\t * @param jsonString The JSON-RPC 2.0 response string, UTF-8 encoded.\n\t *\n\t * @return The corresponding JSON-RPC 2.0 response object.\n\t *\n\t * @throws JSONRPC2ParseException With detailed message if the parsing \n\t * failed.\n\t */\n\tpublic static JSONRPC2Response parse(final String jsonString)\n\t\tthrows JSONRPC2ParseException {\n\t\n\t\treturn parse(jsonString, false, false);\n\t}\n\t\n\t\n\t/** \n\t * Parses a JSON-RPC 2.0 response string. This method is thread-safe.\n\t *\n\t * @param jsonString The JSON-RPC 2.0 response string, UTF-8 encoded.\n\t * @param preserveOrder If {@code true} the member order of JSON objects\n\t * in results will be preserved.\n\t * @param noStrict If {@code true} the {@code \"jsonrpc\":\"2.0\"}\n\t * version field in the JSON-RPC 2.0 message will \n\t * not be checked.\n\t *\n\t * @return The corresponding JSON-RPC 2.0 response object.\n\t *\n\t * @throws JSONRPC2ParseException With detailed message if the parsing \n\t * failed.\n\t */\n\tpublic static JSONRPC2Response parse(final String jsonString, final boolean preserveOrder, final boolean noStrict)\n\t\tthrows JSONRPC2ParseException {\n\t\n\t\tJSONRPC2Parser parser = new JSONRPC2Parser(preserveOrder, noStrict);\n\t\t\n\t\treturn parser.parseJSONRPC2Response(jsonString);\n\t}\n\t\n\t\n\t/** \n\t * Creates a new JSON-RPC 2.0 response to a successful request.\n\t *\n\t * @param result The result. The value can <a href=\"#map\">map</a> \n\t * to any JSON type.\n\t * @param id The request identifier echoed back to the caller. \n\t */\n\tpublic JSONRPC2Response(final Object result, final Object id) {\n\t\n\t\tsetResult(result);\n\t\tsetID(id);\n\t}\n\t\n\t\n\t/** \n\t * Creates a new JSON-RPC 2.0 response to a failed request.\n\t * \n\t * @param error A JSON-RPC 2.0 error instance indicating the\n\t * cause of the failure.\n\t * @param id The request identifier echoed back to the caller.\n\t * Pass a {@code null} if the request identifier couldn't\n\t * be determined (e.g. due to a parse error).\n\t */\n\tpublic JSONRPC2Response(final JSONRPC2Error error, final Object id) {\n\t\n\t\tsetError(error);\n\t\tsetID(id);\n\t}\n\t\n\t\n\t/** \n\t * Indicates a successful JSON-RPC 2.0 request and sets the result. \n\t * Note that if the response was previously indicating failure this\n\t * will turn it into a response indicating success. Any previously set\n\t * error data will be invalidated.\n\t *\n\t * @param result The result. The value can <a href=\"#map\">map</a> to \n\t * any JSON type.\n\t */\n\tpublic void setResult(final Object result) {\n\t\t\n\t\tif ( result != null &&\n\t\t ! (result instanceof Boolean) &&\n\t\t ! (result instanceof Number ) &&\n\t\t ! (result instanceof String ) &&\n\t\t ! (result instanceof List ) &&\n\t\t ! (result instanceof Map ) )\n\t\t \tthrow new IllegalArgumentException(\"The result must map to a JSON type\");\n\t\t\n\t\t// result and error are mutually exclusive\n\t\tthis.result = result;\n\t\tthis.error = null;\n\t}\t\n\t\n\t\n\t/** \n\t * Gets the result of the request. The returned value has meaning\n\t * only if the request was successful. Use the {@link #getError getError}\n\t * method to check this.\n\t *\n\t * @return The result\n\t */\n\tpublic Object getResult() {\n\t\t\n\t\treturn result;\n\t}\n\t\n\t\n\t/** \n\t * Indicates a failed JSON-RPC 2.0 request and sets the error details.\n\t * Note that if the response was previously indicating success this\n\t * will turn it into a response indicating failure. Any previously set \n\t * result data will be invalidated.\n\t *\n\t * @param error A JSON-RPC 2.0 error instance indicating the\n\t * cause of the failure.\n\t */\n\tpublic void setError(final JSONRPC2Error error) {\n\t\t\n\t\tif (error == null)\n\t\t\tthrow new NullPointerException(\"The error object cannot be null\");\n\t\t\n\t\t// result and error are mutually exclusive\n\t\tthis.error = error;\n\t\tthis.result = null;\t\t\n\t}\n\t\n\t\n\t/** \n\t * Gets the error object indicating the cause of the request failure. \n\t * If a {@code null} is returned, the request succeeded and there was\n\t * no error.\n\t *\n\t * @return A JSON-RPC 2.0 error object, {@code null} if the\n\t * response indicates success.\n\t */\n\tpublic JSONRPC2Error getError() {\n\t\t\n\t\treturn error;\n\t}\n\t\n\t\n\t/**\n\t * A convinience method to check if the response indicates success or\n\t * failure of the request. Alternatively, you can use the \n\t * {@code #getError} method for this purpose.\n\t *\n\t * @return {@code true} if the request succeeded, {@code false} if\n\t * there was an error.\n\t */\n\tpublic boolean indicatesSuccess() {\n\t\t\n\t\tif (error == null)\n\t\t\treturn true;\n\t\telse\n\t\t\treturn false;\n\t}\n\t\n\t\n\t/**\n\t * Sets the request identifier echoed back to the caller.\n\t *\n\t * @param id The value must <a href=\"#map\">map</a> to a JSON scalar. \n\t * Pass a {@code null} if the request identifier couldn't \n\t * be determined (e.g. due to a parse error).\n\t */\n\tpublic void setID(final Object id) {\n\t\t\n\t\tif ( id != null &&\n\t\t ! (id instanceof Boolean) &&\n\t\t ! (id instanceof Number ) &&\n\t\t ! (id instanceof String ) )\n\t\t\tthrow new IllegalArgumentException(\"The request identifier must map to a JSON scalar\");\n\t\t\n\t\tthis.id = id;\n\t}\n\t\n\t\n\t/** \n\t * Gets the request identifier that is echoed back to the caller.\n\t *\n\t * @return The request identifier. If there was an error during the\n\t * the request retrieval (e.g. parse error) and the identifier \n\t * couldn't be determined, the value will be {@code null}.\n\t */\n\t public Object getID() {\n\t \n\t \treturn id;\n\t}\n\t\n\t\n\t/** \n\t * Gets a JSON representation of this JSON-RPC 2.0 response.\n\t *\n\t * @return A JSON object representing the response.\n\t */\n\tpublic JSONObject toJSON() {\n\t\t\n\t\tJSONObject out = new JSONObject();\n\t\t\n\t\t// Result and error are mutually exclusive\n\t\tif (error != null) {\n\t\t\tout.put(\"error\", error.toJSON());\n\t\t}\n\t\telse {\n\t\t\tout.put(\"result\", result);\n\t\t}\n\t\t\n\t\tout.put(\"id\", id);\n\t\t\n\t\tout.put(\"jsonrpc\", \"2.0\");\n\t\t\n\t\treturn out;\n\t}\n\n}",
"public class JSONRPC2SessionException extends Exception {\n\n\t\n\t/**\n\t * The exception cause is network or I/O related.\n\t */\n\tpublic static final int NETWORK_EXCEPTION = 1;\n\t\n\t\n\t/**\n\t * Unexpected \"Content-Type\" header value of the HTTP response.\n\t */\n\tpublic static final int UNEXPECTED_CONTENT_TYPE = 2;\n\t\n\t\n\t/**\n\t * Invalid JSON-RPC 2.0 response.\n\t */\n\tpublic static final int BAD_RESPONSE = 3;\n\t\n\t\n\t/**\n\t * Indicates the type of cause for this exception, see\n\t * constants.\n\t */\n\tprivate int causeType;\n\t\n\t\n\t/**\n\t * Creates a new JSON-RPC 2.0 session exception with the specified \n\t * message and cause type.\n\t *\n\t * @param message The message.\n\t * @param causeType The cause type, see the constants.\n\t */\n\tpublic JSONRPC2SessionException(final String message, final int causeType) {\n\t\n\t\tsuper(message);\n\t\tthis.causeType = causeType;\n\t}\n\t\n\t\n\t/**\n\t * Creates a new JSON-RPC 2.0 session exception with the specified \n\t * message, cause type and cause.\n\t *\n\t * @param message The message.\n\t * @param causeType The cause type, see the constants.\n\t * @param cause The original exception.\n\t */\n\tpublic JSONRPC2SessionException(final String message, final int causeType, final Throwable cause) {\n\t\n\t\tsuper(message, cause);\n\t\tthis.causeType = causeType;\n\t}\n\t\n\t\n\t/**\n\t * Returns the exception cause type.\n\t *\n\t * @return The cause type constant.\n\t */\n\tpublic int getCauseType() {\n\t\n\t\treturn causeType;\n\t}\n}"
] | import java.util.EnumMap;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import net.i2p.itoopie.i2pcontrol.InvalidParametersException;
import net.i2p.itoopie.i2pcontrol.InvalidPasswordException;
import net.i2p.itoopie.i2pcontrol.JSONRPC2Interface;
import net.i2p.itoopie.i2pcontrol.UnrecoverableFailedRequestException;
import net.i2p.itoopie.i2pcontrol.methods.I2PControl.I2P_CONTROL;
import com.thetransactioncompany.jsonrpc2.JSONRPC2Request;
import com.thetransactioncompany.jsonrpc2.JSONRPC2Response;
import com.thetransactioncompany.jsonrpc2.client.JSONRPC2SessionException; | package net.i2p.itoopie.i2pcontrol.methods;
public class GetI2PControl {
public static EnumMap<I2P_CONTROL, Object> execute(I2P_CONTROL ... settings)
throws InvalidPasswordException, JSONRPC2SessionException{
| JSONRPC2Request req = new JSONRPC2Request("I2PControl", JSONRPC2Interface.incrNonce()); | 2 |
cfg4j/cfg4j | cfg4j-core/src/test/java/org/cfg4j/source/classpath/ClasspathConfigurationSourceTest.java | [
"public class DefaultEnvironment extends ImmutableEnvironment {\n /**\n * Constructs environment named \"\" (empty string).\n */\n public DefaultEnvironment() {\n super(\"\");\n }\n\n @Override\n public String toString() {\n return \"DefaultEnvironment{}\";\n }\n}",
"public interface Environment {\n\n /**\n * Name of the environment. Should not be null.\n *\n * @return environment name. Not null.\n */\n String getName();\n\n}",
"public class ImmutableEnvironment implements Environment {\n\n private final String envName;\n\n /**\n * Construct environment named {@code envName}. This name never changes.\n *\n * @param envName environment name to use\n */\n public ImmutableEnvironment(String envName) {\n this.envName = requireNonNull(envName);\n }\n\n @Override\n public String getName() {\n return envName;\n }\n\n @Override\n public String toString() {\n return \"ImmutableEnvironment{\" +\n \"envName='\" + envName + '\\'' +\n '}';\n }\n}",
"public class MissingEnvironmentException extends RuntimeException {\n\n private static final String MISSING_ENV_MSG = \"Missing environment: \";\n\n /**\n * Environment named {@code envName} is missing.\n *\n * @param envName environment name\n */\n public MissingEnvironmentException(String envName) {\n super(MISSING_ENV_MSG + envName);\n }\n\n /**\n * Environment named {@code envName} is missing.\n *\n * @param envName environment name\n * @param cause root cause\n */\n public MissingEnvironmentException(String envName, Throwable cause) {\n super(MISSING_ENV_MSG + envName, cause);\n }\n}",
"public interface ConfigFilesProvider {\n\n /**\n * Provide a list of configuration files to use.\n * @return {@link Iterable} of configuration {@link File}s to use\n */\n Iterable<Path> getConfigFiles();\n\n}"
] | import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.assertj.core.data.MapEntry;
import org.cfg4j.source.context.environment.DefaultEnvironment;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.ImmutableEnvironment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.cfg4j.source.context.filesprovider.ConfigFilesProvider;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension; | /*
* Copyright 2015-2018 Norbert Potocki (norbert.potocki@nort.pl)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cfg4j.source.classpath;
@ExtendWith(MockitoExtension.class)
class ClasspathConfigurationSourceTest {
private TempConfigurationClasspathRepo classpathRepo;
private ConfigFilesProvider configFilesProvider;
private ClasspathConfigurationSource source;
@BeforeEach
void setUp() {
classpathRepo = new TempConfigurationClasspathRepo();
source = new ClasspathConfigurationSource();
source.init();
}
@AfterEach
void tearDown() throws Exception {
classpathRepo.close();
}
@Test
void getConfigurationReadsFromGivenPath() {
Environment environment = new ImmutableEnvironment("otherApplicationConfigs");
assertThat(source.getConfiguration(environment)).containsOnly(MapEntry.entry("some.setting", "otherAppSetting"));
}
@Test
void getConfigurationDisallowsLeadingSlashInClasspathLocation() {
Environment environment = new ImmutableEnvironment("/otherApplicationConfigs");
assertThatThrownBy(() -> source.getConfiguration(environment)).isExactlyInstanceOf(MissingEnvironmentException.class);
}
@Test
void getConfigurationReadsFromGivenFiles() {
configFilesProvider = () -> Arrays.asList(
Paths.get("application.properties"),
Paths.get("otherConfig.properties")
);
source = new ClasspathConfigurationSource(configFilesProvider); | assertThat(source.getConfiguration(new DefaultEnvironment())).containsOnlyKeys("some.setting", "otherConfig.setting"); | 0 |
maofw/anetty_client | src/com/netty/client/android/handler/NettyProcessorHandler.java | [
"public class ClientBroadcastReceiver extends BroadcastReceiver {\n\t// 消息通知\n\tpublic static final String NOTIFICATION_ACTION = \"com.netty.NOTIFICATION\";\n\t// 注册成功广播通知\n\tpublic static final String REG_ACTION = \"com.netty.REG\";\n\n\t@Override\n\tpublic void onReceive(Context context, Intent intent) {\n\t\ttry {\n\t\t\tLog.i(ApplicationContextClient.class.getName(), \"NotificationReceiver:\" + intent.getAction() + \":\" + context);\n\t\t} catch (Exception e) {\n\t\t\tSystem.out.println(\"NotificationReceiver\");\n\t\t}\n\t\tif (REG_ACTION.equals(intent.getAction())) {\n\t\t\t// 接收广播通知 展示notification\n\t\t\tCommandProtoc.RegistrationResult message = (CommandProtoc.RegistrationResult) intent.getSerializableExtra(SystemConsts.REGISTRATION_MESSAGE);\n\t\t\t// 通知所有监听器\n\t\t\tif (message != null) {\n\t\t\t\t// 获取本应用AppPackage名称\n\t\t\t\tif (isSelfContext(context, message.getAppPackage())) {\n\t\t\t\t\tConnectionManager.notificationRegisterListeners(message.getRegistrationId());\n\t\t\t\t}\n\t\t\t}\n\n\t\t} else if (NOTIFICATION_ACTION.equals(intent.getAction())) {\n\t\t\t// 接收广播通知 展示notification\n\t\t\tCommandProtoc.Message message = (CommandProtoc.Message) intent.getSerializableExtra(SystemConsts.NOTIFICATION_MESSAGE);\n\t\t\t// 通知所有监听器\n\t\t\tif (message != null) {\n\t\t\t\t// 获取本应用AppPackage名称\n\t\t\t\tif (isSelfContext(context, message.getAppPackage())) {\n\t\t\t\t\tConnectionManager.notificationMessageListeners(message);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * 判断是否是属于本应用\n\t * \n\t * @param context\n\t * @param appPackage\n\t * @return\n\t */\n\tprivate boolean isSelfContext(Context context, String appPackage) {\n\t\tboolean b = false;\n\t\tif (appPackage != null && appPackage.equals(context.getPackageName())) {\n\t\t\tb = true;\n\t\t}\n\t\treturn b;\n\t}\n\n}",
"public interface INettyHandlerListener<T> {\n\tpublic void callback(T t);\n}",
"public class RemoteService extends Service {\n\n\tprivate static ApplicationContextClient applicationContextClient = null;// ApplicationContextClient.getInstance();\n\n\tprivate NettyServerManager mConnectionManager = null;\n\tprivate NettyProcessorHandler mNettyProcessorHandler = null;\n\t// 服務器连接成功后监听\n\tprivate ServerStatusListener mServerStatusListener = null;\n\n\t// 广播通知\n\tprivate AlarmReceiver alarmReceiver = null;\n\n\t/**\n * \n */\n\tIBinder mBinder = new NettyServiceClientImpl();\n\n\tThread thread = null;\n\n\t/**\n\t * dao操作类\n\t */\n\tprivate static DaoMaster daoMaster;\n\n\tprivate static DaoSession daoSession;\n\n\tprivate static Context mContext;\n\n\t@Override\n\tpublic void onCreate() {\n\t\tsuper.onCreate();\n\t\t// 初始化\n\t\tinit();\n\t\t// 连接服务器\n\t\tconnectServer();\n\t\t// 注册广播\n\t\tif (alarmReceiver == null) {\n\t\t\talarmReceiver = new AlarmReceiver();\n\t\t}\n\t\t// 註冊廣播\n\t\tIntentFilter filter = new IntentFilter();\n\t\t// 心跳action\n\t\tfilter.addAction(AlarmReceiver.ACTION);\n\t\t// 连接action\n\t\tfilter.addAction(AlarmReceiver.CONNECT_ACTION);\n\t\t// 切换网络action\n\t\tfilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);\n\t\tregisterReceiver(alarmReceiver, filter);\n\t}\n\n\t/**\n\t * 初始化\n\t */\n\tprivate void init() {\n\t\tmContext = this;\n\t\tif (mNettyProcessorHandler == null) {\n\t\t\tmNettyProcessorHandler = new NettyProcessorHandler(this);\n\t\t}\n\t\tif (mServerStatusListener == null) {\n\t\t\tmServerStatusListener = new ServerStatusListener();\n\t\t}\n\n\t\tif (applicationContextClient == null) {\n\t\t\tapplicationContextClient = new ApplicationContextClient(mContext);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void onDestroy() {\n\t\tLog.i(getClass().getName(), \"onDestroy\");\n\t\tif (applicationContextClient != null) {\n\t\t\t// 下线所有设备 并且设置数据库下线状态\n\t\t\tapplicationContextClient.offlineAllDevices();\n\t\t\tapplicationContextClient.destory();\n\t\t\tapplicationContextClient = null;\n\t\t}\n\t\tif (mServerStatusListener != null) {\n\t\t\tmServerStatusListener.destory();\n\t\t\tmServerStatusListener = null;\n\t\t}\n\t\tmNettyProcessorHandler = null;\n\t\tdaoSession.clear();\n\t\tdaoMaster = null;\n\t\tif (thread != null) {\n\t\t\tthread.interrupt();\n\t\t\tthread = null;\n\t\t}\n\t\tif (alarmReceiver != null) {\n\t\t\t// 解除广播\n\t\t\tunregisterReceiver(alarmReceiver);\n\t\t}\n\t\tsuper.onDestroy();\n\t}\n\n\t/**\n\t * 连接服务器\n\t */\n\tprivate void connectServer() {\n\t\tLog.i(RemoteService.class.getName(), \"connectServer\");\n\t\tif (mConnectionManager == null) {\n\t\t\tmConnectionManager = NettyServerManager.getInstance(RemoteService.this, mNettyProcessorHandler);\n\t\t}\n\t\tLog.i(RemoteService.class.getName(), \"connectServer connectState:\" + mConnectionManager.getConnectState());\n\t\tif (mConnectionManager != null && !mConnectionManager.isConnected()) {\n\t\t\tif (thread == null) {\n\t\t\t\tthread = new Thread() {\n\t\t\t\t\tpublic void run() {\n\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tmConnectionManager.connect(SystemConsts.HOST, SystemConsts.PORT, mServerStatusListener);\n\t\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t}\n\t\t\tthread.start();\n\t\t}\n\t}\n\n\t/**\n\t * @author mrsimple\n\t */\n\tclass NettyServiceClientImpl extends Stub {\n\n\t\t@Override\n\t\tpublic void regist(String appKey, String appPackage) throws RemoteException {\n\t\t\tLog.i(RemoteService.class.getName(), \"connect\");\n\t\t\tif (mConnectionManager == null) {\n\t\t\t\tmConnectionManager = NettyServerManager.getInstance(RemoteService.this, mNettyProcessorHandler);\n\t\t\t}\n\t\t\tif (mConnectionManager != null) {\n\t\t\t\tLog.i(RemoteService.class.getName(), \"regist connectState:\" + mConnectionManager.getConnectState());\n\t\t\t\t// 服务连接成功 后监听\n\t\t\t\tConnectionListener connectionListener = new ConnectionListener(RemoteService.this, appKey, appPackage);\n\t\t\t\tif (mConnectionManager.isConnecting()) {\n\t\t\t\t\t// 注册ConnectionListener 当服务器连接成功 后通知\n\t\t\t\t\tmServerStatusListener.registNettyHandlerListener(connectionListener);\n\t\t\t\t} else if (mConnectionManager.isConnected()) {\n\t\t\t\t\t// 如果已经连接成功了 则 直接执行ConnectionListener\n\t\t\t\t\tconnectionListener.callback(null);\n\t\t\t\t\tconnectionListener = null;\n\t\t\t\t} else {\n\t\t\t\t\t// 服务器尚未连接 则进行server连接工作\n\t\t\t\t\ttry {\n\t\t\t\t\t\t// 如果服务器正在连接状态则 等待\n\t\t\t\t\t\tmConnectionManager.connect(SystemConsts.HOST, SystemConsts.PORT, connectionListener);\n\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// @Override\n\t\t// public void deviceOnline(String appPackage) throws RemoteException {\n\t\t// Log.i(RemoteService.class.getName(), \"deviceOnline\");\n\t\t// DeviceInfo deviceInfo = applicationContextClient.getDeviceInfoByAppPackage(appPackage);\n\t\t// applicationContextClient.sendDeviceOnlineMessage(deviceInfo, null);\n\t\t//\n\t\t// }\n\n\t\t@Override\n\t\tpublic void deviceOffline(String appPackage) throws RemoteException {\n\t\t\tLog.i(RemoteService.class.getName(), \"deviceOffline\");\n\t\t\tDevice deviceInfo = applicationContextClient.getDeviceInfoByAppPackage(appPackage);\n\t\t\tapplicationContextClient.sendDeviceOfflineMessage(deviceInfo, null);\n\t\t}\n\n\t}\n\n\t/*\n\t * 返回Binder实例,即实现了ILogin接口的Stub的子类,这里为LoginStubImpl [url=home.php?mod=space&uid=133757]@see[/url] android.app.Service#onBind(android.content.Intent)\n\t */\n\t@Override\n\tpublic IBinder onBind(Intent intent) {\n\t\t// 初始化\n\t\tinit();\n\t\treturn mBinder;\n\t}\n\n\t@Override\n\tpublic boolean onUnbind(Intent intent) {\n\t\treturn super.onUnbind(intent);\n\t}\n\n\t/**\n\t * 获取上下文环境\n\t * \n\t * @return\n\t */\n\tpublic static final ApplicationContextClient getApplicationContextClient() {\n\t\tif (applicationContextClient == null) {\n\t\t\tapplicationContextClient = new ApplicationContextClient(mContext);\n\t\t}\n\t\treturn applicationContextClient;\n\t}\n\n\t/**\n\t * 取得DaoMaster\n\t * \n\t * @param context\n\t * @return\n\t */\n\tpublic static DaoMaster getDaoMaster(Context context) {\n\t\tif (daoMaster == null) {\n\t\t\tOpenHelper helper = new DaoMaster.DevOpenHelper(context, SystemConsts.DATABASE_NAME, null);\n\t\t\tdaoMaster = new DaoMaster(helper.getWritableDatabase());\n\t\t}\n\t\treturn daoMaster;\n\t}\n\n\t/**\n\t * 取得DaoSession\n\t * \n\t * @param context\n\t * @return\n\t */\n\tpublic static DaoSession getDaoSession(Context context) {\n\t\tif (daoSession == null) {\n\t\t\tif (daoMaster == null) {\n\t\t\t\tdaoMaster = getDaoMaster(context);\n\t\t\t}\n\t\t\tdaoSession = daoMaster.newSession();\n\t\t}\n\t\treturn daoSession;\n\t}\n\n}",
"public class SystemConsts {\n\t/**\n\t * db名称\n\t */\n\tpublic static final String DATABASE_NAME = \"push.db\";\n\t/**\n\t * 主机IP地址\n\t */\n\tpublic static final String HOST = \"221.130.48.67\";\n\tpublic static final int PORT = 16319;\n\tpublic static final String CHANNEL = \"android\";\n\tpublic static final String NOTIFICATION_MESSAGE = \"notification_message\";\n\tpublic static final String REGISTRATION_MESSAGE = \"registration_message\";\n}",
"public class ApplicationContextClient {\n\n\t// 设备在线状态\n\tpublic static final int DEVICE_ONLINE = 1;\n\tpublic static final int DEVICE_OFFLINE = 0;\n\n\t// 是否关闭状态\n\tpublic static boolean isClosed = false;\n\tprivate ChannelHandlerContext ctx;\n\tprivate Map<String, Device> deviceInfos = new HashMap<String, Device>();\n\n\t// 保存handler 回调Listener\n\t@SuppressWarnings(\"rawtypes\")\n\tprivate Map<String, Map<Integer, INettyHandlerListener>> nettyHandlerListeners = new HashMap<String, Map<Integer, INettyHandlerListener>>();\n\n\tprivate PushDbService pushDbService;\n\tprivate Context mContext;\n\n\tpublic ApplicationContextClient(Context context) {\n\t\tthis.mContext = context;\n\t\tthis.pushDbService = PushDbService.getInstance(context);\n\t}\n\n\tpublic ChannelHandlerContext getCtx() {\n\t\treturn ctx;\n\t}\n\n\tpublic void setCtx(ChannelHandlerContext ctx) {\n\t\tthis.ctx = ctx;\n\t}\n\n\tpublic void writeAndFlush(CommandProtoc.PushMessage pushMessage) {\n\t\tif (this.ctx != null) {\n\t\t\tthis.ctx.writeAndFlush(pushMessage);\n\t\t}\n\t}\n\n\tpublic Map<String, Device> getDeviceInfos() {\n\t\tif (deviceInfos == null || deviceInfos.isEmpty()) {\n\t\t\tMap<String, Device> map = this.pushDbService.queryDevicesForMap();\n\t\t\tif (map != null && map.size() > 0) {\n\t\t\t\tdeviceInfos.putAll(map);\n\t\t\t}\n\t\t}\n\t\treturn deviceInfos;\n\t}\n\n\t/**\n\t * 根据app包名获取设备信息\n\t * \n\t * @param appPackage\n\t * @return\n\t */\n\tpublic Device getDeviceInfoByAppPackage(String appPackage) {\n\t\tMap<String, Device> map = this.getDeviceInfos();\n\t\tif (map != null && !map.isEmpty()) {\n\t\t\treturn map.get(appPackage);\n\t\t}\n\t\treturn null;\n\t}\n\n\t/**\n\t * 註冊設備\n\t * \n\t * @param appKey\n\t * @param appPackage\n\t * @param deviceId\n\t * @param imei\n\t * @param regId\n\t * @return\n\t */\n\tpublic void saveOrUpdateDevice(Device device) {\n\t\tif (device != null) {\n\t\t\tdeviceInfos.put(device.getAppPackage(), device);\n\t\t\tthis.pushDbService.saveOrUpdateDevice(device);\n\t\t}\n\t}\n\n\t/**\n\t * 生成Device对象\n\t * \n\t * @param appKey\n\t * @param appPackage\n\t * @param deviceId\n\t * @param imei\n\t * @return\n\t */\n\n\tpublic Device makeDevice(Context context, String appKey, String appPackage) {\n\n\t\tDevice deviceInfo = this.getDeviceInfoByAppPackage(appPackage);\n\t\tif (deviceInfo == null || (deviceInfo.getAppKey() != null && !deviceInfo.getAppKey().equals(appKey))) {\n\t\t\tTelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);\n\t\t\tString imei = tm.getDeviceId();\n\n\t\t\tString macAddress = null;\n\t\t\tWifiManager wifiMgr = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);\n\t\t\tWifiInfo info = (null == wifiMgr ? null : wifiMgr.getConnectionInfo());\n\t\t\tif (null != info) {\n\t\t\t\tmacAddress = info.getMacAddress();\n\t\t\t}\n\n\t\t\tString deviceId = Md5Util.toMD5(SystemConsts.CHANNEL + appKey + macAddress + imei);\n\t\t\tif (deviceInfo == null) {\n\t\t\t\tdeviceInfo = new Device();\n\t\t\t}\n\t\t\tdeviceInfo.setAppKey(appKey);\n\t\t\tdeviceInfo.setAppPackage(appPackage);\n\t\t\tdeviceInfo.setDeviceId(deviceId);\n\t\t\tdeviceInfo.setImei(imei);\n\t\t\tdeviceInfo.setIsOnline(DEVICE_OFFLINE);\n\t\t}\n\t\treturn deviceInfo;\n\t}\n\n\t/**\n\t * 删除设备\n\t * \n\t * @param appPackage\n\t */\n\tpublic void deleteDeviceInfo(Device deviceInfo) {\n\t\tif (deviceInfo != null) {\n\t\t\tthis.pushDbService.deleteDevice(deviceInfo);\n\t\t\t// 删除缓存内容\n\t\t\tdeviceInfos.remove(deviceInfo.getAppPackage());\n\t\t}\n\t}\n\n\tpublic void offlineAllDevices() {\n\t\tif (deviceInfos != null && !deviceInfos.isEmpty()) {\n\t\t\tList<Device> list = new ArrayList<Device>();\n\t\t\tIterator<Map.Entry<String, Device>> iterator = deviceInfos.entrySet().iterator();\n\t\t\twhile (iterator.hasNext()) {\n\t\t\t\tMap.Entry<String, Device> entry = iterator.next();\n\t\t\t\tDevice device = entry.getValue();\n\t\t\t\tif (device != null) {\n\t\t\t\t\tdevice.setIsOnline(DEVICE_OFFLINE);\n\t\t\t\t\tlist.add(device);\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis.pushDbService.saveOrUpdateDevices(list);\n\t\t\tlist = null;\n\t\t}\n\n\t}\n\n\t@SuppressWarnings(\"rawtypes\")\n\tpublic void registListener(String appPackage, Integer type, INettyHandlerListener listener) {\n\t\tif (listener != null) {\n\t\t\tMap<Integer, INettyHandlerListener> mNettyHandlerListeners = nettyHandlerListeners.get(appPackage);\n\t\t\tINettyHandlerListener nettyHandlerListener = null;\n\t\t\tif (mNettyHandlerListeners == null) {\n\t\t\t\tmNettyHandlerListeners = new HashMap<Integer, INettyHandlerListener>();\n\t\t\t\tnettyHandlerListeners.put(appPackage, mNettyHandlerListeners);\n\t\t\t} else {\n\t\t\t\tnettyHandlerListener = mNettyHandlerListeners.get(type);\n\t\t\t\tif (nettyHandlerListener != null) {\n\t\t\t\t\tnettyHandlerListener = null;\n\t\t\t\t}\n\t\t\t}\n\t\t\tmNettyHandlerListeners.put(type, listener);\n\t\t}\n\t}\n\n\t@SuppressWarnings(\"rawtypes\")\n\tpublic INettyHandlerListener getNettyHandlerListener(String appPackage, Integer type) {\n\t\tif (appPackage != null && type != null && nettyHandlerListeners.containsKey(appPackage)) {\n\t\t\tMap<Integer, INettyHandlerListener> mNettyHandlerListeners = nettyHandlerListeners.get(appPackage);\n\t\t\tINettyHandlerListener nettyHandlerListener = mNettyHandlerListeners == null ? null : mNettyHandlerListeners.get(type);\n\t\t\treturn nettyHandlerListener;\n\t\t}\n\t\treturn null;\n\t}\n\n\t/**\n\t * 心跳请求\n\t * \n\t * @param listener\n\t */\n\tpublic void sendHeartBeatMessage() {\n\t\ttry {\n\t\t\tLog.i(ApplicationContextClient.class.getName(), \"sendHeartBeatMessage\");\n\t\t} catch (Exception e) {\n\t\t\tSystem.out.println(\"sendHeartBeatMessage\");\n\t\t}\n\t\tif (ctx != null) {\n\t\t\t// 心跳请求\n\t\t\tCommandProtoc.PushMessage.Builder builder = this.createCommandPushMessage(CommandProtoc.PushMessage.Type.HEART_BEAT);\n\t\t\tctx.writeAndFlush(builder.build());\n\t\t}\n\t}\n\n\t/**\n\t * 设备注册请求\n\t * \n\t * @param ctx\n\t * @param imei\n\t * @param deviceId\n\t * @param appKey\n\t * @param appPackage\n\t */\n\tpublic void sendRegistrationMessage(Device deviceInfo, INettyHandlerListener<CommandProtoc.RegistrationResult> listener) {\n\t\ttry {\n\t\t\tLog.i(ApplicationContextClient.class.getName(), \"sendRegistrationMessage\");\n\t\t} catch (Exception e) {\n\t\t\tSystem.out.println(\"sendRegistrationMessage\");\n\t\t}\n\t\t// Log.i(ApplicationContextClient.class.getName(),\"sendRegistrationMessage\");\n\t\t// 激活后发送设备注册请求\n\t\tif (deviceInfo != null) {\n\t\t\tif (listener == null && this.getNettyHandlerListener(deviceInfo.getAppPackage(), NettyProcessorHandler.REGISTRATION_RESULT) == null) {\n\t\t\t\tthis.registListener(deviceInfo.getAppPackage(), NettyProcessorHandler.REGISTRATION_RESULT, new RegistrationResultListener(mContext, deviceInfo));\n\t\t\t} else {\n\t\t\t\tthis.registListener(deviceInfo.getAppPackage(), NettyProcessorHandler.REGISTRATION_RESULT, listener);\n\t\t\t}\n\t\t\tCommandProtoc.PushMessage pushMessage = this.createCommandRegistration(deviceInfo.getImei(), deviceInfo.getDeviceId(), deviceInfo.getAppKey(),\n\t\t\t\t\tdeviceInfo.getAppPackage());\n\t\t\tctx.writeAndFlush(pushMessage);\n\t\t}\n\t}\n\n\t/**\n\t * 发送设备上线消息\n\t * \n\t * @param ctx\n\t * @param deviceId\n\t */\n\tpublic void sendDeviceOnlineMessage(Device deviceInfo, INettyHandlerListener<CommandProtoc.DeviceOnoffResult> listener) {\n\t\ttry {\n\t\t\tLog.i(ApplicationContextClient.class.getName(), \"sendDeviceOnlineMessage\");\n\t\t} catch (Exception e) {\n\t\t\tSystem.out.println(\"sendDeviceOnlineMessage\");\n\t\t}\n\t\tif (deviceInfo != null) {\n\t\t\tthis.registListener(deviceInfo.getAppPackage(), NettyProcessorHandler.DEVICE_ONLINE_RESULT, listener);\n\t\t\tCommandProtoc.PushMessage pushMessage = this.createCommandDeviceOnline(deviceInfo.getDeviceId());\n\t\t\tctx.writeAndFlush(pushMessage);\n\t\t}\n\t}\n\n\t/**\n\t * 发送设备下线消息\n\t * \n\t * @param ctx\n\t * @param deviceId\n\t */\n\tpublic void sendDeviceOfflineMessage(Device deviceInfo, INettyHandlerListener<CommandProtoc.DeviceOnoffResult> listener) {\n\t\ttry {\n\t\t\tLog.i(ApplicationContextClient.class.getName(), \"sendDeviceOfflineMessage\");\n\t\t} catch (Exception e) {\n\t\t\tSystem.out.println(\"sendDeviceOfflineMessage\");\n\t\t}\n\t\tif (deviceInfo != null) {\n\t\t\tthis.registListener(deviceInfo.getAppPackage(), NettyProcessorHandler.DEVICE_OFFLINE_RESULT, listener);\n\t\t\tCommandProtoc.PushMessage pushMessage = this.createCommandDeviceOffline(deviceInfo.getDeviceId());\n\t\t\tctx.writeAndFlush(pushMessage);\n\t\t}\n\t}\n\n\t/**\n\t * 发送消息确认回执消息\n\t * \n\t * @param ctx\n\t * @param appKey\n\t * @param msgId\n\t */\n\tpublic void sendReceiptMessage(Device deviceInfo, String msgId) {\n\t\ttry {\n\t\t\tLog.i(ApplicationContextClient.class.getName(), \"sendReceiptMessage\");\n\t\t} catch (Exception e) {\n\t\t\tSystem.out.println(\"sendReceiptMessage\");\n\t\t}\n\t\tif (deviceInfo != null) {\n\t\t\tCommandProtoc.PushMessage pushMessage = this.createCommandMessageReceipt(deviceInfo.getAppKey(), deviceInfo.getRegId(), msgId);\n\t\t\tctx.writeAndFlush(pushMessage);\n\t\t}\n\t}\n\n\t/**\n\t * 创建Registration对象\n\t * \n\t * @param type\n\t * @return\n\t */\n\tpublic CommandProtoc.PushMessage createCommandRegistration(String imei, String deviceId, String appKey, String appPackage) {\n\t\tCommandProtoc.Registration.Builder builder = CommandProtoc.Registration.newBuilder();\n\t\tbuilder.setImei(imei);\n\t\tbuilder.setDeviceId(deviceId);\n\t\tbuilder.setAppKey(appKey);\n\t\tbuilder.setAppPackage(appPackage);\n\t\tbuilder.setChannel(SystemConsts.CHANNEL);\n\t\tCommandProtoc.Registration commandProtoc = builder.build();\n\n\t\t// 创建消息对象\n\t\tCommandProtoc.PushMessage.Builder messageBuilder = this.createCommandPushMessage(CommandProtoc.PushMessage.Type.REGISTRATION);\n\t\tmessageBuilder.setRegistration(commandProtoc);\n\t\treturn messageBuilder.build();\n\t}\n\n\t/**\n\t * 创建DeviceOnline对象\n\t * \n\t * @param type\n\t * @return\n\t */\n\tpublic CommandProtoc.PushMessage createCommandDeviceOnline(String deviceId) {\n\t\tCommandProtoc.DeviceOnline.Builder builder = CommandProtoc.DeviceOnline.newBuilder();\n\t\tbuilder.setDeviceId(deviceId);\n\t\tCommandProtoc.DeviceOnline commandProtoc = builder.build();\n\n\t\t// 创建消息对象\n\t\tCommandProtoc.PushMessage.Builder messageBuilder = this.createCommandPushMessage(CommandProtoc.PushMessage.Type.DEVICE_ONLINE);\n\t\tmessageBuilder.setDeviceOnline(commandProtoc);\n\t\treturn messageBuilder.build();\n\t}\n\n\t/**\n\t * 创建DeviceOffline对象\n\t * \n\t * @param type\n\t * @return\n\t */\n\tpublic CommandProtoc.PushMessage createCommandDeviceOffline(String deviceId) {\n\t\tCommandProtoc.DeviceOffline.Builder builder = CommandProtoc.DeviceOffline.newBuilder();\n\t\tbuilder.setDeviceId(deviceId);\n\t\tCommandProtoc.DeviceOffline commandProtoc = builder.build();\n\n\t\t// 创建消息对象\n\t\tCommandProtoc.PushMessage.Builder messageBuilder = this.createCommandPushMessage(CommandProtoc.PushMessage.Type.DEVICE_OFFLINE);\n\t\tmessageBuilder.setDeviceOffline(commandProtoc);\n\t\treturn messageBuilder.build();\n\t}\n\n\t/**\n\t * 创建MessageReceipt对象\n\t * \n\t * @param type\n\t * @return\n\t */\n\tpublic CommandProtoc.PushMessage createCommandMessageReceipt(String appKey, String registrationId, String msgId) {\n\t\tCommandProtoc.MessageReceipt.Builder builder = CommandProtoc.MessageReceipt.newBuilder();\n\t\tbuilder.setAppKey(appKey);\n\t\tbuilder.setRegistrationId(registrationId);\n\t\tbuilder.setMsgId(msgId);\n\t\tCommandProtoc.MessageReceipt commandProtoc = builder.build();\n\t\t// 创建消息对象\n\t\tCommandProtoc.PushMessage.Builder messageBuilder = this.createCommandPushMessage(CommandProtoc.PushMessage.Type.MESSAGE_RECEIPT);\n\t\tmessageBuilder.setMessageReceipt(commandProtoc);\n\t\treturn messageBuilder.build();\n\t}\n\n\t/**\n\t * 创建发送消息对象\n\t * \n\t * @param type\n\t * @return\n\t */\n\tprivate CommandProtoc.PushMessage.Builder createCommandPushMessage(CommandProtoc.PushMessage.Type type) {\n\t\tCommandProtoc.PushMessage.Builder builder = CommandProtoc.PushMessage.newBuilder();\n\t\tbuilder.setType(type);\n\t\treturn builder;\n\t}\n\n\tpublic void destory() {\n\t\tisClosed = true;\n\t\tif (this.deviceInfos != null) {\n\t\t\tthis.deviceInfos.clear();\n\t\t\tthis.deviceInfos = null;\n\t\t}\n\n\t\tif (nettyHandlerListeners != null) {\n\t\t\tnettyHandlerListeners.clear();\n\t\t\tnettyHandlerListeners = null;\n\t\t}\n\n\t\tpushDbService = null;\n\t\tif (ctx != null) {\n\t\t\tctx.close();\n\t\t\tctx = null;\n\t\t}\n\t}\n}"
] | import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;
import com.netty.client.android.broadcast.ClientBroadcastReceiver;
import com.netty.client.android.listener.INettyHandlerListener;
import com.netty.client.android.service.RemoteService;
import com.netty.client.consts.SystemConsts;
import com.netty.client.context.ApplicationContextClient;
import com.xwtec.protoc.CommandProtoc; | package com.netty.client.android.handler;
public class NettyProcessorHandler extends Handler {
public static final int REGISTRATION_RESULT = 100;
public static final int DEVICE_ONLINE_RESULT = 101;
public static final int DEVICE_OFFLINE_RESULT = 102;
public static final int MESSAGE = 103;
private Context context;
private ApplicationContextClient applicationContextClient;
public NettyProcessorHandler(Context context) {
this.context = context;
this.applicationContextClient = RemoteService.getApplicationContextClient();
}
/**
* 消息处理方法
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public void handleMessage(Message msg) {
if (msg != null) {
Log.i(getClass().getName(), "-handleMessage:msg.what=" + msg.what);
MessageObject mo = (MessageObject) msg.obj;
if (mo == null) {
return;
} | INettyHandlerListener listener = applicationContextClient.getNettyHandlerListener(mo.getAppPackage(), msg.what); | 1 |
azinik/ADRMine | release/v1/java_src/ADRMine/src/main/java/edu/asu/diego/adrmine/features/TokenClauseFeatures.java | [
"public class Negation {\n\t\n\tstatic ArrayList<String> modifier_rels = new ArrayList<String>(Arrays.asList(\"det\",\"neg\",\"amod\",\"advmod\",\"dep\",\"nn\",\"prep\"));\n\t\n\tpublic static ArrayList<String> getNegationModifierRelations()\n\t{\n\t\treturn modifier_rels;\n\t}\n\tpublic static boolean isWordNegated( Artifact word,Artifact sent) throws Exception\n\t{\n\t\tboolean is_negated =false;\n\t\t\n\t\tArrayList<DependencyLine> sentDepLines =\n\t\t\t\tStanfordDependencyUtil.parseDepLinesFromString(sent.getStanDependency());\n\t\tArrayList<String> mod_list = getNegationModifierRelations();\n\t\t\t\n\t\t//get the original word\n\t\tInteger word_offset = word.getWordIndex();\n\t\t\n\t\tArrayList<String> previous_tokens = getNPrevTokens(word_offset,sent, 2);\n\n\t\tif (previous_tokens.contains(\"no\") || previous_tokens.contains(\"not\")\n\t\t\t\t|| previous_tokens.contains(\"hasnt\")\n\t\t\t\t|| previous_tokens.contains(\"havent\")\n\t\t\t\t|| previous_tokens.contains(\"cant\")\n\t\t\t\t|| previous_tokens.contains(\"dont\")\n\t\t\t\t|| previous_tokens.contains(\"didnt\")\n\t\t\t\t|| previous_tokens.contains(\"hadnt\")\n\t\t\t\t|| previous_tokens.contains(\"couldnt\"))\n\t\t{\n\t\t\tis_negated = true;\n\t\t\treturn is_negated;\n\t\t}\n\t\t\n\t\t//get next words TODO: this should be recursive and in a method\n//\t\tArrayList<String> next_tokens = new ArrayList<>();\n//\t\t\n//\t\tArtifact nextWord = word.getNextArtifact();\n//\t\tif (nextWord != null)\n//\t\t{\n//\t\t\tnext_tokens.add(nextWord.getContent().toLowerCase());\n//\t\t\tnextWord= nextWord.getNextArtifact();\n//\t\t\tif (nextWord != null)\n//\t\t\t{\n//\t\t\t\tnext_tokens.add(nextWord.getContent().toLowerCase());\n//\t\t\t}\n//\t\t}\n//\t\tif (next_tokens.contains(\"no\") || next_tokens.contains(\"not\"))\n//\t\t{\n//\t\t\tis_negated = true;\n//\t\t\treturn is_negated;\n//\t\t}\t\n\t\t//To be compatible with stanford parser\n\t\t\n\t\tword_offset++;\n\t\tfor(DependencyLine curLine:sentDepLines)\n\t\t{\n\t\t\tif (!mod_list.contains(curLine.relationName))\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (curLine.relationName.equals(\"neg\") && curLine.firstOffset==word_offset)\n\t\t\t{\n\t\t\t\tis_negated = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse if (curLine.firstOffset==word_offset)\n\t\t\t{\n\t\t\t\tif (curLine.secondPart.equals(\"no\") || curLine.secondPart.equals(\"any\") ||\n\t\t\t\t\t\tcurLine.secondPart.equals(\"not\") || curLine.secondPart.equals(\"less\"))\n\t\t\t\t{\n\t\t\t\t\tis_negated = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t\n\n\t\treturn is_negated;\n\t}\n\n\tpublic static ArrayList<String> getNPrevTokens(int word_index,Artifact sent,int howMany)\n\t{\n\t\tArrayList<String> prev_tokens = new ArrayList<String>(); \n\t\tArtifact target = sent.getChildByWordIndex(word_index);\n\t\tArtifact prev= target.getPreviousArtifact();\n\t\twhile (howMany!=0 && prev!=null)\n\t\t{\n\t\t\tprev_tokens.add(prev.getContent().toLowerCase());\n\t\t\thowMany--;\n\t\t\tprev=prev.getPreviousArtifact();\n\t\t}\n\t\treturn prev_tokens;\n\t}\n\tpublic static Artifact calclateGovVerb(Artifact pWord) {\n\t\tArtifact gov_verb = null;\n\t\tString pos = pWord.getPOS();\n\n\t\tif (pos == null)\n\t\t\treturn null;\n\t\tif (pos != null && (pos.matches(\"VB|VBD|VBN|VBP|VBZ\")) )\n\t\t{\n\t\t\tgov_verb = pWord;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tArtifact next = pWord.getNextArtifact();\n\t\t\tif (next != null && next.getPOS() != null && next.getPOS().startsWith(\"VB\"))\n\t\t\t{\n\t\t\t\tArtifact next_verb = next.getNextArtifact();\n\t\t\t\tif (next_verb != null && next_verb.getPOS()!= null &&\n\t\t\t\t\t\tnext_verb.getPOS().matches(\"VBD\"))\n\t\t\t\t{\n\t\t\t\t\tgov_verb = next_verb;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tgov_verb = next;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tArtifact prev = pWord.getPreviousArtifact();\n\t\t\t\twhile (prev != null && prev.getPOS() != null &&\n\t\t\t\t\t\t!prev.getPOS().matches(\"VB|VBD|VBN|VBP|VBZ\") )\n\t\t\t\t{\n\t\t\t\t\tprev = prev.getPreviousArtifact();\n\t\t\t\t}\n\t\t\t\tif (prev != null && prev.getPOS().startsWith(\"VB\"))\n\t\t\t\t{\n\t\t\t\t\tgov_verb = prev;\n\t\t\t\t}\n\t\t\t}\n\t\t\t//if still null\n\t\t\tif (gov_verb == null)\n\t\t\t{\n\t\t\t\twhile (next != null && next.getPOS() != null && \n\t\t\t\t\t\t!next.getPOS().matches(\"VB|VBD|VBN|VBP|VBZ\") )\n\t\t\t\t{\n\t\t\t\t\tnext = next.getNextArtifact();\n\t\t\t\t}\n\t\t\t\tif (next != null && next.getPOS() != null && next.getPOS().startsWith(\"VB\"))\n\t\t\t\t{\n\t\t\t\t\tArtifact next_verb = next.getNextArtifact();\n\t\t\t\t\tif (next_verb != null && next_verb.getPOS() !=null && next_verb.getPOS().matches(\"VBD\"))\n\t\t\t\t\t{\n\t\t\t\t\t\tgov_verb = next_verb;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tgov_verb = next;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn gov_verb;\n\t}\n}",
"@Entity\n@Table( name = \"Artifact\" )\npublic class Artifact {\n\tString content;\n\tString generalized_content;\n\tList<Artifact> childsArtifact;\n\tArtifact parentArtifact;\n\tArtifact nextArtifact;\n\tArtifact previousArtifact;\n\tType artifactType;\n\tprivate boolean forTrain;\n\tprivate boolean forDemo=false;\n\t\n\t\n\t\n\t@Transient\n\tboolean isNew;\n\t@Transient\n//\tList<ArtifactFeature> features = new ArrayList<ArtifactFeature>();\n\t\n\tString POS;\n\t\n\t// These two variable are lazy and will be initialized in getter\n\tInteger startIndex = null;\n\tInteger endIndex = null;\n\n\tInteger lineOffset = null;\n\tInteger wordOffset = null;\n\t\n\tString stanDependency =null;\n\tprivate String stanPennTree = null;\n\t\n\tint artifactId = -1;\n\t/*\n\t * Physical address of file which artifact loaded from that\n\t */\n\tString associatedFilePath;\n\tString corpusName;\n\n\tpublic enum Type {\n\t\tDocument, Sentence, Phrase, Word\n\t}\n\n\t\n\tpublic Artifact()\n\t{\n\t\t\n\t}\n\t/**\n\t * Loads Artifact by id\n\t * @param pArtifactID\n\t * @return\n\t */\n\tpublic static Artifact getInstance(int pArtifactID) {\n\t\tString hql = \"from Artifact where artifactId = \"+pArtifactID;\n\t\tArtifact artifact_obj = \n\t\t\t(Artifact)HibernateUtil.executeReader(hql).get(0);\n\t\treturn artifact_obj;\n\t}\n\t/**\n\t * Creates completely empty Artifact object\n\t * @return\n\t */\n\tpublic static Artifact getInstance(Type pArtifactType) {\n\t\tArtifact artifact_obj = new Artifact();\n\t\tartifact_obj.setArtifactType(pArtifactType);\n\t\tHibernateUtil.save(artifact_obj);\n\t\treturn artifact_obj;\n\t}\n\t\n\t/**\n\t * Loads or creates the Artifact\n\t * @param pArtifactType\n\t * @param pFilePath\n\t * @param pStartIndex\n\t * @return\n\t */\n\tpublic static Artifact getInstance(Type pArtifactType, String pFilePath, \n\t\t\tint pStartIndex){\n\t\tString hql = \"from Artifact where artifactType = \"+\n\t\t\tpArtifactType.ordinal()+\" and associatedFilePath ='\" +\n\t\t\tpFilePath + \"' and startIndex=\"+pStartIndex;\n\t\tList<Artifact> artifact_objects = \n\t\t\t\t(List<Artifact>) HibernateUtil.executeReader(hql);\n\t \n\t \n\t Artifact artifact_obj;\n\t if(artifact_objects.size()==0)\n\t {\n\t \tartifact_obj = new Artifact();\n\t \tartifact_obj.setStartIndex(pStartIndex);\n\t \tartifact_obj.setAssociatedFilePath(pFilePath);\n\t \tartifact_obj.setArtifactType(pArtifactType);\n\t \tartifact_obj.setForTrain(Setting.TrainingMode);\n\t \tHibernateUtil.save(artifact_obj);\n\t }else\n\t {\n\t \tartifact_obj = \n\t\t\t\tartifact_objects.get(0);\n\t }\n\t return artifact_obj;\n\t}\n\tpublic static Artifact getInstance(Type pArtifactType, String pFilePath, \n\t\t\tint pStartIndex,String corpusName){\n\t\tString hql = \"from Artifact where artifactType = \"+\n\t\t\tpArtifactType.ordinal()+\" and associatedFilePath ='\" +\n\t\t\tpFilePath + \"' and corpusName= '\"+corpusName+\"' and startIndex=\"+pStartIndex;\n\t\tList<Artifact> artifact_objects = \n\t\t\t\t(List<Artifact>) HibernateUtil.executeReader(hql);\n\t \n\t \n\t Artifact artifact_obj;\n\t if(artifact_objects.size()==0)\n\t {\n\t \tartifact_obj = new Artifact();\n\t \tartifact_obj.setStartIndex(pStartIndex);\n\t \tartifact_obj.setAssociatedFilePath(pFilePath);\n\t \tartifact_obj.setArtifactType(pArtifactType);\n\t \tartifact_obj.setForTrain(Setting.TrainingMode);\n\t \tartifact_obj.setCorpusName(corpusName);\n\t \tHibernateUtil.save(artifact_obj);\n\t }else\n\t {\n\t \tartifact_obj = \n\t\t\t\tartifact_objects.get(0);\n\t }\n\t return artifact_obj;\n\t}\n\tpublic static Artifact getInstance(Type pArtifactType, String pFilePath, \n\t\t\tint pStartIndex,boolean forDemo){\n\t\tString hql = \"from Artifact where artifactType = \"+\n\t\t\tpArtifactType.ordinal()+\" and associatedFilePath ='\" +\n\t\t\tpFilePath + \"' and startIndex=\"+pStartIndex+\" and forDemo=\"+forDemo;\n\t\tList<Artifact> artifact_objects = \n\t\t\t\t(List<Artifact>) HibernateUtil.executeReader(hql);\n\t \n\t \n\t Artifact artifact_obj;\n\t if(artifact_objects.size()==0)\n\t {\n\t \tartifact_obj = new Artifact();\n\t \tartifact_obj.setStartIndex(pStartIndex);\n\t \tartifact_obj.setAssociatedFilePath(pFilePath);\n\t \tartifact_obj.setArtifactType(pArtifactType);\n\t \tHibernateUtil.save(artifact_obj);\n\t }else\n\t {\n\t \tartifact_obj = \n\t\t\t\tartifact_objects.get(0);\n\t }\n\t return artifact_obj;\n\t}\n\tpublic static Artifact getInstance(int pWordIndex,Type pArtifactType, String pFilePath\n\t\t\t){\n\t\tString hql = \"from Artifact where artifactType = \"+\n\t\t\tpArtifactType.ordinal()+\" and associatedFilePath ='\" +\n\t\t\tpFilePath + \"' and wordIndex=\"+pWordIndex;\n\t\tList<Artifact> artifact_objects = \n\t\t\t\t(List<Artifact>) HibernateUtil.executeReader(hql);\n\t \n\t \n\t Artifact artifact_obj;\n\t if(artifact_objects.size()==0)\n\t {\n\t \tartifact_obj = new Artifact();\n\t \tartifact_obj.setWordIndex(pWordIndex);\n\t \tartifact_obj.setAssociatedFilePath(pFilePath);\n\t \tartifact_obj.setArtifactType(pArtifactType);\n\t \tHibernateUtil.save(artifact_obj);\n\t }else\n\t {\n\t \tartifact_obj = \n\t\t\t\tartifact_objects.get(0);\n\t }\n\t return artifact_obj;\n\t}\n\tpublic static Artifact getInstance(Type pArtifactType, String unique_id, \n\t\t\tString content){\n\t\tString hql = \"from Artifact where artifactType = \"+\n\t\t\tpArtifactType.ordinal()+\" and associatedFilePath ='\" +\n\t\t\tunique_id+\"'\";\n\t\t\n\t\tList<Artifact> artifact_objects = \n\t\t\t\t(List<Artifact>) HibernateUtil.executeReader(hql);\n\t \n\t \n\t Artifact artifact_obj;\n\t if(artifact_objects.size()==0)\n\t {\n\t \tartifact_obj = new Artifact();\n\t \t\n\t \tartifact_obj.setAssociatedFilePath(unique_id);\n\t \tartifact_obj.setContent(content);\n\t \tartifact_obj.setArtifactType(pArtifactType);\n\t \t\n\t \tHibernateUtil.save(artifact_obj);\n\t }else\n\t {\n\t \tartifact_obj = \n\t\t\t\tartifact_objects.get(0);\n\t }\n\t return artifact_obj;\n\t}\n\tpublic static Artifact getInstanceByEndChar(Type pArtifactType, String pFilePath, \n\t\t\tint pEndIndex){\n\t\tString hql = \"from Artifact where artifactType = \"+\n\t\t\tpArtifactType.ordinal()+\" and associatedFilePath ='\" +\n\t\t\tpFilePath + \"' and endIndex=\"+pEndIndex;\n\t\tList<Artifact> artifact_objects = \n\t\t\t\t(List<Artifact>) HibernateUtil.executeReader(hql);\n\t \n\t \n\t Artifact artifact_obj;\n\t if(artifact_objects.size()==0)\n\t {\n\t \tartifact_obj = new Artifact();\n\t \tartifact_obj.setEndIndex(pEndIndex);\n\t \tartifact_obj.setAssociatedFilePath(pFilePath);\n\t \tartifact_obj.setArtifactType(pArtifactType);\n\t \tHibernateUtil.save(artifact_obj);\n\t }else\n\t {\n\t \tartifact_obj = \n\t\t\t\tartifact_objects.get(0);\n\t }\n\t return artifact_obj;\n\t}\n\tpublic static Artifact getMadeUpInstance(String content){\n\t\tString hql = \"from Artifact where content = '\"+content+\"'\";\n\t\tList<Artifact> artifact_objects = \n\t\t\t\t(List<Artifact>) HibernateUtil.executeReader(hql);\n\t \n\t \n\t Artifact artifact_obj;\n\t if(artifact_objects.size()==0)\n\t {\n\t \tartifact_obj = new Artifact();\n\t \tartifact_obj.setContent(content);\n\t \tHibernateUtil.save(artifact_obj);\n\t }else\n\t {\n\t \tartifact_obj = \n\t\t\t\tartifact_objects.get(0);\n\t }\n\t return artifact_obj;\n\t}\n\t@ManyToOne( cascade = {CascadeType.PERSIST, CascadeType.MERGE})\n//\t@ManyToOne( cascade = {CascadeType.PERSIST, CascadeType.MERGE}, fetch=FetchType.LAZY )\n//\t@ManyToOne( cascade = {CascadeType.PERSIST, CascadeType.MERGE} )\n @JoinColumn(name=\"parentArtifact\")\n\tpublic Artifact getParentArtifact() {\n\t\treturn parentArtifact;\n\t}\n\tpublic void setParentArtifact(Artifact _parentArtifact) {\n\t\tparentArtifact = _parentArtifact;\n\t}\n\t\n//\t@OneToMany(mappedBy=\"parentArtifact\")\n// @OrderBy(\"startIndex\")\n\t@Transient\n\tpublic List<Artifact> getChildsArtifact() {\n\t\tif(childsArtifact==null && artifactType != Type.Word)\n\t\t\tchildsArtifact = \n\t\t\t\t(List<Artifact>) HibernateUtil.executeReader( \"from Artifact where parentArtifact = \"+artifactId+\" order by artifactId\");\n\n\t\treturn childsArtifact;\n\t}\n\t\n\n\t\n\t\n//\t@OneToOne( cascade = {CascadeType.PERSIST, CascadeType.MERGE}, fetch=FetchType.LAZY )\n\t@OneToOne( cascade = {CascadeType.PERSIST, CascadeType.MERGE} )\n\t@JoinColumn(name=\"nextArtifact\")\n public Artifact getNextArtifact() {\n\t\treturn nextArtifact;\n\t}\n\tpublic void setNextArtifact(Artifact pNextArtifact){\n\t\tnextArtifact = pNextArtifact;\n\t}\n\t\n\n//\t@OneToOne( cascade = {CascadeType.PERSIST, CascadeType.MERGE}, fetch=FetchType.LAZY )\n\t@OneToOne( cascade = {CascadeType.PERSIST, CascadeType.MERGE} )\n\t@JoinColumn(name=\"previousArtifact\")\n public Artifact getPreviousArtifact() {\n\t\treturn previousArtifact;\n\t}\n\tpublic void setPreviousArtifact(Artifact pPreviousArtifact){\n\t\tpreviousArtifact = pPreviousArtifact;\n\t}\n\t/**\n\t * Return oldest parent of this Artifact which is usually a Document\n\t */\n\t@Transient\n\tpublic Artifact grandFather() throws SQLException {\n\t\tArtifact grandFather = this;\n\n\t\twhile (grandFather.getParentArtifact() != null) {\n\t\t\tgrandFather = grandFather.getParentArtifact();\n\t\t}\n\n\t\treturn grandFather;\n\t}\n\n\t@Index(name = \"index_start_index\")\n\tpublic Integer getStartIndex() {\n\t\tif (this.getArtifactType() == Type.Document) {\n\t\t\tstartIndex = 0;\n\t\t} else if (startIndex == null) {\n\t\t\tint _previousArtifactsLength = 0;\n\t\t\tArtifact previous = this.getPreviousArtifact();\n\t\t\twhile (previous != null) {\n\t\t\t\t_previousArtifactsLength += previous.getContent().length() + 1;\n\t\t\t\tprevious = previous.getPreviousArtifact();\n\t\t\t}\n\t\t\tif(getParentArtifact()!=null)\n\t\t\t\tstartIndex = parentArtifact.getStartIndex()\n\t\t\t\t\t\t+ _previousArtifactsLength + 1;\n\t\t\t\n\t\t}\n\t\treturn startIndex;\n\t}\n\n\tpublic void setEndIndex(Integer _endIndex) {\n\t\tif (_endIndex == null && !this.getContent().isEmpty()) {\n\t\t\t_endIndex = startIndex + this.getContent().length();\n\t\t}\n\t\tendIndex = _endIndex;\n\t}\n\n\t@Index(name = \"index_end_index\")\n\tpublic Integer getEndIndex() {\n\t\tif (endIndex == null)\n\t\t{\n\t\t\tif(getStartIndex()!=null)\n\t\t\t\tendIndex = startIndex + getContent().length();\n\t\t}\n\t\t\n\t\treturn endIndex;\n\t}\n\n\t\n\n\tpublic String getPOS()\n\t{\n//\t\tif(POS==null){\n////\t\t\ttry {\n////\t\t\t\tPOS = \n////\t\t\t\t\tArtifactAttributeTable.getAttributeValue(artifactId, \n////\t\t\t\t\t\t\tAttributeValuePair.AttributeType.POS.name());\n////\t\t\t} catch (SQLException e) {\n////\t\t\t\t// TODO Auto-generated catch block\n////\t\t\t\te.printStackTrace();\n////\t\t\t}\n//\t\t\tif(POS==null && artifactType == Type.Word){\n//\t\t\t\tString contentRegexCasted = StringUtil.castForRegex(getContent());\n//\t\t\t\tlineOffset = getLineIndex();\n//\t\t\t\tif(lineOffset==null) return \"\";\n//\t\t\t\tString tagged = \n//\t\t\t\t\tStanfordParser.getTagged(associatedFilePath, lineOffset);\n//\t\t\t\tString[] taggedTokens = \n//\t\t\t\t\ttagged.split(\" \");\n//\t\t\t\twordOffset = getWordIndex();\n//\t\t\t\tboolean index_invalid = false;\n//\t\t\t\tif(wordOffset!=null && \n//\t\t\t\t\t\ttaggedTokens.length>wordOffset)\n//\t\t\t\t{\n//\t\t\t\t\tString[] parts = taggedTokens[wordOffset].replace(\"\\\\/\", \"/\"). // '/' is tagger splitter; decast to match\t\t\t\t\t\n//\t\t\t\t\t\t\tsplit(contentRegexCasted+\"/\");\n//\t\t\t\t\tif(parts.length==2)\n//\t\t\t\t\t\tPOS = parts[1];\n//\t\t\t\t\telse\n//\t\t\t\t\t\tindex_invalid = true;\n//\t\t\t\t}\n//\t\t\t\telse\n//\t\t\t\t\tindex_invalid= true;\n//\n//\t\t\t\tif(index_invalid)\n//\t\t\t\t{\n//\t\t\t\t\t\n//\t\t\t\t\tnextArtifact = getNextArtifact();\n//\t\t\t\t\tpreviousArtifact = getPreviousArtifact();\n//\t\t\t\t\tif(previousArtifact != null && nextArtifact!=null)\n//\t\t\t\t\t{\n//\t\t\t\t\t\tString preContent=previousArtifact.getContent();\n//\t\t\t\t\t\tString nextContent=nextArtifact.getContent();\n//\t\t\t\t\t\tif(nextContent.equals(\"-\"))\n//\t\t\t\t\t\t{\n//\t\t\t\t\t\t\tArtifact nextnext = nextArtifact.getNextArtifact();\n//\t\t\t\t\t\t\tif(nextnext!=null)\n//\t\t\t\t\t\t\t{\n//\t\t\t\t\t\t\t\tcontentRegexCasted = \n//\t\t\t\t\t\t\t\t\tcontentRegexCasted+\n//\t\t\t\t\t\t\t\t\tnextContent+\n//\t\t\t\t\t\t\t\t\tnextnext.getContent();\n//\t\t\t\t\t\t\t}\n//\t\t\t\t\t\t}\n//\t\t\t\t\t\t// to make sure not casted before\n////\t\t\t\t\t\t\tcontentRegexCasted = \n////\t\t\t\t\t\t\t\tUtil.castForRegex(Util.decastRegex(contentRegexCasted));\n//\t\t\t\t\t\t\n//\t\t\t\t\t\tPattern p = Pattern.compile(\"(.* )?\"+contentRegexCasted+\"/(\\\\S+)( .*)?\");\n//\t\t\t\t\t\tPattern p2 = Pattern.compile(\"(.* )?\\\\S*\"+contentRegexCasted+\"\\\\S*/(\\\\S+)( .*)?\");\n//\t\t\t\t\t\tMatcher m = p.matcher(tagged);\n//\t\t\t\t\t\tif(m.matches())\n//\t\t\t\t\t\t{\n//\t\t\t\t\t\t\tPOS=m.group(2);\n////\t\t\t\t\t\t\t\tUtil.log(\"_POS found: \"+_POS+\n////\t\t\t\t\t\t\t\t\t\t\" for \"+contentRegexCasted, Level.INFO);\n//\t\t\t\t\t\t}else\n//\t\t\t\t\t\t{\n//\t\t\t\t\t\t\tm = p2.matcher(tagged);\n//\t\t\t\t\t\t\tif(m.matches())\n//\t\t\t\t\t\t\t{\n//\t\t\t\t\t\t\t\tPOS=m.group(2);\n////\t\t\t\t\t\t\t\t\tUtil.log(\"_POS found: \"+_POS+\n////\t\t\t\t\t\t\t\t\t\t\t\" for \"+contentRegexCasted, Level.INFO);\n//\t\t\t\t\t\t\t}\n//\t\t\t\t\t\t}\n//\t\t\t\t\t\t\n//\t\t\t\t\t}\n//\t\t\t\t\t\n//\t\t\t\t\tif(POS==null && previousArtifact != null)\n//\t\t\t\t\t{\n//\t\t\t\t\t\tPOS = previousArtifact.getPOS();\n//\t\t\t\t\t}\n//\t\t\t\t\tif(POS==null)\n//\t\t\t\t\t{\n//\t\t\t\t\t\tPOS = getContent();\n////\t\t\t\t\t\tUtil.log(\"Error in _POS: word index = \"+_wordOffset+\n////\t\t\t\t\t\t\t\", tagged:\"+tagged+\", tagged token:\"+\n////\t\t\t\t\t\t\t\" \"+contentRegexCasted+\" -> \" \n////\t\t\t\t\t\t\t+getContent(), Level.WARNING);\n//\t\t\t\t\t}\n//\t\t\t\t}\n//\t\t\t}\n//\t\t}\n//\t\tif(getContent().equals(\"-\"))\n//\t\t\tPOS = \"-\";\n\n\t\t\n\t\treturn POS;\n\t}\n\tpublic void setPOS(String pPOS) {\n\t\tPOS = pPOS;\n\t}\n\t/**\n\t * starts from 0\n\t * @return\n\t */\n\t@Index(name = \"index_word_index\")\n\tpublic Integer getWordIndex() {\n\t\t\n\t\t\n\t\tif(wordOffset==null)\n\t\t{\n\t\t\t\n\t\t\tif(artifactType==Type.Word)\n\t\t\t{\n\t\t\t\n\t\t\t\twordOffset=0;\n\t\t\t\tArtifact preWord = getPreviousArtifact();\n\t\t\t\twhile(preWord!=null)\n\t\t\t\t{\n\t\t\t\t\twordOffset++;\n\t\t\t\t\tpreWord = preWord.getPreviousArtifact();\n\t\t\t\t\tpreviousArtifact = null;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t}\n\t\treturn wordOffset;\n\t}\n\t\n\tpublic void setWordIndex(Integer _wordOffset) {\n\t\twordOffset = _wordOffset;\n\t}\n\tpublic void setLineIndex(Integer _lineIndex) {\n\t\tlineOffset = _lineIndex;\n\t}\n\tpublic void setStartIndex(Integer _startIndex) {\n\t\tstartIndex = _startIndex;\n\t}\n\t\n\t/**\n\t * sentence index, starts from 1\n\t * @return\n\t */\n\t@Index(name = \"index_line_index\")\n\tpublic Integer getLineIndex() {\n\t\tif(lineOffset==null)\n\t\t{\n\t\t\tif(artifactType==Type.Word)\n\t\t\t{\n\t\t\t\tArtifact sentence = getParentArtifact();\n\t\t\t\tif(sentence==null) \n\t\t\t\t{\n\t\t\t\t\tnextArtifact = getNextArtifact();\n\t\t\t\t\tif(nextArtifact!=null)\n\t\t\t\t\t\tsentence = nextArtifact.getParentArtifact();\n\t\t\t\t}\n\t\t\t\tif(sentence==null) \n\t\t\t\t{\n\t\t\t\t\tpreviousArtifact = getPreviousArtifact();\n\t\t\t\t\tif(previousArtifact!=null)\n\t\t\t\t\t\tsentence = previousArtifact.getParentArtifact();\n\t\t\t\t}\n\t\t\t\tif(sentence==null) \n\t\t\t\t{\n//\t\t\t\t\t\tUtil.log(\"Error in getLineIndex: word '\"+ _artifactId \n//\t\t\t\t\t\t\t\t+\"' doesn't have parent!\", Level.SEVERE);\n\t\t\t\t\t\t\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t\tlineOffset = sentence.getLineIndex();\n\t\t\t}\n\t\t\tif(artifactType==Type.Sentence)\n\t\t\t{\n\t\t\t\tlineOffset=1;\n\t\t\t\tArtifact preSentence = getPreviousArtifact();\n\t\t\t\twhile(preSentence!=null)\n\t\t\t\t{\n\t\t\t\t\tlineOffset++;\n\t\t\t\t\tpreSentence = preSentence.getPreviousArtifact();\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t}\n\t\treturn lineOffset;\n\t}\n\n\tpublic void setContent(String _content) {\n\t\tthis.content = _content;\n\t}\n\t@Column(length = 2000)\n\t@Index(name = \"index_content\")\n\tpublic String getContent() {\n\t\tif(content==null) return \"\";\n\t\treturn content;\n\t}\n\n\tpublic void setAssociatedFilePath(String _associatedFilePath) {\n\t\tthis.associatedFilePath = _associatedFilePath;\n\t}\n\n\tpublic String getAssociatedFilePath() {\n\t\treturn associatedFilePath;\n\t}\n\t\n\t@Column(nullable = false)\n\tpublic void setArtifactType(Type _artifactType) {\n\t\tthis.artifactType = _artifactType;\n\t}\n\n\tpublic Type getArtifactType() {\n\t\treturn artifactType;\n\t}\n\n\tpublic void setArtifactId(int _artifactId) {\n\t\tthis.artifactId = _artifactId;\n\t}\n\t@Id\n\t@GeneratedValue(generator=\"increment\")\n\t@GenericGenerator(name=\"increment\", strategy = \"increment\")\n\tpublic int getArtifactId() {\n\t\treturn artifactId;\n\t}\n\t\n\t@Override public String toString()\n\t{\n\t\treturn associatedFilePath.substring(associatedFilePath.length()-15, \n\t\t\t\tassociatedFilePath.length()-1) + \":\"+\n\t\t\tartifactId+\"-\"+artifactType.toString()+\"-\"\n\t\t\t+parentArtifact.artifactId+\"-\"+\n\t\t\tnextArtifact.artifactId+\"-\"+\n\t\t\tpreviousArtifact.artifactId;\n\t}\n\t\n\t@Override public boolean equals(Object pArtifact)\n\t{\n\t\tif(!(pArtifact instanceof Artifact))\n\t\t\treturn false;\n\t\tArtifact a = (Artifact)pArtifact;\n\t\treturn (a.getArtifactId() == artifactId) ||\n\t\t\t\t(a.getStartIndex() == getStartIndex() &&\n\t\t\t\ta.getContent().equals(getContent()) &&\n\t\t\t\ta.getAssociatedFilePath().equals(getAssociatedFilePath()) &&\n\t\t\t\ta.getArtifactType().equals(getArtifactType()));\n\t}\n\t@Override public int hashCode()\n\t{\n\t\treturn artifactId;\n\t}\n\tpublic static Artifact findInstance(Type pArtifactType, String pFilePath, \n\t\t\tint pWordIndex, int pLineIndex){\n\t\tString hql = \"from Artifact where artifactType =:artifactType and\" +\n\t\t\t\t\" associatedFilePath like :associatedFilePath and wordIndex=:wordIndex \" +\n\t\t\t\t\" and lineIndex= :lineIndex\";\n\t\t\n\t\tHashMap<String, Object> params = new HashMap<String, Object>();\n\t\tparams.put(\"associatedFilePath\", '%'+pFilePath);\n\t\tparams.put(\"wordIndex\", pWordIndex);\n\t\tparams.put(\"artifactType\", pArtifactType.ordinal());\n\t\tparams.put(\"lineIndex\",pLineIndex);\n\t\t\n\t\t\n\t\tList<Artifact> artifact_objects = \n\t\t\t\t(List<Artifact>) HibernateUtil.executeReader(hql,params);\n\t \n\t \n\t Artifact artifact_obj=null;\n\t if(artifact_objects.size()!=0)\n\t {\n\t \tartifact_obj = \n\t\t\t\tartifact_objects.get(0);\n\t }\n\t return artifact_obj;\n\t}\n\tpublic static Artifact findInstance(Artifact pSentence,int pWordIndex){\n\t\tString hql = \"from Artifact where parentArtifact = \"+pSentence.getArtifactId()+\" and wordIndex =\" +\n\t\tpWordIndex;\n\t\t\n\t\tList<Artifact> artifact_objects = \n\t\t\t\t(List<Artifact>) HibernateUtil.executeReader(hql);\n\t \n\t \n\t Artifact artifact_obj=null;\n\t if(artifact_objects.size()!=0)\n\t {\n\t \tartifact_obj = \n\t\t\t\tartifact_objects.get(0);\n\t }\n\t return artifact_obj;\n\t}\n\tpublic static Artifact findInstance(Type pArtifactType, String pFilePath, \n\t\t\tint pLine, int pWordIndex, String pContent, String pSecondWord){\n\t\t\n\t\tHashMap<String, Object> params = new HashMap<String, Object>();\n\t\tString hql = \"from Artifact where artifactType =:artifactType and\" +\n\t\t\t\t\" associatedFilePath like :associatedFilePath and content like:content \" +\n\t\t\t\t\" and lineIndex= :lineIndex \";\n\t\tif (pSecondWord != null)\n\t\t{\n\t\t\thql += \"and nextArtifact.content = :nextContent\";\n\t\t\tparams.put(\"nextContent\", pSecondWord);\n\t\t}\n\t\telse\n\t\t{\n\t\t\thql += \" and ABS(wordIndex - :pWordIndex) <=5\";\n\t\t\tparams.put(\"pWordIndex\",pWordIndex);\n\t\t}\n\t\t\n\t\tparams.put(\"associatedFilePath\", '%'+pFilePath);\n\t\tparams.put(\"content\", pContent+'%');\n\t\tparams.put(\"artifactType\", pArtifactType.ordinal());\n\t\tparams.put(\"lineIndex\",pLine);\n\t\t\n\t\t\n\t\t\n\t\tList<Artifact> artifact_objects = \n\t\t\t\t(List<Artifact>) HibernateUtil.executeReader(hql,params);\n\t \n\t \n\t Artifact artifact_obj=null;\n\t if(artifact_objects.size()!=0)\n\t {\n\t \tartifact_obj = \n\t\t\t\tartifact_objects.get(0);\n\t }\n\t return artifact_obj;\n\t}\n\tpublic static Artifact findInstanceByContent(Type pArtifactType, String pFilePath, \n\t\t\tString pContent ){\n\t\t\n\t\tHashMap<String, Object> params = new HashMap<String, Object>();\n\t\tString hql = \"from Artifact where artifactType =:artifactType and\" +\n\t\t\t\t\" associatedFilePath like :associatedFilePath and content like:content \";\n\t\t\n\t\t\n\t\tparams.put(\"associatedFilePath\", '%'+pFilePath+'%');\n\t\tparams.put(\"content\", '%'+pContent+'%');\n\t\tparams.put(\"artifactType\", pArtifactType.ordinal());\n\t\t\n\t\tList<Artifact> artifact_objects = \n\t\t\t\t(List<Artifact>) HibernateUtil.executeReader(hql,params);\n\t \n\t \n\t Artifact artifact_obj=null;\n\t if(artifact_objects.size()!=0)\n\t {\n\t \tartifact_obj = \n\t\t\t\tartifact_objects.get(0);\n\t }\n\t return artifact_obj;\n\t}\n\tpublic static Artifact findInstanceByContentEnd(Type pArtifactType, String pFilePath, \n\t\t\tString pContent ){\n\t\tHashMap<String, Object> params = new HashMap<String, Object>();\n\t\tString hql = \"from Artifact where artifactType =:artifactType and\" +\n\t\t\t\t\" associatedFilePath like :associatedFilePath and content like:content \";\n\t\t\n\t\tparams.put(\"associatedFilePath\", '%'+pFilePath+'%');\n\t\tparams.put(\"content\", '%'+pContent);\n\t\tparams.put(\"artifactType\", pArtifactType.ordinal());\n\t\t\n\t\tList<Artifact> artifact_objects = \n\t\t\t\t(List<Artifact>) HibernateUtil.executeReader(hql,params);\n\t Artifact artifact_obj=null;\n\t if(artifact_objects.size()!=0)\n\t {\n\t \tartifact_obj = \n\t\t\t\tartifact_objects.get(0);\n\t }\n\t return artifact_obj;\n\t}\n\tpublic static Artifact findInstanceByExactContent(Type pArtifactType, String pFilePath, \n\t\t\tString pContent ){\n\t\tHashMap<String, Object> params = new HashMap<String, Object>();\n\t\tString hql = \"from Artifact where artifactType =:artifactType and\" +\n\t\t\t\t\" associatedFilePath like :associatedFilePath and content like:content \";\n\t\t\n\t\tparams.put(\"associatedFilePath\", '%'+pFilePath+'%');\n\t\tparams.put(\"content\", pContent);\n\t\tparams.put(\"artifactType\", pArtifactType.ordinal());\n\t\t\n\t\tList<Artifact> artifact_objects = \n\t\t\t\t(List<Artifact>) HibernateUtil.executeReader(hql,params);\n\t Artifact artifact_obj=null;\n\t if(artifact_objects.size()!=0)\n\t {\n\t \tartifact_obj = \n\t\t\t\tartifact_objects.get(0);\n\t }\n\t return artifact_obj;\n\t}\n\tpublic static Artifact findInstance(Type pArtifactType, String pFilePath, \n\t\t\tint pStartChar, String pContent, String pSecondWord){\n\t\t\n\t\tHashMap<String, Object> params = new HashMap<String, Object>();\n\t\tString hql = \"from Artifact where artifactType =:artifactType and\" +\n\t\t\t\t\" associatedFilePath like :associatedFilePath and content like:content \" +\n\t\t\t\t\" and ABS(startIndex - :pStartIndex) <45\";\n\t\tif (pSecondWord != null)\n\t\t{\n\t\t\thql += \"and nextArtifact.content = :nextContent\";\n\t\t\tparams.put(\"nextContent\", pSecondWord);\n\t\t}\n\t\n\t\t\n\t\tparams.put(\"associatedFilePath\", '%'+pFilePath);\n\t\tparams.put(\"content\", pContent+'%');\n\t\tparams.put(\"artifactType\", pArtifactType.ordinal());\n\t\tparams.put(\"pStartIndex\",pStartChar);\n\t\t\n\t\t\n\t\t\n\t\tList<Artifact> artifact_objects = \n\t\t\t\t(List<Artifact>) HibernateUtil.executeReader(hql,params);\n\t \n\t \n\t Artifact artifact_obj=null;\n\t if(artifact_objects.size()!=0)\n\t {\n\t \tartifact_obj = \n\t\t\t\tartifact_objects.get(0);\n\t }\n\t return artifact_obj;\n\t}\n\tpublic static Artifact findInstanceByStartIndex(String pFilePath,int pStartIndex){\n\t\tString hql = \"from Artifact where associatedFilePath like :associatedFilePath and artifactType=:artifactType and startIndex=:startIndex \";\n\n\t\tHashMap<String, Object> params = new HashMap<String, Object>();\n\t\tparams.put(\"associatedFilePath\", '%'+pFilePath);\n\t\tparams.put(\"startIndex\", pStartIndex);\n\t\tparams.put(\"artifactType\", 3);\n\t\t\n\n\t\tList<Artifact> artifact_objects = \n\t\t\t\t\t(List<Artifact>) HibernateUtil.executeReader(hql, params);\n\n\n\t Artifact artifact_obj=null;\n\t if(artifact_objects.size()!=0)\n\t {\n\t \tartifact_obj = \n\t\t\t\tartifact_objects.get(0);\n\t }\n\t return artifact_obj;\n\t}\n\tpublic static Artifact findInstanceByEndIndex(String pFilePath,int pEndIndex){\n\t\tString hql = \"from Artifact where associatedFilePath like :associatedFilePath and artifactType=:artifactType and endIndex=:endIndex \";\n\n\t\tHashMap<String, Object> params = new HashMap<String, Object>();\n\t\tparams.put(\"associatedFilePath\", '%'+pFilePath);\n\t\tparams.put(\"endIndex\", pEndIndex);\n\t\tparams.put(\"artifactType\", 3);\n\t\t\n\n\t\tList<Artifact> artifact_objects = \n\t\t\t\t\t(List<Artifact>) HibernateUtil.executeReader(hql, params);\n\n\n\t Artifact artifact_obj=null;\n\t if(artifact_objects.size()!=0)\n\t {\n\t \tartifact_obj = \n\t\t\t\tartifact_objects.get(0);\n\t }\n\t return artifact_obj;\n\t}\n\tpublic static List<Artifact> listByType(Type pSentenceType) {\n\t\tString hql = \"from Artifact where artifactType = \"+pSentenceType.ordinal()\n\t\t\t\t+\" order by associatedFilePath\";\n\t\t\t\n\t\tList<Artifact> artifact_objects = \n\t\t\t\t(List<Artifact>) HibernateUtil.executeReader(hql);\n\t\treturn artifact_objects;\n\t}\n\t//TODO: move this method to the right class\n\tpublic static List<Artifact> listTweets(Type pSentenceType) {\n\t\tString hql = \"from Artifact where artifactType = \"+pSentenceType.ordinal()\n\t\t\t\t+\" and associatedFilePath not like '%host%' order by associatedFilePath\";\n\t\t\t\n\t\tList<Artifact> artifact_objects = \n\t\t\t\t(List<Artifact>) HibernateUtil.executeReader(hql);\n\t\treturn artifact_objects;\n\t}\n\tpublic static List<Artifact> listByTypeByForTrain(Type pSentenceType, boolean forTrain) {\n\t\tString hql = \"from Artifact where artifactType = \"+pSentenceType.ordinal()\n\t\t\t\t+\" and forTrain= \"+forTrain+\" order by associatedFilePath\";\n\t\t\t\n\t\tList<Artifact> artifact_objects = \n\t\t\t\t(List<Artifact>) HibernateUtil.executeReader(hql);\n\t\treturn artifact_objects;\n\t}\n\tpublic static List<Artifact> listByTypeByForTrainByCorpus(Type pSentenceType, boolean forTrain,String corpusName) {\n\t\tString hql = \"from Artifact where artifactType = \"+pSentenceType.ordinal()\n\t\t\t\t+\" and forTrain= \"+forTrain+\" and corpusName= '\"+corpusName+\"' order by associatedFilePath\";\n\t\t\t\n\t\tList<Artifact> artifact_objects = \n\t\t\t\t(List<Artifact>) HibernateUtil.executeReader(hql);\n\t\treturn artifact_objects;\n\t}\n\n\tpublic static List<Artifact> listByTypeLimited(Type pSentenceType,boolean for_train, Integer count) {\n\t\t\n\t\tString hql = \"from Artifact where artifactType = \"+pSentenceType.ordinal()\n\t\t\t\t+\" and forTrain = \"+for_train+\" order by rand()\";\n\t\tHashMap<String, Object> params = new HashMap<String, Object>();\n\t\tList<Artifact> artifact_objects = \n\t\t\t\t(List<Artifact>) HibernateUtil.executeReader(hql,params,count);\n\t\treturn artifact_objects;\n\t}\n\tpublic static List<Artifact> listByType(Type pSentenceType,boolean for_train) {\n\t\tString file_path_pattern = \"/train/\";\n\t\tif (!for_train)\n\t\t{\n\t\t\tfile_path_pattern = \"/test/\";\n\t\t}\n\t\tString hql = \"from Artifact where artifactType = \"+pSentenceType.ordinal()\n\t\t\t\t+\" and associatedFilePath like :pPattern order by associatedFilePath\";\n\t\tHashMap<String, Object> params = new HashMap<String, Object>();\n\t\tparams.put(\"pPattern\", '%'+file_path_pattern+'%');\n\t\tList<Artifact> artifact_objects = \n\t\t\t\t(List<Artifact>) HibernateUtil.executeReader(hql,params);\n\t\treturn artifact_objects;\n\t}\n\n\tpublic void setStanDependency(String stanDependency) {\n\t\tthis.stanDependency = stanDependency;\n\t}\n\t@Column(length = 2000)\n\tpublic String getStanDependency() {\n\t\treturn stanDependency;\n\t}\n\t\n\tpublic void setStanPennTree(String stanPennTree) {\n\t\tthis.stanPennTree = stanPennTree;\n\t}\n\t@Column(length = 2000)\n\tpublic String getStanPennTree() {\n\t\treturn stanPennTree;\n\t}\n\t@Transient\n\tList<Artifact> children = null;\n\t@Transient\n\tpublic Artifact getChildByWordIndex(int word_index) {\n\t\tif(children==null)\n\t\t\tloadChildren();\n\t\tArtifact foundArtifact = null;\n\t\tfor(Artifact art : children)\n\t\t\tif(art.getWordIndex() == word_index)\n\t\t\t{\n\t\t\t\tfoundArtifact = art;\n\t\t\t\tbreak;\n\t\t\t}\n\t\treturn foundArtifact;\n\t}\n\tprivate void loadChildren() {\n\t\tString hql = \"from Artifact where parentArtifact = \"+getArtifactId();\n\t\t\n\t\tchildren = \n\t\t\t\t(List<Artifact>) HibernateUtil.executeReader(hql);\n\t}\n\t\n\tpublic static List<Artifact> listByTypeAndForTrain(Type pSentenceType,boolean for_train) {\n\n\t\tString hql = \"from Artifact where forTrain =\"+for_train+\" and artifactType = \"+pSentenceType.ordinal()\n\t\t\t\t+\" order by associatedFilePath\";\n\t\tHashMap<String, Object> params = new HashMap<String, Object>();\n\t\tList<Artifact> artifact_objects = \n\t\t\t\t(List<Artifact>) HibernateUtil.executeReader(hql);\n\t\treturn artifact_objects;\n\t}\n\tpublic static List<Artifact> listByTypeAndForTrain(Type pSentenceType,boolean for_train,String corpus) {\n\n\t\tString hql = \"from Artifact where forTrain =\"+for_train+\" and artifactType = \"+pSentenceType.ordinal()\n\t\t\t\t+\" and corpusName='\"+corpus+\"' order by associatedFilePath\";\n\t\tHashMap<String, Object> params = new HashMap<String, Object>();\n\t\tList<Artifact> artifact_objects = \n\t\t\t\t(List<Artifact>) HibernateUtil.executeReader(hql);\n\t\treturn artifact_objects;\n\t}\n\tpublic boolean isForTrain() {\n\t\treturn forTrain;\n\t}\n\tpublic void setForTrain(boolean forTrain) {\n\t\tthis.forTrain = forTrain;\n\t}\n\tpublic boolean isForDemo() {\n\t\treturn forDemo;\n\t}\n\tpublic void setForDemo(boolean forDemo) {\n\t\tthis.forDemo = forDemo;\n\t}\n\tpublic String getCorpusName() {\n\t\treturn corpusName;\n\t}\n\tpublic void setCorpusName(String name) {\n\t\tthis.corpusName = name;\n\t}\n\t\n}",
"@Entity\n@Table( name = \"FeatureValuePair\" )\npublic class FeatureValuePair {\n\tpublic enum FeatureName {\n\t\t// Document Features\n\t\tJournalTitle,\n\t\tCompletedYear,\n\t\tCreatedYear,\n\t\tRevisedYear,\n\t\tMESHHeading,\n\t\t\n\n\t\t// Paragraph Features\n\t\t// PositionInDoc,\n\n\t\t// Sentence Features\n\t\tProteinCountInSentence,\n\t\tSentenceTFIDF,\n\n\t\t// Words Features\n\t\tPOS,\n\t\tPOSNext1,\n\t\tPOSNext2,\n\t\tPOSPre1,\n\t\tPOSPre2,\n\t\t\n\t\tPorterStem, \n\t\tWordnetStem, \n\t\tOriginalWord, \n\t\tNameEntity, \n\t\tStartWithUppercase, \n\t\tAllUppercase, \n\t\tAllLowercase, \n\t\tHasSpecialChars, \n\t\tHasDigit, \n\t\t\n\t\tCommaLeftCount,\n\t\tCommaRightCount,\n\t\tQuoteLeftCount,\n\t\tQuoteRightCount,\n\t\tProteinCountInWindow,\n\t\t\n\t\tSimilarityToGene_expression, \n\t\tSimilarityToTranscription, \n\t\tSimilarityToProtein_catabolism, \n\t\tSimilarityToLocalization, \n\t\tSimilarityToBinding, \n\t\tSimilarityToPhosphorylation, \n\t\tSimilarityToRegulation, \n\t\tSimilarityToPositive_regulation, \n\t\tSimilarityToNegative_regulation,\n\t\tPositionInDoc,\n\t\t\n\t\t//coreference features\n\t\tAnaphoraIsSubject,\n\t\tAntecedentInFirstSubject,\n\t\tAntecedentInHeader,\n\t\tAntecedentIsSubject,\n\t\tAppositive,\n\t\tNumberAgreement,\n\t\tSentenceDistance, TWOGram, TWOGramBackward, ThreeGram, ThreeGramBackward, NellLink, \n\t\tProblemCountInSentence, TestCountInSentence, TreatmentCountInSentence, TestsBeforeWord, \n\t\tTreatmentsBeforeWord, ProblemsBeforeWord, ProblemPossibleCountInSentence, ProblemHypoCountInSentence, \n\t\tProblemConditionalCountInSentence, ProblemAWSECountInSentence, ProblemAbsentCountInSentence, ProblemPresentCountInSentence, EdgeType,\n\t\tWordWindowNext, WordWindowPre, EdgeParsePath, EdgeParseDistance, DependencyLinkedTokens,\n\t\t\n\t\tTimexCount, ClinicalEventsCount, LinkWordBetween, LinkArgumentType, LinkFromPhrasePolarity, LinkFromPhraseModality, LinkFromPhraseType, LinkToPhraseModality, LinkToPhraseType, \n\t\tLinkToPhrasePolarity, LinkToPhraseTimexMod, LinkFromPhraseTimexMod, \n\t\tInterMentionLocationType, AreDirectlyConnected, HaveCommonGovernors, AreConjunctedAnd,\n\t\t//NGrams\n\t\tNonNormalizedNGram2, NonNormalizedNGram3, NorBetweenNGram2, NorBetweenNGram3, Link2GramBetween, \n\t\tLink2GramFrom,Link2GramTo,\n\t\t\n\t\t//Link Args basic features\n\t\tFromPhraseContent, ToPhraseContent, FromPhrasePOS, ToPhrasePOS,\n\t\t\n\t\tLinkBetweenWordCount, LinkBetweenPhraseCount, \n\t\t\n\t\t//ParseDependency features\n\t\tFromPhraseRelPrep, ToPhraseRelPrep, FromPhraseGovVerb, ToPhraseGovVerb, FromPhraseGovVerbTense,\n\t\tFromPhraseGovVerbAux, toPhraseGovVerbAux, areGovVerbsConnected,\n\t\tnormalizedDependencies,\n\t\t//pattern statistics\n\t\tPOverlapGivenPattern, PBeforeGivenPattern, PAfterGivenPattern, PNoLinkGivenPattern, hasFeasibleLink, \n\t\tPOverlapGivenPatternTTO, PBeforeGivenPatternTTO, PAfterGivenPatternTTO, PNoLinkGivenPatternTTO,\n\t\tmaxProbClassByPattern,\n\t\t\n\t\tParseTreePath, ParseTreePathSize,\n\t\t\n\t\t\n\t\t//sectime features\n\t\trelatedSectionInDoc, AdmissionOrDischarge, \n\t\t//normalized \n\t\tfromPrepArg, toPrepArg, isToPhDirectPrepArgOfFromPh, isEventAfterProblem, norToTypeDep,\n\t\tfromToToPathExist, toToFromPathExist, fromToToPathSize, toToFromPathSize, customGraphPath,\n\t\t//custom graph\n\n\t\tLabeledGraphNorDepPath, customGraphIndividualPath, customGraphPathString,\n\t\t\n\n\t\tTemporalSignal, FromPhrasePOS1By1, ToPhrasePOS1By1, \n\t\tFromPhrasePOSWindowBefore, ToPhrasePOSWindowBefore, \n\t\tFromPhrasePOSWindowAfter, ToPhrasePOSWindowAfter, \n\t\tToPhrasePOSBigramAfter, FromPhrasePOSBigramBefore,\n\t\tToPhrasePOSBigramBefore, FromToPhrasePOSBigram, LinkFromToWordDistance, LinkPOSBetween,\n\t\t\n\t\t\n\t\tbetweenChunck, \n\t\t\n\t\t//for the deext project\n\t\tchunkContent, embeddings,\n\t\t\n\t\t//For Twitter\n\t\tcontent, hasTermInADRDic, \n\t\t\n\t\t//for conceptExtraction\n\t\tTokenContent, PrevTokenContent, NextTokenContent, SecondPrevTokenContent, SecondNextTokenContent, PositiveTokensInChunk, NegativeTokensInChunk, \n\t\tPositiveTokensInNbrChunk, NegativeTokensInNbrChunk, MaxLexiconSim, isInLexiconEntry, GovVerb, MaxPhraseLexSim, BinaryLexiconSim, DeepClassNumber, PrevDeepClassNumber, SecondPrevDeepClassNumber, NextDeepClassNumber, SecondNextDeepClassNumber, GovVerbDeepClassNumber,\n\t\tisTokenInLexicon,isTokenNegated, TokenContentProcessed, isTokenNegatedExpanded,ThirdPrevTokenContent,ThirdNextTokenContent,ThirdPrevDeepClassNumber,\n\t\tThirdNextDeepClassNumber,isPrevTokenInLexicon,isSPrevTokenInLexicon, isNextTokenInLexicon, isSNextTokenInLexicon,\n\t\t\n\t\t//for SVM classifier\n\t\tSVMCandTokenContent, SVMCandPrevTokenContent, SVMCandSecondPrevTokenContent, SVMCandNextTokenContent, SVMCandSecondNextTokenContent, SVMCandGovVerb, Token_IDF, Token_Lexicon_IDF, \n\t\tSVMCandParSentToken, SVMCandParSentTokenIdf, SVMCandBigrams, SVMCandParSenDeepClassNumber, SVMCandThirdNextTokenContent, SVMCandThirdPrevTokenContent, \n\t\tSVMIsPhraseNegatedExpanded, SVMIsPhraseNegated, \n\t\t//hierachical clustering bitstring\n\t\tHClusterBitStringCurrent, PrevHClusterBitString, SecondPrevHClusterBitString, ThirdPrevHClusterBitString, NextHClusterBitString, SecondNextHClusterBitString, ThirdNextHClusterBitString,\n\t\tHClusterBitStringCurrent8, PrevHClusterBitString8, SecondPrevHClusterBitString8, ThirdPrevHClusterBitString8, NextHClusterBitString8, SecondNextHClusterBitString8, ThirdNextHClusterBitString8,\n\t\tHClusterBitStringCurrent4, PrevHClusterBitString4, SecondPrevHClusterBitString4, ThirdPrevHClusterBitString4, NextHClusterBitString4, SecondNextHClusterBitString4, ThirdNextHClusterBitString4, \n\t\t\n\t\tWord2vecADRSimilarity, Word2vecIndicationSimilarity, \n\t\t\n\n\t\t\n\t}\n\n\tString featureName;\n\tString featureValue;\n\t\n\t//For string multi features this can be used to handle real value \n\t// othewise 1 or 0 would be used for values(for tf_idfs)\n\tprivate String featureValueAuxiliary;\n\t\n\tprivate int featureValuePairId = -1;\n\t\n\t//reset every time used for training a model;-1 means not used in training\n\tprivate int tempFeatureIndex = -1;\n\t\n\t\n\t\n\tpublic int getTempFeatureIndex() {\n\t\treturn tempFeatureIndex;\n\t}\n\tpublic void setTempFeatureIndex(int tempFeatureIndex) {\n\t\tthis.tempFeatureIndex = tempFeatureIndex;\n\t}\n\tpublic void setFeatureName(String _featureName) {\n\t\tfeatureName = _featureName;\n\t}\n\t@NaturalId\n\tpublic String getFeatureName() {\n\t\treturn featureName;\n\t}\n\n\t\n\tpublic void setFeatureValue(String _featureValue) {\n\t\tfeatureValue = _featureValue;\n\t}\n\t@NaturalId\n\tpublic String getFeatureValue() {\n\t\treturn featureValue;\n\t}\n\t\n\tpublic FeatureValuePair()\n\t{\n\t\n\t}\n\t\n\n\t\n\tpublic void setFeatureValuePairId(int featureValuePairId) {\n\t\tthis.featureValuePairId = featureValuePairId;\n\t}\n\t@Id\n\t@GeneratedValue(generator=\"increment\")\n\t@GenericGenerator(name=\"increment\", strategy = \"increment\")\n\tpublic int getFeatureValuePairId() {\n\t\treturn featureValuePairId;\n\t}\n\n\t\n\tvoid setFeatureValueAuxiliary(String featureValueAuxiliary) {\n\t\tthis.featureValueAuxiliary = featureValueAuxiliary;\n\t}\n\t@NaturalId\n\tpublic String getFeatureValueAuxiliary() {\n\t\treturn featureValueAuxiliary;\n\t}\n\t\n\t@Override public String toString()\n\t{\n\t\treturn featureName+\" = \"+ featureValue + \n\t\t\t\" (\"+featureValueAuxiliary+\")\";\n\t}\n\t\n\t@Override public boolean equals(Object pFeatureValuePair)\n\t{\n\t\tif(!(pFeatureValuePair instanceof FeatureValuePair))\n\t\t\treturn false;\n\t\tFeatureValuePair fvp = (FeatureValuePair)pFeatureValuePair;\n\t\tif(fvp.getFeatureValuePairId() == featureValuePairId ||\n\t\t\t\t(fvp.getFeatureName() == featureName &&\n\t\t\t\t\tfvp.getFeatureValue().equals(featureValue)&&\n\t\t\t\t\tfvp.getFeatureValueAuxiliary() == featureValueAuxiliary))\n\t\t\treturn true;\n\t\telse \n\t\t\treturn false;\n\t\t\n\t}\n\t@Override public int hashCode()\n\t{\n\t\treturn featureValuePairId;\n\t}\n\tpublic static FeatureValuePair getInstance(String pFeatureName, \n\t\t\tString pFeatureValue,\n\t\t\tString pFeatureValueAuxiliary){\n\t\treturn getInstance(pFeatureName, pFeatureValue, pFeatureValueAuxiliary, false);\n\t}\n\tpublic static FeatureValuePair getInstance(String pFeatureName, \n\t\t\tString pFeatureValue,\n\t\t\tString pFeatureValueAuxiliary,\n\t\t\tboolean isDense)\n\t{\n\t\tFeatureValuePair feature_value;\n\n\t\n\t\t\n\t\tString hql = \"from FeatureValuePair where featureName= :featureName \"+\n\t\t\t\t\t\" AND featureValue= :featureValue \";\n\t\t\n\t\tHashMap<String, Object> params = new HashMap<String, Object>();\n\t\tparams.put(\"featureValue\", pFeatureValue);\n\t\tparams.put(\"featureName\", pFeatureName);\n\t\t\n\t\tif(pFeatureValueAuxiliary!=null)\n\t\t{\n\t\t\thql += \" AND featureValueAuxiliary= :featureValueAuxiliary \";\n\t\t\tparams.put(\"featureValueAuxiliary\", pFeatureValueAuxiliary);\n\t\t}\n\t\t\n\t\tList<FeatureValuePair> featurev_list = \n\t\t\t(List<FeatureValuePair>) HibernateUtil.executeReader(hql, params);\n\t\t\n\t\tif(featurev_list.size() == 0)\n\t\t{\n\t\t\tfeature_value = new FeatureValuePair();\n\t\t\tfeature_value.setFeatureName(pFeatureName);\n\t\t\tfeature_value.setFeatureValue(pFeatureValue);\n\t\t\tif(pFeatureValueAuxiliary!=null)\n\t\t\t\tfeature_value.setFeatureValueAuxiliary(pFeatureValueAuxiliary);\n\t\t\tHibernateUtil.save(feature_value);\n\t\t}else\n\t\t\tfeature_value = featurev_list.get(0);\n\t\treturn feature_value;\n\t}\n\t\n\tpublic static FeatureValuePair getInstance(String pFeatureName, \n\t\t\tString pFeatureValue, boolean isDense)\n\t{\n\t\n\t\treturn getInstance(pFeatureName, pFeatureValue, null, isDense);\n\t}\n\tpublic static FeatureValuePair getInstance(String pFeatureName, \n\t\t\tString pFeatureValue)\n\t{\n\t\n\t\treturn getInstance(pFeatureName, pFeatureValue, null, false);\n\t}\n\t\n\tpublic static List<String> multiValueFeatures = new ArrayList<String>();\n\tstatic\n\t{\n\t\tmultiValueFeatures.add(FeatureName.MESHHeading.name());\n\t\tmultiValueFeatures.add(FeatureName.SentenceTFIDF.name());\n\t\tmultiValueFeatures.add(FeatureName.LinkWordBetween.name());\n\t}\n\t@Transient\n\t//TODO make it better\n\tpublic boolean isMultiValue()\n\t{\n\t\tboolean res = false;\n\t\t\n\t\tif(multiValueFeatures.contains(featureName))\n\t\t\tres = true;\n\n\t\treturn res;\n\t}\n\tpublic static void resetIndexes() {\n\t\tString hql = \"update FeatureValuePair set tempFeatureIndex = \"+Integer.MAX_VALUE;\n\t\tHibernateUtil.executeNonReader(hql);\n\t\tSession temp_Session = HibernateUtil.sessionFactory.openSession();\n\t\tString selecthql = \"from FeatureValuePair\";\n\n\n\t\tList<FeatureValuePair> features = \n\t\t\t(List<FeatureValuePair>) HibernateUtil.executeReader(selecthql,null,null, temp_Session);\n\t\tint new_feature_index = 0;\n\t\tint count =0;\n\t\tfor(int i=0;i<features.size();i++) {\n\t\t\tcount++;\n\t\t\t\n//\t\t\tFileUtil.logLine(null,\"resetIndexes--------feature processed: \"+count+\"/\"+features.size());\n\t\t\ttemp_Session = HibernateUtil.clearSession(temp_Session);\n\t\t\t\n\t\t\t//load again fvp to get effect of bulk update\n\t\t\tString selectfvp = \"from FeatureValuePair where featureValuePairId = \"+features.get(i).getFeatureValuePairId();\n\t\t\t\n\t\t\tFeatureValuePair fvp = \n\t\t\t\t((List<FeatureValuePair>) HibernateUtil.executeReader(selectfvp,null,null, temp_Session)).get(0);\n\t\t\t\n\t\t\tint featureIndex = \n\t\t\t\t\tfvp.getTempFeatureIndex();\n\t\t\tif(featureIndex==Integer.MAX_VALUE)\n\t\t\t{\n\t\t\t\tnew_feature_index ++;\n\t\t\t\tif(fvp.getFeatureValueAuxiliary()!=null)\n\t\t\t\t{\n\t\t\t\t\tfeatureIndex = new_feature_index;\n\t\t\t\t\tfvp.setTempFeatureIndex(featureIndex);\n\t\t\t\t\tHibernateUtil.save(fvp, temp_Session);\n\t\t\t\t}else\n\t\t\t\t{\n\t\t\t\t\t//feature index for attribute not set before\n\t\t\t\t\t//find one for the attribute\n\t\t\t\t\tfeatureIndex = new_feature_index;\n\t\t\t\t\t\n\t\t\t\t\tString update_attribute_index_hql = \n\t\t\t\t\t\t\"UPDATE FeatureValuePair set tempFeatureIndex = \"+ featureIndex\n\t\t\t\t\t\t+ \" where featureName='\"+fvp.getFeatureName()+\"'\";\n\t\t\t\t\tHibernateUtil.executeNonReader(update_attribute_index_hql);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\ttemp_Session.clear();\n\t\ttemp_Session.close();\n\t}\n\tpublic static int getMaxIndex() {\n\t\tSession tmp_session = HibernateUtil.sessionFactory.openSession();\n\t\tString hql = \"select max(tempFeatureIndex) from FeatureValuePair where tempFeatureIndex<\"+Integer.MAX_VALUE;\n\t\tList res = HibernateUtil.executeReader(hql, null,null,tmp_session);\n\t\ttmp_session.clear();\n\t\ttmp_session.close();\n\t\treturn (res.get(0)==null)?0:Integer.valueOf(res.get(0).toString());\n\t}\n\tpublic static int getMinIndexForAttribute(String attributeName) {\n\t\tString hql = \"select min(tempFeatureIndex) from FeatureValuePair where \" +\n\t\t\t\t\"featureName='\" + attributeName + \"'\";\n\t\tList res = HibernateUtil.executeReader(hql);\n\t\treturn (res.get(0)==null)?0:Integer.valueOf(res.get(0).toString());\n\t}\n\tpublic static FeatureValuePair getInstance(FeatureName linkType,\n\t\t\tString pFeatureValue) {\n\t\t\n\t\treturn getInstance(linkType.name(), pFeatureValue);\n\t}\n\t\n\tpublic static FeatureValuePair getInstance(FeatureName linkType,\n\t\t\tString pFeatureValue, String auxValue) {\n\t\t\n\t\treturn getInstance(linkType.name(), pFeatureValue, auxValue);\n\t}\n\tpublic static Integer getRelatedFromEventTypeFValuePairIds(\n\t\t\tString pFeatureValue)\n\t{\n\t\tInteger feature_value_id =null;\n\t\t\n//\t\tString featureValueString = \"\";\n//\t\tfor(String val: pFeatureValues)\n//\t\t{\n//\t\t\tfeatureValueString = featureValueString.concat(\", '\"+val+\"'\");\n//\t\t}\n//\t\tfeatureValueString = featureValueString.replaceFirst(\",\", \"\");\n\t\t\n\t\tString hql = \"from FeatureValuePair where featureName in ('LinkFromPhraseType') \"+\n\t\t\t\t\t\" AND featureValue = '\"+pFeatureValue+\"' \";\n\t\t\n\t\t\n\t\tList<FeatureValuePair> featurev_list = \n\t\t\t(List<FeatureValuePair>) HibernateUtil.executeReader(hql);\n\t\tif (featurev_list.size() !=0)\n\t\t{\n\t\t\tfeature_value_id = featurev_list.get(0).getFeatureValuePairId();\n\t\t}\n\t\t\n\t\treturn feature_value_id;\n\t}\n\tpublic static Integer getRelatedToEventTypeFValuePairIds(\n\t\tString pFeatureValue)\n\t{\n\t\tInteger feature_value_id =null;\n\t\t\n//\t\tString featureValueString = \"\";\n//\t\tfor(String val: pFeatureValues)\n//\t\t{\n//\t\t\tfeatureValueString = featureValueString.concat(\", '\"+val+\"'\");\n//\t\t}\n//\t\tfeatureValueString = featureValueString.replaceFirst(\",\", \"\");\n\t\t\n\t\tString hql = \"from FeatureValuePair where featureName in ('LinkToPhraseType') \"+\n\t\t\t\t\t\" AND featureValue ='\"+pFeatureValue+\"' \";\n\t\t\n\t\t\n\t\tList<FeatureValuePair> featurev_list = \n\t\t\t(List<FeatureValuePair>) HibernateUtil.executeReader(hql);\n\t\tif (featurev_list.size() !=0)\n\t\t{\n\t\t\tfeature_value_id = featurev_list.get(0).getFeatureValuePairId();\n\t\t}\n\t\t\n\t\treturn feature_value_id;\n\t}\n\tpublic static List<FeatureValuePair> getInstancesBulk(\n\t\t\tList<String> vector_values, String featurePrefix) {\n\t\t\n\t\tString valuesOfInterest = \"\";\n\t\tfor (Integer d=0;d<vector_values.size();d++)\n\t\t{\n\t\t\tString curValue = vector_values.get(d);\n\t\t\tvaluesOfInterest+=\"'\"+curValue+\"',\";\n\t\t}\n\t\tvaluesOfInterest+=\"''\";\n\t\tString hql = \"from FeatureValuePair where featureName like :featurePrefix and featureValue in (\"+valuesOfInterest+\")\";\n\t\t\n\t\tHashMap<String, Object> params = new HashMap<String, Object>();\n\t\tparams.put(\"featurePrefix\", featurePrefix+\"%\");\n\t\t\n\t\tList<FeatureValuePair> featurev_list = \n\t\t\t(List<FeatureValuePair>) HibernateUtil.executeReader(hql, params);\n\t\tHibernateUtil.startTransaction();;\n\t\tSession session = HibernateUtil.saverSession;\n\t\tList<FeatureValuePair> fvpsResult = new ArrayList<FeatureValuePair>();\n\t\t\n\t\tfor (Integer d=0;d<vector_values.size();d++)\n\t\t{\n\t\t\tFeatureValuePair feature_value = null;\n\t\t\tString curValue = vector_values.get(d);\n\t\t\tboolean found = false;\n\t\t\tfor(FeatureValuePair fvp : featurev_list){\n\t\t\t\tif(fvp.getFeatureName().equals(featurePrefix+d) && \n\t\t\t\t\t\tfvp.getFeatureValue().equals(curValue)){\n\t\t\t\t\tfeature_value = fvp;\n\t\t\t\t\tfound = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif(!found){\n\t\t\t\tfeature_value = new FeatureValuePair();\n\t\t\t\tfeature_value.setFeatureName(featurePrefix+d);\n\t\t\t\tfeature_value.setFeatureValue(curValue);\n\t\t\t\tsession.save(feature_value);\n\t\t\t}\n\t\t\t\n\t\t\tfvpsResult.add(feature_value);\n\t\t}\n\t\t\n\t\tHibernateUtil.endTransaction(); \n\t\t\n\t\t\n\t\treturn fvpsResult;\n\t}\n\t\n\t\n}",
"public enum FeatureName {\n\t// Document Features\n\tJournalTitle,\n\tCompletedYear,\n\tCreatedYear,\n\tRevisedYear,\n\tMESHHeading,\n\t\t\n\n\t// Paragraph Features\n\t// PositionInDoc,\n\n\t// Sentence Features\n\tProteinCountInSentence,\n\tSentenceTFIDF,\n\n\t// Words Features\n\tPOS,\n\tPOSNext1,\n\tPOSNext2,\n\tPOSPre1,\n\tPOSPre2,\n\t\t\n\tPorterStem, \n\tWordnetStem, \n\tOriginalWord, \n\tNameEntity, \n\tStartWithUppercase, \n\tAllUppercase, \n\tAllLowercase, \n\tHasSpecialChars, \n\tHasDigit, \n\t\t\n\tCommaLeftCount,\n\tCommaRightCount,\n\tQuoteLeftCount,\n\tQuoteRightCount,\n\tProteinCountInWindow,\n\t\t\n\tSimilarityToGene_expression, \n\tSimilarityToTranscription, \n\tSimilarityToProtein_catabolism, \n\tSimilarityToLocalization, \n\tSimilarityToBinding, \n\tSimilarityToPhosphorylation, \n\tSimilarityToRegulation, \n\tSimilarityToPositive_regulation, \n\tSimilarityToNegative_regulation,\n\tPositionInDoc,\n\t\t\n\t//coreference features\n\tAnaphoraIsSubject,\n\tAntecedentInFirstSubject,\n\tAntecedentInHeader,\n\tAntecedentIsSubject,\n\tAppositive,\n\tNumberAgreement,\n\tSentenceDistance, TWOGram, TWOGramBackward, ThreeGram, ThreeGramBackward, NellLink, \n\tProblemCountInSentence, TestCountInSentence, TreatmentCountInSentence, TestsBeforeWord, \n\tTreatmentsBeforeWord, ProblemsBeforeWord, ProblemPossibleCountInSentence, ProblemHypoCountInSentence, \n\tProblemConditionalCountInSentence, ProblemAWSECountInSentence, ProblemAbsentCountInSentence, ProblemPresentCountInSentence, EdgeType,\n\tWordWindowNext, WordWindowPre, EdgeParsePath, EdgeParseDistance, DependencyLinkedTokens,\n\t\t\n\tTimexCount, ClinicalEventsCount, LinkWordBetween, LinkArgumentType, LinkFromPhrasePolarity, LinkFromPhraseModality, LinkFromPhraseType, LinkToPhraseModality, LinkToPhraseType, \n\tLinkToPhrasePolarity, LinkToPhraseTimexMod, LinkFromPhraseTimexMod, \n\tInterMentionLocationType, AreDirectlyConnected, HaveCommonGovernors, AreConjunctedAnd,\n\t//NGrams\n\tNonNormalizedNGram2, NonNormalizedNGram3, NorBetweenNGram2, NorBetweenNGram3, Link2GramBetween, \n\tLink2GramFrom,Link2GramTo,\n\t\t\n\t//Link Args basic features\n\tFromPhraseContent, ToPhraseContent, FromPhrasePOS, ToPhrasePOS,\n\t\t\n\tLinkBetweenWordCount, LinkBetweenPhraseCount, \n\t\t\n\t//ParseDependency features\n\tFromPhraseRelPrep, ToPhraseRelPrep, FromPhraseGovVerb, ToPhraseGovVerb, FromPhraseGovVerbTense,\n\tFromPhraseGovVerbAux, toPhraseGovVerbAux, areGovVerbsConnected,\n\tnormalizedDependencies,\n\t//pattern statistics\n\tPOverlapGivenPattern, PBeforeGivenPattern, PAfterGivenPattern, PNoLinkGivenPattern, hasFeasibleLink, \n\tPOverlapGivenPatternTTO, PBeforeGivenPatternTTO, PAfterGivenPatternTTO, PNoLinkGivenPatternTTO,\n\tmaxProbClassByPattern,\n\t\t\n\tParseTreePath, ParseTreePathSize,\n\t\t\n\t\t\n\t//sectime features\n\trelatedSectionInDoc, AdmissionOrDischarge, \n\t//normalized \n\tfromPrepArg, toPrepArg, isToPhDirectPrepArgOfFromPh, isEventAfterProblem, norToTypeDep,\n\tfromToToPathExist, toToFromPathExist, fromToToPathSize, toToFromPathSize, customGraphPath,\n\t//custom graph\n\n\tLabeledGraphNorDepPath, customGraphIndividualPath, customGraphPathString,\n\t\t\n\n\tTemporalSignal, FromPhrasePOS1By1, ToPhrasePOS1By1, \n\tFromPhrasePOSWindowBefore, ToPhrasePOSWindowBefore, \n\tFromPhrasePOSWindowAfter, ToPhrasePOSWindowAfter, \n\tToPhrasePOSBigramAfter, FromPhrasePOSBigramBefore,\n\tToPhrasePOSBigramBefore, FromToPhrasePOSBigram, LinkFromToWordDistance, LinkPOSBetween,\n\t\t\n\t\t\n\tbetweenChunck, \n\t\t\n\t//for the deext project\n\tchunkContent, embeddings,\n\t\t\n\t//For Twitter\n\tcontent, hasTermInADRDic, \n\t\t\n\t//for conceptExtraction\n\tTokenContent, PrevTokenContent, NextTokenContent, SecondPrevTokenContent, SecondNextTokenContent, PositiveTokensInChunk, NegativeTokensInChunk, \n\tPositiveTokensInNbrChunk, NegativeTokensInNbrChunk, MaxLexiconSim, isInLexiconEntry, GovVerb, MaxPhraseLexSim, BinaryLexiconSim, DeepClassNumber, PrevDeepClassNumber, SecondPrevDeepClassNumber, NextDeepClassNumber, SecondNextDeepClassNumber, GovVerbDeepClassNumber,\n\tisTokenInLexicon,isTokenNegated, TokenContentProcessed, isTokenNegatedExpanded,ThirdPrevTokenContent,ThirdNextTokenContent,ThirdPrevDeepClassNumber,\n\tThirdNextDeepClassNumber,isPrevTokenInLexicon,isSPrevTokenInLexicon, isNextTokenInLexicon, isSNextTokenInLexicon,\n\t\t\n\t//for SVM classifier\n\tSVMCandTokenContent, SVMCandPrevTokenContent, SVMCandSecondPrevTokenContent, SVMCandNextTokenContent, SVMCandSecondNextTokenContent, SVMCandGovVerb, Token_IDF, Token_Lexicon_IDF, \n\tSVMCandParSentToken, SVMCandParSentTokenIdf, SVMCandBigrams, SVMCandParSenDeepClassNumber, SVMCandThirdNextTokenContent, SVMCandThirdPrevTokenContent, \n\tSVMIsPhraseNegatedExpanded, SVMIsPhraseNegated, \n\t//hierachical clustering bitstring\n\tHClusterBitStringCurrent, PrevHClusterBitString, SecondPrevHClusterBitString, ThirdPrevHClusterBitString, NextHClusterBitString, SecondNextHClusterBitString, ThirdNextHClusterBitString,\n\tHClusterBitStringCurrent8, PrevHClusterBitString8, SecondPrevHClusterBitString8, ThirdPrevHClusterBitString8, NextHClusterBitString8, SecondNextHClusterBitString8, ThirdNextHClusterBitString8,\n\tHClusterBitStringCurrent4, PrevHClusterBitString4, SecondPrevHClusterBitString4, ThirdPrevHClusterBitString4, NextHClusterBitString4, SecondNextHClusterBitString4, ThirdNextHClusterBitString4, \n\t\t\n\tWord2vecADRSimilarity, Word2vecIndicationSimilarity, \n\t\t\n\n\t\t\n}",
"public interface IFeatureCalculator {\n\tpublic void calculateFeatures(MLExample exampleToProcess) throws SQLException, Exception;\n}",
"@Entity\n@Table( name = \"MLExample\" )\npublic class MLExample {\n\tint exampleId;\n\n\n\tint predictedClass;\n\tint expectedClass;\n\tboolean forTrain;\n\tString corpusName;\n\tString predictionEngine;\n\tArtifact relatedArtifact;\n\tPhraseLink relatedPhraseLink;\n\tprivate String associatedFilePath;\n\tprivate double predictionWeight;\n\tprivate int expectedReal;\n\tprivate int expectedClosure;\n\tprivate int expectedIntegrated;\n\t\n\tprivate Phrase relatedPhrase;\n\t\n\t@Transient\n\tList<MLExampleFeature> exampleFeatures;\n\tstatic public Session hibernateSession; \n\t\n\tString relatedDrug;\n\t@Transient\n\tpublic List<MLExampleFeature> getExampleFeatures()\n\t{\n\t\tif(exampleFeatures==null)\n\t\t{\n\t\t\tif(hibernateSession == null)\n\t\t\t\thibernateSession = HibernateUtil.sessionFactory.openSession();\n\t\t\tString hql = \"from MLExampleFeature where relatedExample = \"+\n\t\t\t getExampleId()+ \n\t\t\t \" order by featureValuePair.tempFeatureIndex\";\n//\t\t\t \" order by featureValuePair.featureValuePairId\";\n\t\t\texampleFeatures = (List<MLExampleFeature>) HibernateUtil.executeReader(hql, null,null, hibernateSession);\n\t\t}\n\t\treturn exampleFeatures;\n\t}\n\t@Transient\n\tpublic List<MLExampleFeature> getNonEmbeddingsExampleFeatures()\n\t{\n\t\tif(exampleFeatures==null)\n\t\t{\n\t\t\tif(hibernateSession == null)\n\t\t\t\thibernateSession = HibernateUtil.sessionFactory.openSession();\n\t\t\tString hql = \"from MLExampleFeature where relatedExample = \"+\n\t\t\t getExampleId()+ \n\t\t\t \" and featureValuePair. featureName not like '%Embeddings%' order by featureValuePair.tempFeatureIndex\";\n//\t\t\t \" order by featureValuePair.featureValuePairId\";\n\t\t\texampleFeatures = (List<MLExampleFeature>) HibernateUtil.executeReader(hql, null,null, hibernateSession);\n\t\t}\n\t\treturn exampleFeatures;\n\t}\n\t@Transient\n\t//TODO: improve this, this is a quick way to get a specific one value String feature\n\tpublic String getFeatureValueForExample(MLExample e, String featureName)\n\t{\n\t\t\n\t\tif(hibernateSession == null || !hibernateSession.isOpen())\n\t\t\thibernateSession = HibernateUtil.sessionFactory.openSession();\n\t\tString hql = \"from MLExampleFeature where relatedExample = \"+\n\t\t e.getExampleId()+ \n\t\t \" and featureValuePair. featureName ='\"+featureName+\"' order by featureValuePair.tempFeatureIndex\";\n//\t\t\t \" order by featureValuePair.featureValuePairId\";\n\t\tList<MLExampleFeature> eFeatures = (List<MLExampleFeature>) HibernateUtil.executeReader(hql, null,null, hibernateSession);\n\t\t\n\t\tif (eFeatures.isEmpty())\n\t\t{\n\t\t\tFileUtil.logLine(\"/tmp/featureErrors.txt\", \"no feature for example id: \"+e.getExampleId());\n\t\t\treturn \"UNK\";\n\t\t}\n\n\t\tMLExampleFeature feature = eFeatures.get(0);\n\t\tFeatureValuePair fvp = feature.getFeatureValuePair();\n\t\t\n\t\treturn fvp.getFeatureValue();\n\t}\n\tpublic String getPredictionEngine() {\n\t\treturn predictionEngine;\n\t}\n\n\tpublic void setPredictionEngine(String pPredictionEngine) {\n\t\tpredictionEngine = pPredictionEngine;\n\t}\n\n\n\t\n\t\n\tpublic String getCorpusName() {\n\t\treturn corpusName;\n\t}\n\t\n\tpublic void setCorpusName(String pCorpusName) {\n\t\tcorpusName = pCorpusName;\n\t}\n\t\n\tpublic boolean getForTrain() {\n\t\treturn forTrain;\n\t}\n//\t@ManyToOne( cascade = {CascadeType.PERSIST, CascadeType.MERGE }, fetch=FetchType.LAZY )\t\n\t@ManyToOne( cascade = {CascadeType.PERSIST, CascadeType.MERGE } )\n @JoinColumn(name=\"relatedArtifact\")\n\tpublic Artifact getRelatedArtifact() {\n\t\treturn relatedArtifact;\n\t}\n\n\tpublic void setRelatedArtifact(Artifact relatedArtifact) {\n\t\tthis.relatedArtifact = relatedArtifact;\n\t}\n\n\t@ManyToOne( cascade = {CascadeType.PERSIST, CascadeType.MERGE} , fetch=FetchType.LAZY )\n @JoinColumn(name=\"relatedPhraseLink\")\n\tpublic PhraseLink getRelatedPhraseLink() {\n\t\treturn relatedPhraseLink;\n\t}\n\n\tpublic void setRelatedPhraseLink(PhraseLink relatedPhraseLink) {\n\t\tthis.relatedPhraseLink = relatedPhraseLink;\n\t}\n\n\tpublic void setForTrain(boolean isForTrain) {\n\t\tforTrain = isForTrain;\n\t}\n\t\n\tpublic int getPredictedClass() {\n\t\treturn predictedClass;\n\t}\n\t\n\tpublic void setPredictedClass(int pPredictedClass) {\n\t\tpredictedClass = pPredictedClass;\n\t}\n\t\n\tpublic int getExpectedClass() {\n\t\treturn expectedClass;\n\t}\n\t\n\tpublic void setExpectedClass(int pExpectedClass) {\n\t\texpectedClass = pExpectedClass;\n\t}\n\t@Id\n\t@GeneratedValue(generator=\"increment\")\n\t@GenericGenerator(name=\"increment\", strategy = \"increment\")\n\tpublic int getExampleId() {\n\t\treturn exampleId;\n\t}\n\n\tpublic void setExampleId(int exampleId) {\n\t\tthis.exampleId = exampleId;\n\t}\n\t@Temporal(TemporalType.TIMESTAMP)\n Date updateTime;\n\t\n\t\n\t@PrePersist\n protected void onCreate() {\n\t\tupdateTime = new Date();\n }\n\n @PreUpdate\n protected void onUpdate() {\n \tupdateTime = new Date();\n }\n\n\tpublic static MLExample getInstanceForArtifact(Artifact artifact,\n\t\t\tString experimentgroup) {\n\t\tString hql = \"from MLExample where relatedArtifact = \"+\n\t\t\t\tartifact.getArtifactId() + \" and corpusName = '\"+\n\t\t\t\texperimentgroup+\"'\";\n\t\t\tList<MLExample> example_objects = \n\t\t\t\t\tgetExamplesList(hql);\n\t\t \n\t\t\tMLExample example_obj;\n\t\t if(example_objects.size()==0)\n\t\t {\n\t\t \texample_obj = new MLExample();\n\t\t \n\t\t \t\n\t\t \texample_obj.setCorpusName(experimentgroup);\n\t\t \texample_obj.setRelatedArtifact(artifact);\n\t\t \t\n\t\t \tif(Setting.SaveInGetInstance)\n\t\t\t \tsaveExample(example_obj);\n\t\t }else\n\t\t {\n\t\t \texample_obj = \n\t\t \t\t\texample_objects.get(0);\n\t\t }\n\t\t return example_obj;\n\t}\n\tpublic static MLExample findInstanceForArtifact(Artifact artifact,\n\t\t\tString experimentgroup) {\n\t\tString hql = \"from MLExample where relatedArtifact = \"+\n\t\t\t\tartifact.getArtifactId() + \" and corpusName = '\"+\n\t\t\t\texperimentgroup+\"'\";\n\t\t\tList<MLExample> example_objects = \n\t\t\t\t\tgetExamplesList(hql);\n\t\t \n\t\t\tMLExample example_obj;\n\t\t if(example_objects.size()==0)\n\t\t {\n\t\t \texample_obj= null;\n\t\t }else\n\t\t {\n\t\t \texample_obj = \n\t\t \t\t\texample_objects.get(0);\n\t\t }\n\t\t return example_obj;\n\t}\n\n\tpublic void calculateFeatures(\n\t\t\tList<IFeatureCalculator> featureCalculators) throws Exception {\n\t\tfor(IFeatureCalculator feature_calculator : featureCalculators)\n\t\t{\n\t\t\tfeature_calculator.calculateFeatures(this);\n\t\t\tHibernateUtil.clearLoaderSession();\n\t\t}\n\t\t\n\t}\n\n\tpublic static MLExample getInstanceForLink(PhraseLink phrase_link,\n\t\t\tString experimentgroup) {\n\t\tString hql = \"from MLExample where relatedPhraseLink = \"+\n\t\t\t\tphrase_link.getPhraseLinkId() + \" and corpusName = '\"+\n\t\t\t\t\t\texperimentgroup+\"'\";\n\t\t\tList<MLExample> example_objects = \n\t\t\t\t\tgetExamplesList(hql);\n\t\t \n\t\t\tMLExample example_obj;\n\t\t if(example_objects.size()==0)\n\t\t {\n\t\t \texample_obj = new MLExample();\n\t\t \n\t\t \t\n\t\t \texample_obj.setCorpusName(experimentgroup);\n\t\t \texample_obj.setRelatedPhraseLink(phrase_link);\n\t\t \texample_obj.setAssociatedFilePath(phrase_link.getFromPhrase().getStartArtifact().getAssociatedFilePath());\n\t\t \t\n\t\t \tif(Setting.SaveInGetInstance)\n\t\t \t\tsaveExample(example_obj);\n\t\t }else\n\t\t {\n\t\t \texample_obj = \n\t\t \t\t\texample_objects.get(0);\n\t\t }\n\t\t return example_obj;\n\t}\n\n\n\tpublic static void saveExample(MLExample example)\n\t{\n\t\tif(hibernateSession == null)\n\t\t\thibernateSession = HibernateUtil.loaderSession;\n\t\t\n\t\tHibernateUtil.save(example, hibernateSession);\n\t}\n\tstatic List<MLExample> getExamplesList(String hql)\n\t{\n\t\tList<MLExample> examples;\n\t\tif(hibernateSession == null || !hibernateSession.isOpen())\n\t\t\thibernateSession = HibernateUtil.loaderSession;\n\t\texamples = \n\t\t\t(List<MLExample>) HibernateUtil.executeReader(hql, null, null, hibernateSession);\n\t\treturn examples;\n\t}\n\tstatic List<MLExample> getExamplesList(String hql, Integer limit)\n\t{\n\t\tList<MLExample> examples;\n\t\tif(hibernateSession == null || !hibernateSession.isOpen())\n\t\t\thibernateSession = HibernateUtil.loaderSession;\n\t\texamples = \n\t\t\t(List<MLExample>) HibernateUtil.executeReader(hql, null, limit, hibernateSession);\n\t\treturn examples;\n\t}\n\tstatic List<MLExample> getExamplesList(String hql, HashMap<String, Object> params)\n\t{\n\t\tList<MLExample> examples;\n\t\tif(hibernateSession == null || !hibernateSession.isOpen())\n\t\t\thibernateSession = HibernateUtil.loaderSession;\n\t\t\n\t\texamples = \n\t\t\t(List<MLExample>) HibernateUtil.executeReader(hql, params, null, hibernateSession);\n\t\treturn examples;\n\t}\n\tpublic static List<MLExample> temptGetAllExamplesFotTrain(String experimentgroup, boolean for_train)\n\t{\n\t\tString hql = \"from MLExample where corpusName = '\"+\n\t\t\t\t\t\texperimentgroup+\"' and forTrain=\"+(for_train?1:0)\n\t\t\t\t\t\t+\" and exampleId < 37406 \"\n\t\t\t\t\t\t+ \" order by relatedArtifact\";\n\t\t\n\t\treturn getExamplesList(hql);\n\t}\n\tpublic static List<MLExample> getAllExamples(String experimentgroup, boolean for_train)\n\t{\n\t\tString hql = \"from MLExample where corpusName = '\"+\n\t\t\t\t\t\texperimentgroup+\"' and forTrain=\"+(for_train?1:0)\n\t\t\t\t\t\t+ \" order by relatedArtifact\";\n\t\t\n\t\treturn getExamplesList(hql);\n\t}\n\t//get limited selected examples \n\tpublic static List<MLExample> getLimitedPreSelectedExamples(String experimentgroup, boolean for_train,String condition)\n\t{\n//\t\ttempIsSelectedForTrain=1\n\t\tString hql = \"from MLExample where corpusName = '\"+\n\t\t\t\t\t\texperimentgroup+\"' and forTrain=\"+(for_train?1:0)\n\t\t\t\t\t\t+ \" and \"+condition+\" order by relatedArtifact\";\n\t\t\n\t\treturn getExamplesList(hql);\n\t}\n\tpublic static List<MLExample> getAllExamplesTwitter(String experimentgroup, boolean for_train)\n\t{\n\t\tString hql = \"from MLExample where corpusName = '\"+\n\t\t\t\t\t\texperimentgroup+\"' and forTrain=\"+(for_train?1:0)\n\t\t\t\t\t\t+\" and expectedClosure=1 order by exampleId\";\n\t\t\n\t\treturn getExamplesList(hql);\n\t}\n\tpublic static List<MLExample> getAllExamples(boolean for_train)\n\t{\n\t\tString hql = \"from MLExample where forTrain=\"+(for_train?1:0)\n\t\t\t\t\t\t+\" order by exampleId\";\n\t\t\n\t\treturn getExamplesList(hql);\n\t}\n\tpublic static List<MLExample> getExampleById(int example_id, String experimentgroup)\n\t{\n\t\tString hql = \"from MLExample where corpusName = '\"+\n\t\t\t\t\t\texperimentgroup+\"' and exampleId=\"+example_id\n\t\t\t\t\t\t+\" order by exampleId\";\n\t\treturn getExamplesList(hql);\n\t}\n\tpublic static MLExample getExampleById(int example_id)\n\t{\n\t\tString hql = \"from MLExample where exampleId=\"+example_id;\n\t\tList<MLExample> example_objects = \n\t\t\t(List<MLExample>) HibernateUtil.executeReader(hql);\n \n\t\tMLExample example_obj=null;\n\t if(example_objects.size()!=0)\n\t {\n\t \texample_obj = \n\t \t\texample_objects.get(0);\n\t }\n\t return example_obj;\n\t}\n\tpublic static List<MLExample> getAllExamples(String experimentgroup, boolean for_train, int limit)\n\t{\n\t\tString hql = \"from MLExample where corpusName = '\"+\n\t\t\t\t\t\texperimentgroup+\"' and forTrain=\"+(for_train?1:0)+\" order by exampleId\";\n\t\treturn getExamplesList(hql,limit);\n\t}\n\tpublic static List<MLExample> getLastExamples(String experimentgroup, boolean for_train, int limit)\n\t{\n\t\tString hql = \"from MLExample where corpusName = '\"+\n\t\t\texperimentgroup+\"' and forTrain=\"+(for_train?1:0)+\n\t\t\t\t\"order by exampleId desc\";\n\t\treturn getExamplesList(hql);\n\t}\n\t\n\tpublic static List<MLExample> getExampleByExpectedClass(String experimentgroup,boolean for_train, LinkType type)\n\t{\n\t\tString hql = \"from MLExample where corpusName = '\"+\n\t\t\t\t\t\texperimentgroup+\"' and expectedClass=\"+type.ordinal()\n\t\t\t\t\t\t+\" and forTrain=\"+(for_train?1:0)+\" order by exampleId\";\n\t\treturn getExamplesList(hql);\n\t}\n\t\n\tpublic static List<MLExample> getExamplesInDocument(String experimentgroup, \n\t\t\tString doc_path)\n\t{\n\t\t\n\t\tString hql = \"FROM MLExample \" +\n\t\t\t\t\"where corpusName =:corpusName \" +\n\t\t\t\t\" and associatedFilePath = '\" +\n\t\t\t\tdoc_path + \"' \" +\n\t\t\t\t\t\t\"order by exampleId desc\";\n\t\t\n\t\tHashMap<String, Object> params = new HashMap<String, Object>();\n\t\tparams.put(\"corpusName\", experimentgroup);\n\t\t\n\t\treturn getExamplesList(hql, params);\n\t}\n\n\tpublic static List<MLExample> getExamplesByDocument(String experimentgroup, \n\t\t\tboolean for_train, int num_of_documents)\n\t{\n\t\tList<Artifact> docs = Artifact.listByType(Type.Document, for_train);\n\t\tif(docs.size()<num_of_documents)\n\t\t\tnum_of_documents = docs.size();\n\t\t\n\t\tString docPaths = \"\";\n\t\tfor(int i=0;i<num_of_documents;i++)\n\t\t\tdocPaths = docPaths.concat(\", '\"+docs.get(i).getAssociatedFilePath()+\"'\");\n\t\tdocPaths = docPaths.replaceFirst(\",\", \"\");\n\t\t\n\t\tString hql = \"FROM MLExample \" +\n\t\t\t\t\"where corpusName =:corpusName \" +\n\t\t\t\t\" and forTrain=\"+(for_train?1:0) +\" and associatedFilePath in (\" +\n\t\t\t\t\t\tdocPaths + \") \" +\n\t\t\t\t\t\t\"order by associatedFilePath desc\";\n\t\t\n\t\tHashMap<String, Object> params = new HashMap<String, Object>();\n\t\tparams.put(\"corpusName\", experimentgroup);\n\t\t\n\t\treturn getExamplesList(hql, params);\n\t}\n\tpublic static List<MLExample> getTokenExamplesBySent(Artifact sent,String experimentgroup, \n\t\t\tboolean for_train)\n\t{\t\n//\t\tString hql = \"FROM MLExample \" +\n//\t\t\t\t\"where corpusName =:corpusName \" +\n//\t\t\t\t\" and forTrain=\"+(for_train?1:0) +\" and relatedArtifact.parentArtifact=\" +sent.getArtifactId()+\n//\t\t\t\t\t\t\n//\t\t\t\t\t\t\" order by associatedFilePath desc\";\n\t\tString hql = \"FROM MLExample \" +\n\t\t\t\t\"where corpusName =:corpusName \" +\n\t\t\t\t\" and relatedArtifact.parentArtifact=\" +sent.getArtifactId()+\n\t\t\t\t\t\t\n\t\t\t\t\t\t\" order by exampleID asc\";\n\t\t\n\t\tHashMap<String, Object> params = new HashMap<String, Object>();\n\t\tparams.put(\"corpusName\", experimentgroup);\n\t\t\n\t\treturn getExamplesList(hql, params);\n\t}\n\t\n\tpublic static List<MLExample> getExamplesByEventTypeByDocument(String experimentgroup, \n\t\t\tboolean for_train, int num_of_documents, String type1,\n\t\t\tString type2,String order)\n\t{\n\t\tList<Artifact> docs = Artifact.listByType(Type.Document,for_train);\n\t\tif(docs.size()<num_of_documents)\n\t\t\tnum_of_documents = docs.size();\n\t\t\n\t\tString docPaths = \"\";\n\t\tif (order.equals(\"top\"))\n\t\t{\n\t\t\tfor(int i=0;i<num_of_documents;i++)\n\t\t\t\tdocPaths = docPaths.concat(\", '\"+docs.get(i).getAssociatedFilePath()+\"'\");\n\t\t\tdocPaths = docPaths.replaceFirst(\",\", \"\");\n\t\t}\n\t\telse if(order.equals(\"last\"))\n\t\t{\n\t\t\tfor(int i=docs.size()-1;i>docs.size()-num_of_documents-1;i--)\n\t\t\t\tdocPaths = docPaths.concat(\", '\"+docs.get(i).getAssociatedFilePath()+\"'\");\n\t\t\tdocPaths = docPaths.replaceFirst(\",\", \"\");\n\t\t}\n\t\tInteger type1_from_fvpIds = FeatureValuePair.getRelatedFromEventTypeFValuePairIds(type1);\n\t\tInteger type1_to_fvpIds = FeatureValuePair.getRelatedToEventTypeFValuePairIds(type1);\n\t\tInteger type2_from_fvpIds = FeatureValuePair.getRelatedFromEventTypeFValuePairIds(type2);\n\t\tInteger type2_to_fvpIds = FeatureValuePair.getRelatedToEventTypeFValuePairIds(type2);\n\t\t\n//\t\tString from_fvpIds = \"\";\n//\t\tfor(Integer id: fromFeatureValuePairIds)\n//\t\t{\n//\t\t\tfrom_fvpIds = from_fvpIds.concat(\", '\"+id+\"'\");\n//\t\t}\n//\t\tfrom_fvpIds = from_fvpIds.replaceFirst(\",\", \"\");\n//\t\t\n//\n//\t\tString to_fvpIds = \"\";\n//\t\tfor(Integer id: toTeatureValuePairIds)\n//\t\t{\n//\t\t\tto_fvpIds = to_fvpIds.concat(\", '\"+id+\"'\");\n//\t\t}\n//\t\tto_fvpIds = to_fvpIds.replaceFirst(\",\", \"\");\n\t\t\n\t\tString hql = \" FROM MLExample m \" +\n\t \"where (( exists (from MLExampleFeature f where m.exampleId =f.relatedExample and featureValuePair in (\"+type1_from_fvpIds+\"))\" +\n\t \" and exists (from MLExampleFeature f where m.exampleId =f.relatedExample and featureValuePair in (\"+type2_to_fvpIds+\"))) or\" +\n\t \" (exists (from MLExampleFeature f where m.exampleId =f.relatedExample and featureValuePair in (\"+type2_from_fvpIds+\")) and \" +\n\t \t\t\"exists (from MLExampleFeature f where m.exampleId =f.relatedExample and featureValuePair in (\"+type1_to_fvpIds+\")))) \" +\n\t \" and corpusName =:corpusName \" +\n\t \" and forTrain=\"+(for_train?1:0) +\" and \" +\n\t \"associatedFilePath in (\" +\n\t docPaths + \") \" +\n \"order by associatedFilePath desc\";\n\t\t\n\t\tHashMap<String, Object> params = new HashMap<String, Object>();\n\t\tparams.put(\"corpusName\", experimentgroup);\n\t\t\n\t\treturn getExamplesList(hql, params);\n\t}\n\tpublic static List<MLExample> getLastExamplesByDocument(String experimentgroup, \n\t\t\tboolean for_train, int num_of_documents)\n\t{\n\t\tList<Artifact> docs = Artifact.listByType(Type.Document,for_train);\n\t\tif(docs.size()<num_of_documents)\n\t\t\tnum_of_documents = docs.size();\n\t\t\n\t\tString docPaths = \"\";\n\t\tfor(int i=docs.size()-1;i>docs.size()-num_of_documents-1;i--)\n\t\t\tdocPaths = docPaths.concat(\", '\"+docs.get(i).getAssociatedFilePath()+\"'\");\n\t\tdocPaths = docPaths.replaceFirst(\",\", \"\");\n\t\t\n\t\tString hql = \"FROM MLExample \" +\n\t\t\t\t\"where corpusName =:corpusName \" +\n\t\t\t\t\" and forTrain=\"+(for_train?1:0) +\" and associatedFilePath in (\" +\n\t\t\t\t\t\tdocPaths + \") \" +\n\t\t\t\t\t\t\"order by associatedFilePath desc\";\n\t\t\n\t\tHashMap<String, Object> params = new HashMap<String, Object>();\n\t\tparams.put(\"corpusName\", experimentgroup);\n\t\t\n\t\treturn getExamplesList(hql, params);\n\t}\n\n\t@Override\n\tpublic MLExample clone()\n\t{\n\t\tif(relatedArtifact!=null)\n\t\t\treturn getInstanceForArtifact(relatedArtifact, corpusName);\n\t\telse\n\t\t\treturn getInstanceForLink(relatedPhraseLink, corpusName);\t}\n\n\n\t\n\tpublic static void resetExamplesPredicted(String experimentgroup, boolean for_train) {\n\t\tString hql = \"update MLExample set predictedClass = -1 where corpusName = '\"+\n\t\t\t\texperimentgroup+\"' and forTrain=\"+(for_train?1:0);\n\t\tHibernateUtil.executeNonReader(hql);\n\t}\n\tpublic static void setExamplePredictedClass(int example_id, int predicted) {\n\t\tString hql = \"update MLExample set predictedClass = \"+predicted+\" where exampleId=\"+example_id;\n\t\tHibernateUtil.executeNonReader(hql);\n\t}\n\tpublic static void resetExamplesPredictedToDefault(String experimentgroup, boolean for_train, int default_predicted) {\n\t\tString hql = \"update MLExample set predictedClass = \"+default_predicted+\" where corpusName = '\"+\n\t\t\t\texperimentgroup+\"' and forTrain=\"+(for_train?1:0);\n\t\tHibernateUtil.executeNonReader(hql);\n\t}\n\n\tpublic void setAssociatedFilePath(String associatedFilePath) {\n\t\tthis.associatedFilePath = associatedFilePath;\n\t}\n\n\tpublic String getAssociatedFilePath() {\n\t\treturn associatedFilePath;\n\t}\n\tpublic static void updateAssociatedFilePath() {\n\t\tString hql = \"from MLExample \";\n\t\tSession tempSession = HibernateUtil.sessionFactory.openSession();\n\t\tList<MLExample> examples = \n\t\t\t\t(List<MLExample>) HibernateUtil.executeReader(hql, null,null, tempSession);\n\t\t\n\t\tfor (MLExample example: examples)\n\t\t{\n\t\t\tPhraseLink related_phrase_link = example.getRelatedPhraseLink();\n\t\t\tPhrase from_phrase = related_phrase_link.getFromPhrase();\n\t\t\tArtifact start_artifact = from_phrase.getStartArtifact();\n\t\t\t\n\t\t\tString file_path = start_artifact.getAssociatedFilePath();\n\t\t\texample.setAssociatedFilePath(file_path);\n\t\t\tHibernateUtil.save(example, tempSession);\n\t\t\t\n\t\t}\n\t\ttempSession.clear();\n\t\ttempSession.close();\n\t}\n\n\tpublic static MLExample findInstance(PhraseLink phrase_link,\n\t\t\tString experimentgroup) {\n\t\tString hql = \"from MLExample where relatedPhraseLink = \"+\n\t\t\t\tphrase_link.getPhraseLinkId() + \" and corpusName = '\"+\n\t\t\t\t\t\texperimentgroup+\"'\";\n\t\t\tList<MLExample> example_objects = \n\t\t\t\t\tgetExamplesList(hql);\n\t\t \n\t\t\tMLExample example_obj=null;\n\t\t if(example_objects.size()!=0)\n\t\t {\n\t\t \texample_obj = \n\t\t \t\t\texample_objects.get(0);\n\t\t }\n\t\t return example_obj;\n\t}\n\tpublic static MLExample findInstance(PhraseLink phrase_link) {\n\t\tString hql = \"from MLExample where relatedPhraseLink = \"+\n\t\t\t\tphrase_link.getPhraseLinkId();\n\t\t\n\t\t\tList<MLExample> example_objects = \n\t\t\t\t\tgetExamplesList(hql);\n\t\t \n\t\t\tMLExample example_obj=null;\n\t\t if(example_objects.size()!=0)\n\t\t {\n\t\t \texample_obj = \n\t\t \t\t\texample_objects.get(0);\n\t\t }\n\t\t return example_obj;\n\t}\n\n\tpublic void setPredictionWeight(double predictionWeight) {\n\t\tthis.predictionWeight = predictionWeight;\n\t}\n\n\tpublic double getPredictionWeight() {\n\t\treturn predictionWeight;\n\t}\n\n\tpublic static List<MLExample> getDecidedExamplesForGraph(Artifact p_sentence) {\n\t\tString hql = \"from MLExample where predictedClass <> -1 \" +\n\t\t\t\t\"and relatedPhraseLink.fromPhrase.startArtifact.parentArtifact = \"+\n\t\tp_sentence.getArtifactId()+\" and relatedPhraseLink.toPhrase.startArtifact.parentArtifact = \"+\n\t\tp_sentence.getArtifactId();\n\n\t\tList<MLExample> example_objects = \n\t\t\t\tgetExamplesList(hql);\n\t \n\t return example_objects;\n\t}\n\t public static List<MLExample> getPhraseExamplesByPredictedClass(Artifact p_sentence, String corpusName, boolean forTrain, Integer predictedClass) {\n\t\t \n\n//\t\tString hql = \"from MLExample where (predictedClass = 1 or predictedClass=2 ) and forTrain=\"+(forTrain?1:0)\n\t\tString hql = \"from MLExample where (predictedClass = \"+predictedClass+\" ) and forTrain=\"+(forTrain?1:0)\n\t\t\t\t\t+\n\t\t\t\t\" and corpusName = '\"+corpusName+\"' and relatedPhrase.startArtifact.parentArtifact = \"+p_sentence.getArtifactId();\n\n\t\tList<MLExample> example_objects = \n\t\t\t\tgetExamplesList(hql);\n\t \n\t return example_objects;\n\t}\n\t public static List<MLExample> getPhraseExamplesByCorpus(Artifact p_sentence, String corpusName, boolean forTrain) {\n\t\t \n\t\tString hql = \"from MLExample where forTrain=\"+(forTrain?1:0)\n\t\t\t\t\t+\n\t\t\t\t\" and corpusName = '\"+corpusName+\"' and relatedPhrase.startArtifact.parentArtifact = \"+p_sentence.getArtifactId();\n\n\t\tList<MLExample> example_objects = \n\t\t\t\tgetExamplesList(hql);\n\t \n\t return example_objects;\n\t}\n\n\tpublic void setExpectedReal(int expectedReal) {\n\t\tthis.expectedReal = expectedReal;\n\t}\n\n\tpublic int getExpectedReal() {\n\t\treturn expectedReal;\n\t}\n\n\tpublic void setExpectedClosure(int expectedClosure) {\n\t\tthis.expectedClosure = expectedClosure;\n\t}\n\n\tpublic int getExpectedClosure() {\n\t\treturn expectedClosure;\n\t}\n\n\tpublic void setExpectedIntegrated(int expectedIntegrated) {\n\t\tthis.expectedIntegrated = expectedIntegrated;\n\t}\n\n\tpublic int getExpectedIntegrated() {\n\t\treturn expectedIntegrated;\n\t}\n\n\tpublic static MLExample getInstanceForPhrase(Phrase relatedPhrase,\n\t\t\tString experimentgroup) {\n\t\tString hql = \"from MLExample where relatedPhrase = \"+\n\t\t\t\trelatedPhrase.getPhraseId() + \" and corpusName = '\"+\n\t\t\t\texperimentgroup+\"'\";\n\t\t\tList<MLExample> example_objects = \n\t\t\t\t\tgetExamplesList(hql);\n\t\t \n\t\t\tMLExample example_obj;\n\t\t if(example_objects.size()==0)\n\t\t {\n\t\t \texample_obj = new MLExample();\n\t\t \texample_obj.setCorpusName(experimentgroup);\n\t\t \texample_obj.setRelatedPhrase(relatedPhrase);\n\t\t \t\n\t\t \tif(Setting.SaveInGetInstance)\n\t\t\t \tsaveExample(example_obj);\n\t\t }else\n\t\t {\n\t\t \texample_obj = \n\t\t \t\t\texample_objects.get(0);\n\t\t }\n\t\t return example_obj;\n\t}\n\n\t@Transient\n\tpublic String getRelatedDrug() {\n\t\treturn relatedDrug;\n\t}\n\n\tpublic void setRelatedDrug(String relatedDrug) {\n\t\tthis.relatedDrug = relatedDrug;\n\t}\n//\t@OneToOne( cascade = {CascadeType.PERSIST, CascadeType.MERGE} , fetch=FetchType.LAZY )\n\t@OneToOne( cascade = {CascadeType.PERSIST, CascadeType.MERGE} )\n @JoinColumn(name=\"relatedPhrase\")\n\tpublic Phrase getRelatedPhrase() {\n\t\treturn relatedPhrase;\n\t}\n\tpublic void setRelatedPhrase(Phrase relatedPhrase) {\n\t\tthis.relatedPhrase = relatedPhrase;\n\t}\n}",
"@Entity\n@Table( name = \"MLExampleFeature\" )\npublic class MLExampleFeature {\n\tprivate Integer exampleFeatureId;\n\t\n\tprivate MLExample relatedExample;\n\t\n\tprivate FeatureValuePair featureValuePair;\n\t\n\tpublic MLExampleFeature()\n\t{\n\t\t\n\t}\n\t\n\tpublic void setExampleFeatureId(Integer _artifactFeatureId) {\n\t\tthis.exampleFeatureId = _artifactFeatureId;\n\t}\n\t@Id\n\t@GeneratedValue(generator=\"increment\")\n\t@GenericGenerator(name=\"increment\", strategy = \"increment\")\n\tpublic Integer getExampleFeatureId() {\n\t\treturn exampleFeatureId;\n\t}\n\t\n\t\n\tpublic void setRelatedExample(MLExample relatedExample) {\n\t\tthis.relatedExample = relatedExample;\n\t}\n\t@ManyToOne( cascade = {CascadeType.PERSIST, CascadeType.MERGE} )\n @JoinColumn(name=\"relatedExample\")\n\tpublic MLExample getRelatedExample() {\n\t\treturn relatedExample;\n\t}\n\t\n\t\n\tpublic void setFeatureValuePair(FeatureValuePair _featureValuePair) {\n\t\tfeatureValuePair = _featureValuePair;\n\t}\n\t@ManyToOne( cascade = {CascadeType.PERSIST, CascadeType.MERGE} )\n @JoinColumn(name=\"featureValuePair\")\n\tpublic FeatureValuePair getFeatureValuePair() {\n\t\treturn featureValuePair;\n\t}\n\n\tpublic static MLExampleFeature setFeatureExample(MLExample pExample,\n\t\t\tFeatureValuePair pNewFeature) {\n\t\treturn setFeatureExample(pExample, pNewFeature, false);\n\t}\n\tpublic static MLExampleFeature setFeatureExample(MLExample pExample,\n\t\t\tFeatureValuePair pNewFeature, boolean isDenseFeature) {\n\n//\t\tif(!isDenseFeature){\n\t\tif(pNewFeature.getFeatureValueAuxiliary()!=null)\n\t\t\t//is multi value\n\t\t\tdeleteExampleFeatures(pExample, pNewFeature.getFeatureName()\n\t\t\t\t\t,pNewFeature.getFeatureValue());\n\t\telse\n\t\t\tdeleteExampleFeatures(pExample, pNewFeature.getFeatureName());\n//\t\t}\n\t\t\n\t\tMLExampleFeature artifact_feature = new MLExampleFeature();\n\t\tartifact_feature.setFeatureValuePair(pNewFeature);\n\t\tartifact_feature.setRelatedExample(pExample);\n\t\t\n\t\t\n\t\tSession session = HibernateUtil.sessionFactory.openSession();\n\t\t\n\t\tHibernateUtil.save(artifact_feature, session);\n\t\t\n\t\tsession.clear();\n\t\tsession.close();\n\t\t\n\t\treturn artifact_feature;\n\t}\n\tprivate static void deleteExampleFeatures(MLExample pExample,\n\t\t\tString featureName, String featureValue) {\n\t\t\n\t\tSession session = HibernateUtil.sessionFactory.openSession();\n\t\tsession.beginTransaction();\n\t\tString hql = \"from MLExampleFeature af where af.relatedExample = \" +\n\t\t\t\tpExample.getExampleId()+\" AND \"+\n\t\t\t\t\"af.featureValuePair.featureName = :featureName\"+\n\t\t\t\t\" AND af.featureValuePair.featureValue = :featureValue\";\n\t\t\n\t\tList<MLExampleFeature> artifact_feature_list = \n\t\t\tsession.createQuery(hql).setParameter(\"featureValue\", featureValue)\n\t\t\t.setParameter(\"featureName\", featureName).list();\n\t\t\n\t\t\n\t\tfor(MLExampleFeature af : artifact_feature_list)\n\t\t\tsession.delete(af);\n\t\t\n\t\tsession.getTransaction().commit();\n\t\tsession.close();\n\t}\n\n\t/*\n\t * delete all attribute name for an specific artifact\n\t */\n\tpublic static void deleteExampleFeatures(MLExample pExample,\n\t\t\tString featureName) {\n\t\tString hql = \"from MLExampleFeature as af inner join fetch af.featureValuePair \" +\n\t\t\t\t\"where af.relatedExample = \" +\n\t\t\t\tpExample.getExampleId()+\" AND \"+\n\t\t\t\t\"af.featureValuePair.featureName = :featureName\";\n\t\t\n\t\tHashMap<String, Object> params = new HashMap<String, Object>();\n\t\tparams.put(\"featureName\", featureName);\n\t\tSession session = HibernateUtil.sessionFactory.openSession();\n\t\t\n\t\tList<MLExampleFeature> artifact_feature_list = \n\t\t\t(List<MLExampleFeature>) HibernateUtil.executeReader(hql, params,null, session);\n\t\t\n\t\tif(artifact_feature_list.size()>0)\n\t\t{\n\t\t\tString example_feature_ids = \"\";\n\t\t\tfor(MLExampleFeature af : artifact_feature_list)\n\t\t\t\texample_feature_ids=example_feature_ids.concat(af.getExampleFeatureId()+\",\");\n\t\t\texample_feature_ids = example_feature_ids.replaceAll(\",$\", \"\");\n\t\t\tHibernateUtil.executeNonReader(\"delete from MLExampleFeature where exampleFeatureId in (\"+\n\t\t\t\t\texample_feature_ids+\")\");\n\t\t}\n\t\t\n\t\tsession.close();\n\t}\n\n\t@Override public String toString()\n\t{\n\t\treturn \" Example = \"+relatedExample.toString()+\n\t\t\t\" / Feature = \"+\n\t\t\tfeatureValuePair.toString();\n\t}\n\t\n\t@Transient\n\tpublic static void truncateTable()\n\t{\n\t\tString hql = \"delete from MLExampleFeature\";\n\t\tHibernateUtil.executeNonReader(hql);\n\t}\n\n\tpublic static void setBulkFeaturesExample(MLExample exampleToProcess,\n\t\t\tList<FeatureValuePair> features, String featurePrefix) {\n//\t\tHibernateUtil.executeNonReader(\"delete from MLExampleFeature where relatedExample = \"+\n//\t\t\t\texampleToProcess.getExampleId()+\" and featureValuePair in ()\");\n\t\t\n\t\tHibernateUtil.startTransaction();;\n\t\tSession session = HibernateUtil.saverSession;\n\t\t\n\t\tfor (FeatureValuePair fvp : features)\n\t\t{\n\t\t\tMLExampleFeature artifact_feature = new MLExampleFeature();\n\t\t\tartifact_feature.setFeatureValuePair(fvp);\n\t\t\tartifact_feature.setRelatedExample(exampleToProcess);\n\t\t\tsession.save(artifact_feature);\n\t\t}\n\t\t\n\t\tHibernateUtil.endTransaction(); \n\t\t\n\t\t\n\t}\n\n}",
"public class HibernateUtil {\n\t//private static SessionFactory sessionFactory;\n\tprivate static ServiceRegistry serviceRegistry;\n\t// configures settings from hibernate.cfg.xml\n\tpublic static SessionFactory sessionFactory; \n\tpublic static Session loaderSession;\n\tpublic static Session saverSession;\n\tpublic static boolean changeDB=true;\n\tpublic static String db;\n\tpublic static String user;\n\tpublic static String pass;\n\t\n\tstatic{\n\t\t\n\t\tsessionFactory = configureSessionFactory();\n\t\tloaderSession = sessionFactory.openSession();\n\t\tsaverSession = sessionFactory.openSession();\n\t}\n\tstatic boolean inTransaction = false;\n\t\n\t\n\tprivate static SessionFactory configureSessionFactory() throws HibernateException {\n\t\tConfiguration configuration = new Configuration();\n\t configuration.configure();\n\t serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); \n\t sessionFactory = configuration.buildSessionFactory(serviceRegistry);\n\t \n\t return sessionFactory;\n\t}\n\n\tpublic static void changeConfigurationDatabase(String databaseURL, String user, String pass){\n\t \t \n\t Configuration configuration = new Configuration();\n\t\tconfiguration.configure();\n//\t\tserviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); \n//\t\tconfiguration.setProperty(\"hibernate.connection.url\", databaseURL);\n//\t\tconfiguration.setProperty(\"hibernate.connection.username\", user);\n//\t\tconfiguration.setProperty(\"hibernate.connection.password\", pass);\n//\t configuration.configure();\n\t\tconfiguration.setProperty(\"connection.url\", databaseURL);\n\t\tconfiguration.setProperty(\"hibernate.connection.url\", databaseURL);\n\t\tconfiguration.setProperty(\"hibernate.connection.username\", user);\n\t\tconfiguration.setProperty(\"hibernate.connection.password\", pass);\n\t\t\n\t\tconfiguration.getProperty(\"hibernate.connection.url\");\n\t serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); \n\t\t\n\t \n\t sessionFactory = configuration.buildSessionFactory(serviceRegistry);\n\t loaderSession = sessionFactory.openSession();\n\t\tsaverSession = sessionFactory.openSession();\n\t\tMLExample.hibernateSession=loaderSession;\n\t}\n\t/**\n\t * save object status\n\t */\n\tpublic static void save(Object _object, Session session) {\n\t\ttry {\n\t\t\tsession.beginTransaction();\n\t\t\tsession.saveOrUpdate(_object);\n\t\t\tsession.flush();\n\t\t\tsession.getTransaction().commit();\n\t\t} catch (HibernateException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\tpublic static void save(Object _object) {\n\t\tsave(_object, loaderSession);\n\t}\n\t\n\tpublic static List<?> executeReader(String hql)\n\t{\n\t\treturn executeReader(hql, null, null, loaderSession);\n\t}\n\t\n\tpublic static List<?> executeReader(String hql, HashMap<String, Object> params)\n\t{\n\t\treturn executeReader(hql, params, null, loaderSession);\n\t}\n\t\n\tpublic static List<?> executeReader(String hql, HashMap<String, Object> params, Integer limit)\n\t{\n\t\treturn executeReader(hql, params, limit, loaderSession);\n\t}\n\tpublic static List<?> executeReader(String hql, HashMap<String, Object> params, Integer limit, Session session)\n\t{\n\t\tQuery q = session.createQuery(hql);\n\t\t\n\t\tif(params!=null)\n\t\t\tfor(String key :params.keySet())\n\t\t\t{\n\t\t\t\tObject val = params.get(key);\n\t\t\t\tif(val instanceof String)\n\t\t\t\t\tq.setString(key, (String)val);\n\t\t\t\telse\n\t\t\t\t\tq.setInteger(key, (Integer)val);\n\t\t\t}\n\t\tif(limit!=null)\n\t\t\tq.setMaxResults(limit);\n\t\t\n\t\tList<?> result_list = \n\t\t\tq.list();\n\t\t\n\t\treturn result_list;\n\t}\n\t\n\t\n\t\n\tpublic static void executeNonReader(String hql, HashMap<String, Object> params)\n\t{\n\t\tif(!inTransaction)\n\t\t{\n//\t\t\tsession = sessionFactory.openSession();\n\t\t\tsaverSession = clearSession(saverSession);\n\t\t\tsaverSession.beginTransaction();\n\t\t}\n\t\t\n\t\tQuery qr = saverSession.createQuery(hql);\n\t\tif (params!=null)\n\t\tfor(String key :params.keySet())\n\t\t{\n\t\t\tObject val = params.get(key);\n\t\t\tqr.setParameter(key, val);\n\t\t}\n\t\t\n\t\tqr.executeUpdate();\n\t\t\n\t\tif(!inTransaction)\n\t\t{\n\t\t\tsaverSession.flush();\n\t\t\tsaverSession.getTransaction().commit();\n//\t\t\tsession.close();\n\t\t\t\n\t\t}\n\t}\n\t\n\t\n\tpublic static Object getHibernateTemplate() {\n\t\t// TODO Auto-generated method stub\n\t\treturn null;\n\t}\n\tpublic static void executeNonReader(String hql) {\n\t\texecuteNonReader(hql, null);\n\t\t\n\t}\n\tpublic static void startTransaction() {\n\t\tsaverSession = sessionFactory.openSession();\n\t\tsaverSession.beginTransaction();\n\t\tinTransaction = true;\n\t}\n\t\n\t\t \n\t\t\n\tpublic static void endTransaction() {\n\t\tsaverSession.flush();\n\t\tif(!saverSession.getTransaction().wasCommitted())\n\t\t\tsaverSession.getTransaction().commit();\n\t\tsaverSession.close();\n\t\tinTransaction = false;\n\t}\n\tpublic static void clearLoaderSession()\n\t{\n\t\tloaderSession = clearSession(loaderSession);\n\t}\n\tpublic static Session clearSession(Session session)\n\t{\n\t\tif(session!=null && session.isOpen()){\n\t\t\tsession.clear();\n\t\t\tsession.close();\n\t\t}\n\t\tsession= sessionFactory.openSession();\n\t\treturn session;\n\t}\n\t\n\t\n\tpublic static void flushTransaction() {\n\t\tsaverSession.flush();\n\t\tsaverSession.getTransaction().commit();\n\t\t\n\t}\n\tpublic static Object executeGetOneValue(String sql,\n\t\t\tHashMap<String, Object> params) {\n\t\tSession session = sessionFactory.openSession();\n\t\tQuery query = session.createSQLQuery(sql);\n\t\tif (params!=null)\n\t\t\tfor(String key :params.keySet())\n\t\t\t{\n\t\t\t\tObject val = params.get(key);\n\t\t\t\tquery.setParameter(key, val);\n\t\t\t}\n\t\tObject oneVal = query.uniqueResult();\n\t\tsession.clear();\n\t\tsession.close();\n\t\treturn oneVal;\n\t}\n}"
] | import java.util.List;
import edu.asu.diego.adrmine.utils.Negation;
import rainbownlp.core.Artifact;
import rainbownlp.core.FeatureValuePair;
import rainbownlp.core.FeatureValuePair.FeatureName;
import rainbownlp.machineLearning.IFeatureCalculator;
import rainbownlp.machineLearning.MLExample;
import rainbownlp.machineLearning.MLExampleFeature;
import rainbownlp.util.HibernateUtil; | /**
*
*/
package edu.asu.diego.adrmine.features;
/**
* @author Azadeh
*
*/
public class TokenClauseFeatures implements IFeatureCalculator {
public static void main (String[] args) throws Exception
{
// String experimentgroup = TokenSequenceExampleBuilder.ExperimentGroupADRConcepts;
String experimentgroup = args[0];
// List<MLExample> trainExamples =
// MLExample.getAllExamples(experimentgroup, true);
// int count=0;
//
// for (MLExample example:trainExamples)
// {
//
// TokenClauseFeatures lbf = new TokenClauseFeatures();
// lbf.calculateFeatures(example);
//// TokenDeepClusterFeatures cf = new TokenDeepClusterFeatures();
//// cf.calculateFeatures(example);
//
// count++;
//
// System.out.println("***train "+count+"/"+trainExamples.size());
//
// }
// HibernateUtil.clearLoaderSession();
//Test
int count=0;
List<MLExample> testExamples =
MLExample.getAllExamples(experimentgroup, false);
for (MLExample example:testExamples)
{
TokenClauseFeatures lbf = new TokenClauseFeatures();
lbf.calculateFeatures(example);
// TokenDeepClusterFeatures cf = new TokenDeepClusterFeatures();
// cf.calculateFeatures(example);
count++;
System.out.println("***test "+count+"/"+testExamples.size());
}
}
@Override
public void calculateFeatures(MLExample exampleToProcess) throws Exception {
//get related artifact
Artifact relatedArtifact = exampleToProcess.getRelatedArtifact();
// boolean is_negated_expanded = Negation.isWordNegatedExpanded(relatedArtifact, relatedArtifact.getParentArtifact());
boolean is_negated = Negation.isWordNegated(relatedArtifact, relatedArtifact.getParentArtifact());
// FeatureValuePair is_negated_exp_feature = FeatureValuePair.getInstance
// (FeatureName.isTokenNegatedExpanded, is_negated_expanded?"1":"0");
// MLExampleFeature.setFeatureExample(exampleToProcess, is_negated_exp_feature);
//////// | FeatureValuePair is_negated_feature = FeatureValuePair.getInstance | 2 |
mariok/pinemup | src/main/java/net/sourceforge/pinemup/ui/swing/tray/TrayMenu.java | [
"public final class CategoryManager {\n /** The pinboard, which contains all notes. **/\n private PinBoard pinBoard = new PinBoard();\n\n /** Listeners, which will be added per default to new notes. **/\n private final Collection<NoteChangedEventListener> defaultNoteChangedEventListeners = new LinkedList<>();\n\n /** Listeners, which will be added per default to new categories. **/\n private final Collection<CategoryChangedEventListener> defaultCategoryChangedEventlisteners = new LinkedList<>();\n private final Collection<NoteAddedEventListener> defaultNoteAddedEventListeners = new LinkedList<>();\n private final Collection<NoteRemovedEventListener> defaultNoteRemovedEventListeners = new LinkedList<>();\n\n /** Listeners, which will be added per default to new pinboards. **/\n private final Collection<CategoryAddedEventListener> defaultCategoryAddedEventListeners = new LinkedList<>();\n private final Collection<CategoryRemovedEventListener> defaultCategoryRemovedEventListeners = new LinkedList<>();\n\n private static class Holder {\n private static final CategoryManager INSTANCE = new CategoryManager();\n }\n\n public static CategoryManager getInstance() {\n return Holder.INSTANCE;\n }\n\n private CategoryManager() {\n super();\n }\n\n public void addCategory(Category c) {\n addDefaultCategoryEventListeners(c);\n pinBoard.addCategory(c);\n }\n\n public void removeCategory(Category c) {\n pinBoard.removeCategory(c);\n }\n\n public void removeNote(Note note) {\n findCategoryForNote(note).removeNote(note);\n }\n\n public void hideAllNotes() {\n for (Category cat : pinBoard.getCategories()) {\n cat.hideAllNotes();\n }\n }\n\n public void unhideAllNotes() {\n for (Category cat : pinBoard.getCategories()) {\n cat.unhideAllNotes();\n }\n }\n\n public String[] getCategoryNames() {\n int n = getNumberOfCategories();\n String[] s = new String[n];\n int ni = 0;\n for (Category cat : pinBoard.getCategories()) {\n s[ni] = cat.getName();\n ni++;\n }\n return s;\n }\n\n public int getNumberOfCategories() {\n return pinBoard.getCategories().size();\n }\n\n public Category getDefaultCategory() {\n for (Category cat : pinBoard.getCategories()) {\n if (cat.isDefaultCategory()) {\n return cat;\n }\n }\n return null;\n }\n\n public void setDefaultCategory(Category c) {\n c.setDefault(true);\n pinBoard.getCategories().stream().filter(cat -> cat != c).forEach(cat -> {\n cat.setDefault(false);\n });\n }\n\n public void showOnlyNotesOfCategory(Category c) {\n c.unhideAllNotes();\n for (Category cat : pinBoard.getCategories()) {\n if (cat != c) {\n cat.hideAllNotes();\n }\n }\n }\n\n public void moveCategoryUp(Category c) {\n pinBoard.moveCategoryUp(c);\n }\n\n public void moveCategoryDown(Category c) {\n pinBoard.moveCategoryDown(c);\n }\n\n public Category getCategoryByNumber(int n) {\n return pinBoard.getCategoryByNumber(n);\n }\n\n public List<Category> getCategories() {\n return pinBoard.getCategories();\n }\n\n public void replaceWithNewCategories(List<Category> newCategories) {\n hideAllNotes();\n\n for (Category category : newCategories) {\n addDefaultCategoryEventListeners(category);\n\n for (Note note : category.getNotes()) {\n addDefaultNoteEventListeners(note);\n }\n }\n\n pinBoard = new PinBoard();\n addDefaultPinBoardEventListeners(pinBoard);\n\n for (Category category : newCategories) {\n pinBoard.addCategory(category);\n }\n }\n\n public void moveNoteToCategory(Note note, int catNumber) {\n Category newCat = getCategoryByNumber(catNumber);\n if (newCat != null) {\n // remove from old category\n Category oldCat = findCategoryForNote(note);\n if (oldCat != null) {\n oldCat.removeNote(note);\n }\n // add to new category\n newCat.addNote(note);\n // set note color to default color of the new category\n note.setColor(newCat.getDefaultNoteColor());\n }\n }\n\n public Category findCategoryForNote(Note note) {\n Category categoryForNote = null;\n for (Category category : pinBoard.getCategories()) {\n if (category.containsNote(note)) {\n categoryForNote = category;\n break;\n }\n }\n return categoryForNote;\n }\n\n public Note createNoteAndAddToDefaultCategory() {\n Category defCat = getDefaultCategory();\n Note newNote = createNoteWithDefaultUserSettings();\n defCat.addNote(newNote);\n newNote.setColor(defCat.getDefaultNoteColor());\n addDefaultNoteEventListeners(newNote);\n\n return newNote;\n }\n\n private Note createNoteWithDefaultUserSettings() {\n UserSettings userSettings = UserSettings.getInstance();\n Note newNote = new Note();\n newNote.setSize(userSettings.getDefaultWindowWidth(), userSettings.getDefaultWindowHeight());\n newNote.setPosition(userSettings.getDefaultWindowXPostition(), userSettings.getDefaultWindowYPostition());\n newNote.setFontSize(userSettings.getDefaultFontSize());\n newNote.setAlwaysOnTop(userSettings.getDefaultAlwaysOnTop());\n return newNote;\n }\n\n private void addDefaultNoteEventListeners(Note note) {\n for (NoteChangedEventListener listener : defaultNoteChangedEventListeners) {\n note.addNoteChangedEventListener(listener);\n }\n }\n\n private void addDefaultCategoryEventListeners(Category category) {\n for (CategoryChangedEventListener listener : defaultCategoryChangedEventlisteners) {\n category.addCategoryChangedEventListener(listener);\n }\n for (NoteAddedEventListener listener : defaultNoteAddedEventListeners) {\n category.addNoteAddedEventListener(listener);\n }\n for (NoteRemovedEventListener listener : defaultNoteRemovedEventListeners) {\n category.addNoteRemovedEventListener(listener);\n }\n }\n\n private void addDefaultPinBoardEventListeners(PinBoard pinBoard) {\n for (CategoryAddedEventListener listener : defaultCategoryAddedEventListeners) {\n pinBoard.addCategoryAddedEventListener(listener);\n }\n for (CategoryRemovedEventListener listener : defaultCategoryRemovedEventListeners) {\n pinBoard.addCategoryRemovedEventListener(listener);\n }\n }\n\n public void registerDefaultNoteChangedEventListener(NoteChangedEventListener listener) {\n defaultNoteChangedEventListeners.add(listener);\n }\n\n public void registerDefaultNoteAddedEventListener(NoteAddedEventListener listener) {\n defaultNoteAddedEventListeners.add(listener);\n }\n\n public void registerDefaultNoteRemovedEventListener(NoteRemovedEventListener listener) {\n defaultNoteRemovedEventListeners.add(listener);\n }\n\n public void registerDefaultCategoryChangedEventListener(CategoryChangedEventListener listener) {\n defaultCategoryChangedEventlisteners.add(listener);\n }\n\n public void registerDefaultCategoryAddedEventListener(CategoryAddedEventListener listener) {\n defaultCategoryAddedEventListeners.add(listener);\n }\n\n public void registerDefaultCategoryRemovedEventListener(CategoryRemovedEventListener listener) {\n defaultCategoryRemovedEventListeners.add(listener);\n }\n}",
"public final class I18N {\n public enum SupportedLocale {\n de_DE(\"de\", \"DE\"),\n cs_CZ(\"cs\", \"CZ\"),\n en_US(\"en\", \"US\"),\n ru(\"ru\"),\n uk_UA(\"uk\", \"UA\");\n\n private final Locale locale;\n\n private SupportedLocale(String language) {\n locale = new Locale(language);\n }\n\n private SupportedLocale(String language, String country) {\n locale = new Locale(language, country);\n }\n\n public Locale getLocale() {\n return locale;\n }\n\n @Override\n public String toString() {\n return locale.getDisplayName();\n }\n\n public static SupportedLocale fromLocaleString(String localeString) {\n String[] localeParts = localeString.split(\"_\");\n String language = localeParts[0];\n String country = \"\";\n if (localeParts.length > 1) {\n country = localeParts[1];\n }\n\n SupportedLocale locale = FALLBACK_LOCALE;\n for (SupportedLocale l : SupportedLocale.values()) {\n if (language.equals(l.getLocale().getLanguage()) && country.equals(l.getLocale().getCountry())) {\n locale = l;\n break;\n }\n }\n return locale;\n }\n }\n\n private static final SupportedLocale FALLBACK_LOCALE = SupportedLocale.en_US;\n\n private static final Logger LOG = LoggerFactory.getLogger(I18N.class);\n\n private ResourceBundle res;\n\n private static class Holder {\n private static final I18N INSTANCE = new I18N();\n }\n\n public static I18N getInstance() {\n return Holder.INSTANCE;\n }\n\n public void setLocale(Locale locale) {\n res = ResourceBundle.getBundle(\"i18n.messages\", locale);\n Locale.setDefault(locale);\n }\n\n private I18N() {\n res = ResourceBundle.getBundle(\"i18n.messages\", FALLBACK_LOCALE.getLocale());\n }\n\n public String getString(String key) {\n String s;\n try {\n s = res.getString(key);\n } catch (MissingResourceException e) {\n s = key;\n LOG.error(\"The resource with the key '\" + key + \"' could not be found.\", e);\n }\n return s;\n }\n\n public String getString(String key, Object... args) {\n String message = getString(key).replace(\"'\", \"''\");\n return MessageFormat.format(message, args);\n }\n}",
"public class Category {\n private String name;\n private final Set<Note> notes;\n private boolean defaultCategory;\n private NoteColor defaultNoteColor;\n\n private final Collection<CategoryChangedEventListener> categoryChangedEventListeners = new LinkedList<>();\n private final Collection<NoteAddedEventListener> noteAddedEventListeners = new LinkedList<>();\n private final Collection<NoteRemovedEventListener> noteRemovedEventListeners = new LinkedList<>();\n\n public void addCategoryChangedEventListener(CategoryChangedEventListener listener) {\n categoryChangedEventListeners.add(listener);\n }\n\n public void removeCategoryChangedEventListener(CategoryChangedEventListener listener) {\n categoryChangedEventListeners.remove(listener);\n }\n\n public void addNoteAddedEventListener(NoteAddedEventListener listener) {\n noteAddedEventListeners.add(listener);\n }\n\n public void removeNoteAddedEventListener(NoteAddedEventListener listener) {\n noteAddedEventListeners.remove(listener);\n }\n\n public void addNoteRemovedEventListener(NoteRemovedEventListener listener) {\n noteRemovedEventListeners.add(listener);\n }\n\n public void removeNoteRemovedEventListener(NoteRemovedEventListener listener) {\n noteRemovedEventListeners.remove(listener);\n }\n\n public Category(String name, boolean def, NoteColor defNoteColor) {\n this.name = name;\n this.defaultCategory = def;\n this.defaultNoteColor = defNoteColor;\n notes = new HashSet<>();\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n if (!name.equals(this.name)) {\n this.name = name;\n fireCategoryChangedEvent();\n }\n }\n\n public boolean isDefaultCategory() {\n return defaultCategory;\n }\n\n public void setDefault(boolean b) {\n if (b != defaultCategory) {\n defaultCategory = b;\n fireCategoryChangedEvent();\n }\n }\n\n public void setDefaultNoteColor(NoteColor c) {\n if (!c.equals(defaultNoteColor)) {\n defaultNoteColor = c;\n fireCategoryChangedEvent();\n }\n }\n\n public NoteColor getDefaultNoteColor() {\n return defaultNoteColor;\n }\n\n public int getNumberOfNotes() {\n return notes.size();\n }\n\n public void hideAllNotes() {\n for (Note note : notes) {\n note.setHidden(true);\n }\n }\n\n public Set<Note> getNotes() {\n return notes;\n }\n\n public void addNote(Note n) {\n notes.add(n);\n fireNoteAddedEvent(n);\n }\n\n public void removeNote(Note n) {\n notes.remove(n);\n fireNoteRemovedEvent(n);\n }\n\n public void unhideAllNotes() {\n for (Note note : notes) {\n note.setHidden(false);\n }\n }\n\n public boolean containsNote(Note note) {\n return notes.contains(note);\n }\n\n public void fireCategoryChangedEvent() {\n for (CategoryChangedEventListener listener : categoryChangedEventListeners) {\n listener.categoryChanged(new CategoryChangedEvent(this));\n }\n }\n\n public void fireNoteAddedEvent(Note note) {\n for (NoteAddedEventListener listener : noteAddedEventListeners) {\n listener.noteAdded(new NoteAddedEvent(this, note));\n }\n }\n\n public void fireNoteRemovedEvent(Note note) {\n for (NoteRemovedEventListener listener : noteRemovedEventListeners) {\n listener.noteRemoved(new NoteRemovedEvent(this, note));\n }\n }\n}",
"public class CategoryMenuLogic implements ActionListener {\n public enum CategoryAction {\n HIDE_ALL_NOTES(\"menu.categorymenu.hidenotes\"),\n SHOW_ALL_NOTES(\"menu.categorymenu.shownotes\"),\n SHOW_ONLY_NOTES_OF_CATEGORY(\"menu.categorymenu.showonlynotes\"),\n SET_AS_DEFAULT_CATEGORY(\"menu.categorymenu.setasdefault\");\n\n private final String i18nKey;\n\n private CategoryAction(String i18nKey) {\n this.i18nKey = i18nKey;\n }\n\n public String getI18nKey() {\n return i18nKey;\n }\n }\n\n private final Category category;\n\n public CategoryMenuLogic(Category category) {\n this.category = category;\n }\n\n @Override\n public void actionPerformed(ActionEvent e) {\n CategoryAction action = CategoryAction.valueOf(e.getActionCommand());\n\n switch (action) {\n case HIDE_ALL_NOTES:\n category.hideAllNotes();\n break;\n case SHOW_ALL_NOTES:\n category.unhideAllNotes();\n break;\n case SHOW_ONLY_NOTES_OF_CATEGORY:\n CategoryManager.getInstance().showOnlyNotesOfCategory(category);\n break;\n case SET_AS_DEFAULT_CATEGORY:\n CategoryManager.getInstance().setDefaultCategory(category);\n break;\n default:\n break;\n }\n }\n}",
"public enum CategoryAction {\n HIDE_ALL_NOTES(\"menu.categorymenu.hidenotes\"),\n SHOW_ALL_NOTES(\"menu.categorymenu.shownotes\"),\n SHOW_ONLY_NOTES_OF_CATEGORY(\"menu.categorymenu.showonlynotes\"),\n SET_AS_DEFAULT_CATEGORY(\"menu.categorymenu.setasdefault\");\n\n private final String i18nKey;\n\n private CategoryAction(String i18nKey) {\n this.i18nKey = i18nKey;\n }\n\n public String getI18nKey() {\n return i18nKey;\n }\n}",
"public class GeneralMenuLogic implements ActionListener {\n public enum GeneralAction {\n ADD_NOTE(\"menu.addnoteitem\"),\n SHOW_ALL_NOTES(\"menu.showallnotesitem\"),\n HIDE_ALL_NOTES(\"menu.hideallnotesitem\");\n\n private final String i18nKey;\n\n private GeneralAction(String i18nKey) {\n this.i18nKey = i18nKey;\n }\n\n public String getI18nKey() {\n return i18nKey;\n }\n }\n\n @Override\n public void actionPerformed(ActionEvent e) {\n GeneralAction action = GeneralAction.valueOf(e.getActionCommand());\n\n switch (action) {\n case ADD_NOTE:\n CategoryManager.getInstance().createNoteAndAddToDefaultCategory();\n break;\n case SHOW_ALL_NOTES:\n CategoryManager.getInstance().unhideAllNotes();\n break;\n case HIDE_ALL_NOTES:\n CategoryManager.getInstance().hideAllNotes();\n break;\n default:\n break;\n }\n }\n}",
"public enum GeneralAction {\n ADD_NOTE(\"menu.addnoteitem\"),\n SHOW_ALL_NOTES(\"menu.showallnotesitem\"),\n HIDE_ALL_NOTES(\"menu.hideallnotesitem\");\n\n private final String i18nKey;\n\n private GeneralAction(String i18nKey) {\n this.i18nKey = i18nKey;\n }\n\n public String getI18nKey() {\n return i18nKey;\n }\n}"
] | import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.util.ArrayList;
import java.util.List;
import net.sourceforge.pinemup.core.CategoryManager;
import net.sourceforge.pinemup.core.i18n.I18N;
import net.sourceforge.pinemup.core.model.Category;
import net.sourceforge.pinemup.ui.swing.menus.logic.CategoryMenuLogic;
import net.sourceforge.pinemup.ui.swing.menus.logic.CategoryMenuLogic.CategoryAction;
import net.sourceforge.pinemup.ui.swing.menus.logic.GeneralMenuLogic;
import net.sourceforge.pinemup.ui.swing.menus.logic.GeneralMenuLogic.GeneralAction;
import java.awt.Menu; | /*
* pin 'em up
*
* Copyright (C) 2007-2013 by Mario Ködding
*
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package net.sourceforge.pinemup.ui.swing.tray;
public class TrayMenu extends PopupMenu {
private static final long serialVersionUID = 4859510599893727949L;
private Menu categoriesMenu;
private MenuItem manageCategoriesItem;
private final TrayMenuLogic trayMenuLogic;
public TrayMenu(TrayMenuLogic trayMenuLogic) {
super("pin 'em up");
this.trayMenuLogic = trayMenuLogic;
initWithNewLanguage();
}
public final void initWithNewLanguage() {
removeAll();
// add basic items
for (MenuItem item : getBasicMenuItems()) {
add(item);
}
addSeparator();
// categories menus
categoriesMenu = new Menu(I18N.getInstance().getString("menu.categorymenu"));
add(categoriesMenu);
// category actions
manageCategoriesItem = new MenuItem(I18N.getInstance().getString("menu.categorymenu.managecategoriesitem"));
manageCategoriesItem.setActionCommand(TrayMenuLogic.ACTION_MANAGE_CATEGORIES);
manageCategoriesItem.addActionListener(trayMenuLogic);
createCategoriesMenu();
// im-/export menu
addSeparator();
Menu imExMenu = new Menu(I18N.getInstance().getString("menu.notesimexport"));
MenuItem serverUploadItem = new MenuItem(I18N.getInstance().getString("menu.notesimexport.serveruploaditem"));
serverUploadItem.setActionCommand(TrayMenuLogic.ACTION_UPLOAD_TO_SERVER);
serverUploadItem.addActionListener(trayMenuLogic);
imExMenu.add(serverUploadItem);
MenuItem serverDownloadItem = new MenuItem(I18N.getInstance().getString("menu.notesimexport.serverdownloaditem"));
serverDownloadItem.setActionCommand(TrayMenuLogic.ACTION_DOWNLOAD_FROM_SERVER);
serverDownloadItem.addActionListener(trayMenuLogic);
imExMenu.add(serverDownloadItem);
imExMenu.addSeparator();
MenuItem exportItem = new MenuItem(I18N.getInstance().getString("menu.notesimexport.textexportitem"));
exportItem.setActionCommand(TrayMenuLogic.ACTION_EXPORT);
exportItem.addActionListener(trayMenuLogic);
imExMenu.add(exportItem);
add(imExMenu);
// other items
addSeparator();
MenuItem showSettingsDialogItem = new MenuItem(I18N.getInstance().getString("menu.settingsitem"));
showSettingsDialogItem.setActionCommand(TrayMenuLogic.ACTION_SHOW_SETTINGS_DIALOG);
showSettingsDialogItem.addActionListener(trayMenuLogic);
add(showSettingsDialogItem);
// help menu
Menu helpMenu = new Menu(I18N.getInstance().getString("menu.help"));
MenuItem updateItem = new MenuItem(I18N.getInstance().getString("menu.help.updatecheckitem"));
updateItem.setActionCommand(TrayMenuLogic.ACTION_CHECK_FOR_UPDATES);
updateItem.addActionListener(trayMenuLogic);
helpMenu.add(updateItem);
helpMenu.addSeparator();
MenuItem aboutItem = new MenuItem(I18N.getInstance().getString("menu.help.aboutitem"));
aboutItem.setActionCommand(TrayMenuLogic.ACTION_SHOW_ABOUT_DIALOG);
aboutItem.addActionListener(trayMenuLogic);
helpMenu.add(aboutItem);
add(helpMenu);
addSeparator();
// close item
MenuItem closeItem = new MenuItem(I18N.getInstance().getString("menu.exititem"));
closeItem.setActionCommand(TrayMenuLogic.ACTION_EXIT_APPLICATION);
closeItem.addActionListener(trayMenuLogic);
add(closeItem);
}
public void createCategoriesMenu() {
categoriesMenu.removeAll();
for (Menu m : getCategoryMenus()) {
categoriesMenu.add(m);
}
categoriesMenu.addSeparator();
categoriesMenu.add(manageCategoriesItem);
}
private List<Menu> getCategoryMenus() {
List<Menu> categoryMenus = new ArrayList<>(); | for (Category cat : CategoryManager.getInstance().getCategories()) { | 2 |
synapticloop/routemaster | src/main/java/synapticloop/nanohttpd/servant/StaticFileServant.java | [
"public abstract class Handler {\n\t/**\n\t * Return whether this handler can serve the requested URI\n\t * \n\t * @param uri the URI to check\n\t * \n\t * @return whether this handler can serve the requested URI\n\t */\n\tpublic abstract boolean canServeUri(String uri);\n\t\n\t/**\n\t * If the handler can serve this URI, then it will be requested to serve up \n\t * the content\n\t * \n\t * @param rootDir The root directory where the routemaster was started from\n\t * @param uri The URI that is requested to be served\n\t * @param headers The headers that are passed through\n\t * @param session The session object\n\t * \n\t * @return The response that will be sent back to the clien\n\t */\n\tpublic abstract Response serveFile(File rootDir, String uri, Map<String, String> headers, IHTTPSession session);\n\n\t/**\n\t * Get the name of the handler\n\t * \n\t * @return the name of the handler (by default the canonical name of this class)\n\t */\n\tpublic String getName() {\n\t\treturn(this.getClass().getCanonicalName());\n\t}\n\n\t/**\n\t * Get the mimetype for the handler file. This will return the mimetype from \n\t * the file that is requested, by using the fileName.mimeType.handlerExtension.\n\t * \n\t * For example - index.html.templar will look up the mime type mappings for \n\t * 'html', and return the mimetype (if one exists). Else it will return null\n\t * \n\t * @param uri the URI to lookup\n\t * \n\t * @return the mime type if found in the lookup table, else null\n\t */\n\tprotected String getMimeType(String uri) {\n\t\tString[] split = uri.split(\"\\\\.\");\n\t\tint length = split.length;\n\n\t\tif(length > 2) {\n\t\t\t// the last one is .templar\n\t\t\t// the second last one is the mime type we need to lookup\n\t\t\treturn(MimeTypeMapper.getMimeTypes().get(split[length -2]));\n\t\t}\n\t\treturn(null);\n\t}\n\n}",
"public abstract class Routable {\n\t// the route that this routable is bound to\n\tprotected String routeContext = null;\n\t// the map of option key values\n\tprotected Map<String, String> options = new HashMap<String, String>();\n\n\t/**\n\t * Create a new routable class with the bound routing context\n\t *\n\t * @param routeContext the context to route to\n\t */\n\tpublic Routable(String routeContext) {\n\t\tthis.routeContext = routeContext;\n\t}\n\n\t/**\n\t * Serve the correctly routed file\n\t *\n\t * @param rootDir The root directory of the RouteMaster server\n\t * @param httpSession The session\n\t *\n\t * @return The response\n\t */\n\tpublic abstract Response serve(File rootDir, IHTTPSession httpSession);\n\t\n\t/**\n\t * Set an option for this routable into the options map.\n\t * \n\t * @param key The option key\n\t * @param value the value\n\t */\n\tpublic void setOption(String key, String value) {\n\t\toptions.put(key, value);\n\t}\n\n\t/**\n\t * Get an option from the map, or null if it does not exist\n\t * \n\t * @param key the key to search for\n\t * \n\t * @return the value of the option, or null if it doesn't exist\n\t */\n\tpublic String getOption(String key) {\n\t\treturn(options.get(key));\n\t}\n}",
"public class RouteMaster {\n\tprivate static final String ROUTEMASTER_PROPERTIES = \"routemaster.properties\";\n\tprivate static final String ROUTEMASTER_JSON = \"routemaster.json\";\n\tprivate static final String ROUTEMASTER_EXAMPLE_PROPERTIES = \"routemaster.example.properties\";\n\tprivate static final String ROUTEMASTER_EXAMPLE_JSON = \"routemaster.example.json\";\n\n\tprivate static final String PROPERTY_PREFIX_REST = \"rest.\";\n\tprivate static final String PROPERTY_PREFIX_ROUTE = \"route.\";\n\tprivate static final String PROPERTY_PREFIX_HANDLER = \"handler.\";\n\n\tprivate static Router router = null;\n\n\tprivate static Set<String> indexFiles = new HashSet<String>();\n\tprivate static Map<Integer, String> errorPageCache = new ConcurrentHashMap<Integer, String>();\n\tprivate static Map<String, Routable> routerCache = new ConcurrentHashMap<String, Routable>();\n\tprivate static Map<String, Handler> handlerCache = new ConcurrentHashMap<String, Handler>();\n\tprivate static Set<String> modules = new HashSet<String>();\n\n\tprivate static boolean initialised = false;\n\tprivate static File rootDir;\n\n\tprivate RouteMaster() {}\n\n\t/**\n\t * Initialise the RouteMaster by attempting to look for the routemaster.properties\n\t * in the classpath and on the file system.\n\t * \n\t * @param rootDir the root directory from which content should be sourced\n\t */\n\tpublic static void initialise(File rootDir) {\n\t\tRouteMaster.rootDir = rootDir;\n\n\t\tProperties properties = null;\n\t\tboolean allOk = true;\n\n\t\ttry {\n\t\t\tproperties = FileHelper.confirmPropertiesFileDefault(ROUTEMASTER_PROPERTIES, ROUTEMASTER_EXAMPLE_PROPERTIES);\n\t\t} catch (IOException ioex) {\n\t\t\ttry {\n\t\t\t\tlogNoRoutemasterProperties();\n\t\t\t} catch (IOException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t\tallOk = false;\n\t\t}\n\n\t\tif(null == properties) {\n\t\t\ttry {\n\t\t\t\tlogNoRoutemasterProperties();\n\t\t\t} catch (IOException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t\tallOk = false;\n\t\t}\n\n\t\tif(allOk) {\n\t\t\t// at this point we want to load any modules that we find, and at them to the \n\t\t\t// properties file\n\t\t\tloadModules(properties);\n\n\t\t\tparseOptionsAndRoutes(properties);\n\t\t\tinitialised = true;\n\t\t} else {\n\t\t\tStringTokenizer stringTokenizer = new StringTokenizer(\"/*\", \"/\", false);\n\t\t\trouter = new Router(\"/*\", stringTokenizer, UninitialisedServant.class.getCanonicalName());\n\t\t}\n\t}\n\n\t/**\n\t * Dynamically load any modules that exist within the 'modules' directory\n\t * \n\t * @param properties the properties from the default routemaster.properties\n\t */\n\tprivate static void loadModules(Properties properties) {\n\t\t// look in the modules directory\n\t\tFile modulesDirectory = new File(rootDir.getAbsolutePath() + \"/modules/\");\n\t\tif(modulesDirectory.exists() && modulesDirectory.isDirectory() && modulesDirectory.canRead()) {\n\t\t\tString[] moduleList = modulesDirectory.list(new FilenameFilter() {\n\n\t\t\t\t@Override\n\t\t\t\tpublic boolean accept(File dir, String name) {\n\t\t\t\t\treturn(name.endsWith(\".jar\"));\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tint length = moduleList.length;\n\n\t\t\tif(length == 0) {\n\t\t\t\tlogInfo(\"No modules found, continuing...\");\n\t\t\t} else {\n\t\t\t\tlogInfo(\"Scanning '\" + length + \"' jar files for modules\");\n\t\t\t\tURLClassLoader classLoader = (URLClassLoader)ClassLoader.getSystemClassLoader();\n\t\t\t\tMethod method = null;\n\t\t\t\ttry {\n\t\t\t\t\tmethod = URLClassLoader.class.getDeclaredMethod(\"addURL\", URL.class);\n\t\t\t\t} catch (Exception ex) {\n\t\t\t\t\tlogFatal(\"Could not load any modules, exception message was: \" + ex.getMessage());\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tmethod.setAccessible(true);\n\t\t\t\tfor (String module : moduleList) {\n\t\t\t\t\tlogInfo(\"Found potential module in file '\" + module + \"'.\");\n\n\t\t\t\t\tFile file = new File(rootDir + \"/modules/\" + module);\n\n\t\t\t\t\t// try and find the <module>-<version>.jar.properties file which will\n\t\t\t\t\t// over-ride the routemaster.properties entry in the jar file\n\n\t\t\t\t\tboolean loadedOverrideProperties = false;\n\n\t\t\t\t\tString moduleName = getModuleName(module);\n\t\t\t\t\tFile overridePropertiesFile = new File(rootDir + \"/modules/\" + moduleName + \".properties\");\n\t\t\t\t\tif(overridePropertiesFile.exists() && overridePropertiesFile.canRead()) {\n\t\t\t\t\t\tlogInfo(\"[ \" + module + \" ] Found an over-ride .properties file '\" + moduleName + \".properties'.\");\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tProperties mergeProperties = new Properties();\n\t\t\t\t\t\t\tmergeProperties.load(new FileReader(overridePropertiesFile));\n\t\t\t\t\t\t\tIterator<Object> iterator = mergeProperties.keySet().iterator();\n\t\t\t\t\t\t\twhile (iterator.hasNext()) {\n\t\t\t\t\t\t\t\tString key = (String) iterator.next();\n\t\t\t\t\t\t\t\tif(properties.containsKey(key)) {\n\t\t\t\t\t\t\t\t\tlogWarn(\"[ \" + module + \" ] Routemaster already has a property with key '\" + key + \"', over-writing...\");\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tString value = mergeProperties.getProperty(key);\n\t\t\t\t\t\t\t\tproperties.setProperty(key, value);\n\n\t\t\t\t\t\t\t\tlogInfo(\"[ \" + module + \" ] Adding property key '\" + key + \"', value '\" + value + \"'\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tloadedOverrideProperties = true;\n\t\t\t\t\t\t} catch (IOException ex) {\n\t\t\t\t\t\t\tlogFatal(\"Could not load modules message was: \" + ex.getMessage());\n\t\t\t\t\t\t}\n\t\t\t\t\t} \n\n\t\t\t\t\ttry {\n\t\t\t\t\t\t\tJarFile jarFile = new JarFile(file);\n\t\t\t\t\t\t\tZipEntry zipEntry = jarFile.getEntry(moduleName + \".properties\");\n\t\t\t\t\t\t\tif(null != zipEntry) {\n\t\t\t\t\t\t\t\tURL url = file.toURI().toURL();\n\t\t\t\t\t\t\t\tmethod.invoke(classLoader, url);\n\n\t\t\t\t\t\t\t\tif(!loadedOverrideProperties) { \n\t\t\t\t\t\t\t\t\t// assuming that the above works - read the properties from the \n\t\t\t\t\t\t\t\t\t// jar file\n\t\t\t\t\t\t\t\t\treadProperties(module, properties, jarFile, zipEntry);\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tif(!modules.contains(module)) {\n\t\t\t\t\t\t\t\t\tmodules.add(module);\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tlogWarn(\"[ \" + module + \" ] Could not find '/\" + moduleName + \".properties' in file '\" + module + \"'.\");\n\t\t\t\t\t\t\t}\n\t\n\t\t\t\t\t\t\tjarFile.close();\n\t\t\t\t\t\t} catch (Exception ex) {\n\t\t\t\t\t\t\tlogFatal(\"Could not load modules message was: \" + ex.getMessage());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate static void readProperties(String module, Properties properties, JarFile jarFile, ZipEntry zipEntry) throws IOException {\n\t\tInputStream input = jarFile.getInputStream(zipEntry);\n\t\tInputStreamReader isr = new InputStreamReader(input);\n\t\tBufferedReader reader = new BufferedReader(isr);\n\t\tString line;\n\t\twhile ((line = reader.readLine()) != null) {\n\t\t\tString trimmed = line.trim();\n\n\t\t\tif(trimmed.length() != 0) {\n\t\t\t\tif(trimmed.startsWith(\"#\")) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tString[] split = line.split(\"=\", 2);\n\t\t\t\tif(split.length == 2) {\n\t\t\t\t\tString key = split[0].trim();\n\t\t\t\t\tString value = split[1].trim();\n\t\t\t\t\tif(properties.containsKey(key)) {\n\t\t\t\t\t\tlogWarn(\"[ \" + module + \" ] Routemaster already has a property with key '\" + key + \"', over-writing...\");\n\t\t\t\t\t}\n\n\t\t\t\t\tproperties.setProperty(key, value);\n\t\t\t\t\tlogInfo(\"[ \" + module + \" ] Adding property key '\" + key + \"', value '\" + value + \"'\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treader.close();\n\t}\n\n\tprivate static String getModuleName(String module) {\n\t\tPattern r = Pattern.compile(\"(.*)-\\\\d+\\\\.\\\\d+.*\\\\.jar\");\n\t\tMatcher m = r.matcher(module);\n\t\tif(m.matches()) {\n\t\t\treturn(m.group(1));\n\t\t}\n\n\t\tint lastIndexOf = module.lastIndexOf(\".\");\n\t\treturn(module.substring(0, lastIndexOf));\n\t}\n\n\tprivate static void parseOptionsAndRoutes(Properties properties) {\n\t\t// now parse the properties\n\t\tparseOptions(properties);\n\t\tEnumeration<Object> keys = properties.keys();\n\n\t\twhile (keys.hasMoreElements()) {\n\t\t\tString key = (String) keys.nextElement();\n\t\t\tString routerClass = (String)properties.get(key);\n\t\t\tif(key.startsWith(PROPERTY_PREFIX_ROUTE)) {\n\t\t\t\t// time to bind a route\n\t\t\t\tString subKey = key.substring(PROPERTY_PREFIX_ROUTE.length());\n\t\t\t\tStringTokenizer stringTokenizer = new StringTokenizer(subKey, \"/\", false);\n\t\t\t\tif(null == router) {\n\t\t\t\t\trouter = new Router(subKey, stringTokenizer, routerClass);\n\t\t\t\t} else {\n\t\t\t\t\trouter.addRoute(subKey, stringTokenizer, routerClass);\n\t\t\t\t}\n\t\t\t} else if(key.startsWith(PROPERTY_PREFIX_REST)) {\n\t\t\t\t// time to bind a rest route\n\t\t\t\tString subKey = key.substring(PROPERTY_PREFIX_REST.length());\n\t\t\t\t// now we need to get the parameters\n\t\t\t\tString[] splits = subKey.split(\"/\");\n\t\t\t\tStringBuilder stringBuilder = new StringBuilder();\n\n\t\t\t\tList<String> params = new ArrayList<String>();\n\t\t\t\tif(subKey.startsWith(\"/\")) { stringBuilder.append(\"/\"); }\n\n\t\t\t\tfor (int i = 0; i < splits.length; i++) {\n\t\t\t\t\tString split = splits[i];\n\t\t\t\t\tif(split.length() == 0) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tif(split.startsWith(\"%\") && split.endsWith(\"%\")) {\n\t\t\t\t\t\t// have a parameter\n\t\t\t\t\t\tparams.add(split.substring(1, split.length() -1));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tstringBuilder.append(split);\n\t\t\t\t\t\t// keep adding a slash for those that are missing - but not\n\t\t\t\t\t\t// if it the last\n\t\t\t\t\t\tif(i != splits.length -1) { stringBuilder.append(\"/\"); }\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// now clean up the route\n\t\t\t\tString temp = stringBuilder.toString();\n\t\t\t\tif(!temp.endsWith(\"/\")) { stringBuilder.append(\"/\"); }\n\t\t\t\t// need to make sure that the rest router always picks up wildcards\n\t\t\t\tif(!subKey.endsWith(\"*\")) { stringBuilder.append(\"*\"); }\n\n\t\t\t\tsubKey = stringBuilder.toString();\n\t\t\t\tStringTokenizer stringTokenizer = new StringTokenizer(subKey, \"/\", false);\n\t\t\t\tif(null == router) {\n\t\t\t\t\trouter = new Router(subKey, stringTokenizer, routerClass, params);\n\t\t\t\t} else {\n\t\t\t\t\trouter.addRestRoute(subKey, stringTokenizer, routerClass, params);\n\t\t\t\t}\n\n\t\t\t} else if(key.startsWith(PROPERTY_PREFIX_HANDLER)) {\n\t\t\t\t// we are going to add in a plugin\n\t\t\t\tString subKey = key.substring(PROPERTY_PREFIX_HANDLER.length());\n\t\t\t\tString pluginProperty = properties.getProperty(key);\n\n\t\t\t\ttry {\n\t\t\t\t\tObject pluginClass = Class.forName(pluginProperty).newInstance();\n\t\t\t\t\tif(pluginClass instanceof Handler) {\n\t\t\t\t\t\thandlerCache.put(subKey, (Handler)pluginClass);\n\t\t\t\t\t\tlogInfo(\"Handler '\" + pluginClass + \"', registered for '*.\" + subKey + \"'.\");\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlogFatal(\"Plugin class '\" + pluginProperty + \"' is not of instance Plugin.\");\n\t\t\t\t\t}\n\t\t\t\t} catch (ClassNotFoundException cnfex) {\n\t\t\t\t\tlogFatal(\"Could not find the class for '\" + pluginProperty + \"'.\", cnfex);\n\t\t\t\t} catch (InstantiationException iex) {\n\t\t\t\t\tlogFatal(\"Could not instantiate the class for '\" + pluginProperty + \"'.\", iex);\n\t\t\t\t} catch (IllegalAccessException iaex) {\n\t\t\t\t\tlogFatal(\"Illegal acces for class '\" + pluginProperty + \"'.\", iaex);\n\t\t\t\t}\n\n\t\t\t} else {\n\t\t\t\tlogWarn(\"Unknown property prefix for key '\" + key + \"'.\");\n\t\t\t}\n\t\t}\n\n\t\tif(null != router) {\n\t\t\tlogTable(router.getRouters(), \"registered routes\", \"route\", \"routable class\");\n\t\t}\n\n\t\tlogTable(new ArrayList<String>(modules), \"loaded modules\");\n\n\t\tif(indexFiles.isEmpty()) {\n\t\t\t// default welcomeFiles\n\t\t\tindexFiles.add(\"index.html\");\n\t\t\tindexFiles.add(\"index.htm\");\n\t\t}\n\n\t\tlogTable(new ArrayList<String>(indexFiles), \"index files\");\n\n\t\tlogTable(errorPageCache, \"error pages\", \"status\", \"page\");\n\n\t\tlogTable(handlerCache, \"Handlers\", \"extension\", \"handler class\");\n\n\t\tMimeTypeMapper.logMimeTypes();\n\n\t\tlogInfo(RouteMaster.class.getSimpleName() + \" initialised.\");\n\t}\n\n\tprivate static void logNoRoutemasterProperties() throws IOException {\n//\t\tlogFatal(\"Could not load the '\" + ROUTEMASTER_JSON + \"' file, ignoring...\");\n//\t\tlogFatal(\"(Consequently this is going to be a pretty boring experience!\");\n//\t\tlogFatal(\"but we did write out an example file for you - '\" + ROUTEMASTER_EXAMPLE_JSON + \"')\");\n//\t\tlogFatal(\"NOTE: the '\" + ROUTEMASTER_EXAMPLE_JSON + \"' takes precedence)\");\n//\t\tInputStream inputStream = RouteMaster.class.getResourceAsStream(\"/\" + ROUTEMASTER_EXAMPLE_JSON);\n//\n//\t\tFileHelper.writeFile(new File(ROUTEMASTER_EXAMPLE_JSON), inputStream, true);\n//\t\tinputStream.close();\n\n\t\tlogFatal(\"Could not load the '\" + ROUTEMASTER_PROPERTIES + \"' file, ignoring...\");\n\t\tlogFatal(\"(Consequently this is going to be a pretty boring experience!\");\n\t\tlogFatal(\"but we did write out an example file for you - '\" + ROUTEMASTER_EXAMPLE_PROPERTIES + \"')\");\n\n\t\tInputStream inputStream = RouteMaster.class.getResourceAsStream(\"/\" + ROUTEMASTER_EXAMPLE_PROPERTIES);\n\t\tFileHelper.writeFile(new File(ROUTEMASTER_EXAMPLE_PROPERTIES), inputStream, true);\n\t\tinputStream.close();\n\n\t}\n\n\t/**\n\t * Parse the options file\n\t *\n\t * @param properties The properties object\n\t * @param key the option key we are looking at\n\t */\n\tprivate static void parseOption(Properties properties, String key) {\n\t\tif(\"option.indexfiles\".equals(key)) {\n\t\t\tString property = properties.getProperty(key);\n\t\t\tString[] splits = property.split(\",\");\n\t\t\tfor (int i = 0; i < splits.length; i++) {\n\t\t\t\tString split = splits[i].trim();\n\t\t\t\tindexFiles.add(split);\n\t\t\t}\n\t\t} else if(key.startsWith(\"option.error.\")) {\n\t\t\tString subKey = key.substring(\"option.error.\".length());\n\t\t\ttry {\n\t\t\t\tint parseInt = Integer.parseInt(subKey);\n\t\t\t\terrorPageCache.put(parseInt, properties.getProperty(key));\n\t\t\t} catch(NumberFormatException nfex) {\n\t\t\t\tlogFatal(\"Could not parse error key '\" + subKey + \"'.\", nfex);\n\t\t\t}\n\t\t} else if(\"option.log\".equals(key)) {\n\t\t\t//\t\t\tlogRequests = properties.getProperty(\"option.log\").equalsIgnoreCase(\"true\");\n\t\t}\n\t}\n\n\tprivate static void parseOptions(Properties properties) {\n\t\tEnumeration<Object> keys = properties.keys();\n\n\t\twhile (keys.hasMoreElements()) {\n\t\t\tString key = (String) keys.nextElement();\n\t\t\tif(key.startsWith(\"option.\")) {\n\t\t\t\tparseOption(properties, key);\n\t\t\t\tproperties.remove(key);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Serve the correctly routed file\n\t *\n\t * @param rootDir The root directory of the RouteMaster server\n\t * @param httpSession The session\n\t *\n\t * @return The response\n\t */\n\tpublic static Response route(File rootDir, IHTTPSession httpSession) {\n\t\tif(!initialised) {\n\t\t\tHttpUtils.notFoundResponse();\n\t\t}\n\n\t\tResponse routeInternalResponse = routeInternal(rootDir, httpSession);\n\t\tif(null != routeInternalResponse) {\n\t\t\treturn(routeInternalResponse);\n\t\t}\n\n\t\treturn(get500Response(rootDir, httpSession));\n\t}\n\n\tprivate static Response routeInternal(File rootDir, IHTTPSession httpSession) {\n\t\tif(null != router) {\n\t\t\t// try and find the route\n\t\t\tString uri = httpSession.getUri();\n\n\t\t\t// do we have a cached version of this?\n\t\t\tif(routerCache.containsKey(uri)) {\n\t\t\t\tResponse serve = routerCache.get(uri).serve(rootDir, httpSession);\n\t\t\t\tif(serve == null) {\n\t\t\t\t\treturn(get404Response(rootDir, httpSession));\n\t\t\t\t} else {\n\t\t\t\t\treturn(serve);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tStringTokenizer stringTokenizer = new StringTokenizer(uri, \"/\", false);\n\t\t\t\tRoutable routable = router.route(httpSession, stringTokenizer);\n\t\t\t\tif(null != routable) {\n\t\t\t\t\trouterCache.put(uri, routable);\n\t\t\t\t\tResponse serve = routable.serve(rootDir, httpSession);\n\t\t\t\t\tif(null != serve) {\n\t\t\t\t\t\treturn(serve);\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn(get404Response(rootDir, httpSession));\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// have a null route-able return 404 perhaps\n\t\t\t\t\treturn(get404Response(rootDir, httpSession));\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\treturn(get404Response(rootDir, httpSession));\n\t\t}\n\t}\n\n\tprivate static Response getErrorResponse(File rootDir, IHTTPSession httpSession, Status status, String message) {\n\t\tint requestStatus = status.getRequestStatus();\n\t\tString uri = errorPageCache.get(requestStatus);\n\t\tif(errorPageCache.containsKey(requestStatus)) {\n\t\t\tModifiableSession modifiedSession = new ModifiableSession(httpSession);\n\t\t\tmodifiedSession.setUri(uri);\n\t\t\t// if not valid - we have already tried this - and we are going to get a\n\t\t\t// stack overflow, so just drop through\n\t\t\tif(modifiedSession.isValidRequest()) {\n\t\t\t\tResponse response = route(rootDir, modifiedSession);\n\t\t\t\tresponse.setStatus(status);\n\t\t\t\tif(null != response) {\n\t\t\t\t\treturn(response);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn(HttpUtils.notFoundResponse(AsciiArt.ROUTEMASTER + \n\t\t\t\t\" \" + \n\t\t\t\tmessage + \n\t\t\t\t\";\\n\\n additionally, an over-ride \" + \n\t\t\t\tstatus.toString() + \n\t\t\t\t\" error page was not defined\\n\\n in the configuration file, key 'option.error.404'.\"));\n\t}\n\n\tpublic static Response get404Response(File rootDir, IHTTPSession httpSession) { return(getErrorResponse(rootDir, httpSession, Response.Status.NOT_FOUND, \"not found\")); }\n\tpublic static Response get500Response(File rootDir, IHTTPSession httpSession) { return(getErrorResponse(rootDir, httpSession, Response.Status.INTERNAL_ERROR, \"internal server error\")); }\n\n\t/**\n\t * Get the root Router\n\t *\n\t * @return The Router assigned to the root of the site\n\t */\n\tpublic static Router getRouter() { return(router); }\n\n\t/**\n\t * Get the cache of all of the Routables which contains a Map of the Routables\n\t * per path - which saves on going through the Router and determining the\n\t * Routable on every access\n\t *\n\t * @return The Routable cache\n\t */\n\tpublic static Map<String, Routable> getRouterCache() { return (routerCache); }\n\n\t/**\n\t * Get the index/welcome files that are registered.\n\t *\n\t * @return The index files\n\t */\n\tpublic static Set<String> getIndexFiles() { return indexFiles; }\n\n\t/**\n\t * Get the handler cache\n\t * \n\t * @return the handler cache\n\t */\n\tpublic static Map<String, Handler> getHandlerCache() { return (handlerCache); }\n\t\n\t/**\n\t * Get the set of modules that have been registered with the routemaster\n\t * \n\t * @return the set of modules that have been registered\n\t */\n\tpublic static Set<String> getModules() { return(modules); }\n}",
"public class HttpUtils {\n\n\tprivate static final Logger LOGGER = Logger.getLogger(HttpUtils.class.getName());\n\n\tpublic static String cleanUri(String uri) {\n\t\tif(null == uri) {\n\t\t\treturn(null);\n\t\t}\n\n\t\treturn(uri.replaceAll(\"/\\\\.\\\\./\", \"/\").replaceAll(\"//\", \"/\"));\n\t}\n\n\tprivate static Response defaultTextResponse(IStatus status) { return(newFixedLengthResponse(status, NanoHTTPD.MIME_PLAINTEXT, status.getDescription())); }\n\tprivate static Response defaultTextResponse(IStatus status, String content) { return(newFixedLengthResponse(status, NanoHTTPD.MIME_PLAINTEXT, content)); }\n\n\tpublic static Response okResponse() { return(defaultTextResponse(Response.Status.OK)); }\n\tpublic static Response okResponse(String content) { return(defaultTextResponse(Response.Status.OK, content)); }\n\tpublic static Response okResponse(String mimeType, String content) { return(newFixedLengthResponse(Response.Status.OK, mimeType, content)); }\n\tpublic static Response okResponse(String mimeType, InputStream content, long totalBytes) { return(newFixedLengthResponse(Response.Status.OK, mimeType, content, totalBytes)); }\n\n\tpublic static Response notFoundResponse() { return(defaultTextResponse(Response.Status.NOT_FOUND)); }\n\tpublic static Response notFoundResponse(String content) { return(defaultTextResponse(Response.Status.NOT_FOUND, content)); }\n\tpublic static Response notFoundResponse(String mimeType, String content) { return(newFixedLengthResponse(Response.Status.NOT_FOUND, mimeType, content)); }\n\tpublic static Response notFoundResponse(String mimeType, InputStream content, long totalBytes) { return(newFixedLengthResponse(Response.Status.NOT_FOUND, mimeType, content, totalBytes)); }\n\n\tpublic static Response rangeNotSatisfiableResponse() { return(defaultTextResponse(Response.Status.RANGE_NOT_SATISFIABLE)); }\n\tpublic static Response rangeNotSatisfiableResponse(String content) { return(defaultTextResponse(Response.Status.RANGE_NOT_SATISFIABLE, content)); }\n\tpublic static Response rangeNotSatisfiableResponse(String mimeType, String content) { return(newFixedLengthResponse(Response.Status.RANGE_NOT_SATISFIABLE, mimeType, content)); }\n\tpublic static Response rangeNotSatisfiableResponse(String mimeType, InputStream content, long totalBytes) { return(newFixedLengthResponse(Response.Status.RANGE_NOT_SATISFIABLE, mimeType, content, totalBytes)); }\n\n\tpublic static Response methodNotAllowedResponse() { return(defaultTextResponse(Response.Status.METHOD_NOT_ALLOWED)); }\n\tpublic static Response methodNotAllowedResponse(String content) { return(defaultTextResponse(Response.Status.METHOD_NOT_ALLOWED, content)); }\n\tpublic static Response methodNotAllowedResponse(String mimeType, String content) { return(newFixedLengthResponse(Response.Status.METHOD_NOT_ALLOWED, mimeType, content)); }\n\tpublic static Response methodNotAllowedResponse(String mimeType, InputStream content, long totalBytes) { return(newFixedLengthResponse(Response.Status.METHOD_NOT_ALLOWED, mimeType, content, totalBytes)); }\n\n\tpublic static Response internalServerErrorResponse() { return(defaultTextResponse(Response.Status.INTERNAL_ERROR)); }\n\tpublic static Response internalServerErrorResponse(String content) { return(defaultTextResponse(Response.Status.INTERNAL_ERROR, content)); }\n\tpublic static Response internalServerErrorResponse(String mimeType, String content) { return(newFixedLengthResponse(Response.Status.INTERNAL_ERROR, mimeType, content)); }\n\tpublic static Response internalServerErrorResponse(String mimeType, InputStream content, long totalBytes) { return(newFixedLengthResponse(Response.Status.INTERNAL_ERROR, mimeType, content, totalBytes)); }\n\n\tpublic static Response forbiddenResponse() { return(defaultTextResponse(Response.Status.FORBIDDEN)); }\n\tpublic static Response forbiddenResponse(String content) { return(defaultTextResponse(Response.Status.FORBIDDEN, content)); }\n\tpublic static Response forbiddenResponse(String mimeType, String content) { return(newFixedLengthResponse(Response.Status.FORBIDDEN, mimeType, content)); }\n\tpublic static Response forbiddenResponse(String mimeType, InputStream content, long totalBytes) { return(newFixedLengthResponse(Response.Status.FORBIDDEN, mimeType, content, totalBytes)); }\n\n\tpublic static Response badRequestResponse() { return(defaultTextResponse(Response.Status.BAD_REQUEST)); }\n\tpublic static Response badRequestResponse(String content) { return(defaultTextResponse(Response.Status.BAD_REQUEST, content)); }\n\tpublic static Response badRequestResponse(String mimeType, String content) { return(newFixedLengthResponse(Response.Status.BAD_REQUEST, mimeType, content)); }\n\tpublic static Response badRequestResponse(String mimeType, InputStream content, long totalBytes) { return(newFixedLengthResponse(Response.Status.BAD_REQUEST, mimeType, content, totalBytes)); }\n\n\tpublic static Response notModifiedResponse() { return(defaultTextResponse(Response.Status.NOT_MODIFIED)); }\n\tpublic static Response notModifiedResponse(String content) { return(defaultTextResponse(Response.Status.NOT_MODIFIED, content)); }\n\tpublic static Response notModifiedResponse(String mimeType, String content) { return(newFixedLengthResponse(Response.Status.NOT_MODIFIED, mimeType, content)); }\n\tpublic static Response notModifiedResponse(String mimeType, InputStream content, long totalBytes) { return(newFixedLengthResponse(Response.Status.NOT_MODIFIED, mimeType, content, totalBytes)); }\n\n\tpublic static Response partialContentResponse() { return(defaultTextResponse(Response.Status.PARTIAL_CONTENT)); }\n\tpublic static Response partialContentResponse(String content) { return(defaultTextResponse(Response.Status.PARTIAL_CONTENT, content)); }\n\tpublic static Response partialContentResponse(String mimeType, String content) { return(newFixedLengthResponse(Response.Status.PARTIAL_CONTENT, mimeType, content)); }\n\tpublic static Response partialContentResponse(String mimeType, InputStream content, long totalBytes) { return(newFixedLengthResponse(Response.Status.PARTIAL_CONTENT, mimeType, content, totalBytes)); }\n\n\tpublic static Response redirectResponse(String uri) { return(redirectResponse(uri, \"<html><body>Redirected: <a href=\\\"\" + uri + \"\\\">\" + uri + \"</a></body></html>\")); }\n\tpublic static Response redirectResponse(String uri, String message) {\n\t\tResponse res = newFixedLengthResponse(Response.Status.REDIRECT, NanoHTTPD.MIME_HTML, message);\n\t\tres.addHeader(\"Location\", uri);\n\t\treturn(res);\n\t}\n\n\tpublic static Response newFixedLengthResponse(IStatus status, String mimeType, InputStream data, long totalBytes) {\n\t\treturn new Response(status, mimeType, data, totalBytes);\n\t}\n\n\t/**\n\t * Create a text response with known length.\n\t * \n\t * @param status the HTTP status\n\t * @param mimeType the mime type of the response\n\t * @param response the response message \n\t * \n\t * @return The fixed length response object\n\t */\n\tpublic static Response newFixedLengthResponse(IStatus status, String mimeType, String response) {\n\t\tif (response == null) {\n\t\t\treturn newFixedLengthResponse(status, mimeType, new ByteArrayInputStream(new byte[0]), 0);\n\t\t} else {\n\t\t\tbyte[] bytes;\n\t\t\ttry {\n\t\t\t\tbytes = response.getBytes(\"UTF-8\");\n\t\t\t} catch (UnsupportedEncodingException ueex) {\n\t\t\t\tLOGGER.log(Level.SEVERE, \"Encoding problem, responding nothing\", ueex);\n\t\t\t\tbytes = new byte[0];\n\t\t\t}\n\t\t\treturn newFixedLengthResponse(status, mimeType, new ByteArrayInputStream(bytes), bytes.length);\n\t\t}\n\t}\n\n\tpublic static String getMimeType(String uri) {\n\t\tint lastIndexOf = uri.lastIndexOf(\".\");\n\t\tString extension = uri.substring(lastIndexOf + 1);\n\n\t\tString mimeType = NanoHTTPD.MIME_HTML;\n\n\t\tif(MimeTypeMapper.getMimeTypes().containsKey(extension)) {\n\t\t\tmimeType = MimeTypeMapper.getMimeTypes().get(extension);\n\t\t}\n\t\treturn(mimeType);\n\t}\n}",
"public class MimeTypeMapper {\n\tprotected static final String MIMETYPES_PROPERTIES = \"mimetypes.properties\";\n\tprotected static final String MIMETYPES_EXAMPLE_PROPERTIES = \"mimetypes.example.properties\";\n\n\tprivate static Map<String, String> mimeTypes = new HashMap<String, String>();\n\n\tprivate MimeTypeMapper() {}\n\n\tstatic {\n\t\tProperties properties = null;\n\t\ttry {\n\t\t\tproperties = FileHelper.confirmPropertiesFileDefault(MIMETYPES_PROPERTIES, MIMETYPES_EXAMPLE_PROPERTIES);\n\t\t} catch (IOException ioex) {\n\t\t\tSimpleLogger.logFatal(\"Could not load the '\" + MIMETYPES_PROPERTIES + \"' file.\", ioex);\n\t\t}\n\n\t\tif(null != properties) {\n\t\t\tloadMimeTypesFromProperties(properties);\n\t\t}\n\t}\n\n\tprivate static void loadMimeTypesFromProperties(Properties properties) {\n\t\tEnumeration<Object> keys = properties.keys();\n\t\twhile (keys.hasMoreElements()) {\n\t\t\tString key = (String) keys.nextElement();\n\t\t\tmimeTypes.put(key, properties.getProperty(key));\n\t\t}\n\t}\n\n\tpublic static void logMimeTypes() { SimpleLogger.logTable(mimeTypes, \"registered mime types\", \"extension\", \"mime type\"); }\n\tpublic static Map<String, String> getMimeTypes() { return mimeTypes; }\n\n}",
"public abstract class NanoHTTPD {\n\n\t/**\n\t * Pluggable strategy for asynchronously executing requests.\n\t */\n\tpublic interface AsyncRunner {\n\n\t\tvoid closeAll();\n\n\t\tvoid closed(ClientHandler clientHandler);\n\n\t\tvoid exec(ClientHandler code);\n\t}\n\n\t/**\n\t * The runnable that will be used for every new client connection.\n\t */\n\tpublic class ClientHandler implements Runnable {\n\n\t\tprivate final InputStream inputStream;\n\n\t\tprivate final Socket acceptSocket;\n\n\t\tpublic ClientHandler(InputStream inputStream, Socket acceptSocket) {\n\t\t\tthis.inputStream = inputStream;\n\t\t\tthis.acceptSocket = acceptSocket;\n\t\t}\n\n\t\tpublic void close() {\n\t\t\tsafeClose(this.inputStream);\n\t\t\tsafeClose(this.acceptSocket);\n\t\t}\n\n\t\t@Override\n\t\tpublic void run() {\n\t\t\tOutputStream outputStream = null;\n\t\t\ttry {\n\t\t\t\toutputStream = this.acceptSocket.getOutputStream();\n\t\t\t\tTempFileManager tempFileManager = NanoHTTPD.this.tempFileManagerFactory.create();\n\t\t\t\tHTTPSession session = new HTTPSession(tempFileManager, this.inputStream, outputStream, this.acceptSocket.getInetAddress());\n\t\t\t\twhile (!this.acceptSocket.isClosed()) {\n\t\t\t\t\tsession.execute();\n\t\t\t\t}\n\t\t\t} catch (Exception e) {\n\t\t\t\t// When the socket is closed by the client,\n\t\t\t\t// we throw our own SocketException\n\t\t\t\t// to break the \"keep alive\" loop above. If\n\t\t\t\t// the exception was anything other\n\t\t\t\t// than the expected SocketException OR a\n\t\t\t\t// SocketTimeoutException, print the\n\t\t\t\t// stacktrace\n\t\t\t\tif (!(e instanceof SocketException && \"NanoHttpd Shutdown\".equals(e.getMessage())) && !(e instanceof SocketTimeoutException)) {\n\t\t\t\t\tNanoHTTPD.LOG.log(Level.SEVERE, \"Communication with the client broken, or an bug in the handler code\", e);\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\tsafeClose(outputStream);\n\t\t\t\tsafeClose(this.inputStream);\n\t\t\t\tsafeClose(this.acceptSocket);\n\t\t\t\tNanoHTTPD.this.asyncRunner.closed(this);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static class Cookie {\n\n\t\tpublic static String getHTTPTime(int days) {\n\t\t\tCalendar calendar = Calendar.getInstance();\n\t\t\tSimpleDateFormat dateFormat = new SimpleDateFormat(\"EEE, dd MMM yyyy HH:mm:ss z\", Locale.US);\n\t\t\tdateFormat.setTimeZone(TimeZone.getTimeZone(\"GMT\"));\n\t\t\tcalendar.add(Calendar.DAY_OF_MONTH, days);\n\t\t\treturn dateFormat.format(calendar.getTime());\n\t\t}\n\n\t\tprivate final String n, v, e;\n\n\t\tpublic Cookie(String name, String value) {\n\t\t\tthis(name, value, 30);\n\t\t}\n\n\t\tpublic Cookie(String name, String value, int numDays) {\n\t\t\tthis.n = name;\n\t\t\tthis.v = value;\n\t\t\tthis.e = getHTTPTime(numDays);\n\t\t}\n\n\t\tpublic Cookie(String name, String value, String expires) {\n\t\t\tthis.n = name;\n\t\t\tthis.v = value;\n\t\t\tthis.e = expires;\n\t\t}\n\n\t\tpublic String getHTTPHeader() {\n\t\t\tString fmt = \"%s=%s; expires=%s\";\n\t\t\treturn String.format(fmt, this.n, this.v, this.e);\n\t\t}\n\t}\n\n\t/**\n\t * Provides rudimentary support for cookies. Doesn't support 'path',\n\t * 'secure' nor 'httpOnly'. Feel free to improve it and/or add unsupported\n\t * features.\n\t * \n\t * @author LordFokas\n\t */\n\tpublic class CookieHandler implements Iterable<String> {\n\n\t\tprivate final HashMap<String, String> cookies = new HashMap<String, String>();\n\n\t\tprivate final ArrayList<Cookie> queue = new ArrayList<Cookie>();\n\n\t\tpublic CookieHandler(Map<String, String> httpHeaders) {\n\t\t\tString raw = httpHeaders.get(\"cookie\");\n\t\t\tif (raw != null) {\n\t\t\t\tString[] tokens = raw.split(\";\");\n\t\t\t\tfor (String token : tokens) {\n\t\t\t\t\tString[] data = token.trim().split(\"=\");\n\t\t\t\t\tif (data.length == 2) {\n\t\t\t\t\t\tthis.cookies.put(data[0], data[1]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Set a cookie with an expiration date from a month ago, effectively\n\t\t * deleting it on the client side.\n\t\t * \n\t\t * @param name\n\t\t * The cookie name.\n\t\t */\n\t\tpublic void delete(String name) {\n\t\t\tset(name, \"-delete-\", -30);\n\t\t}\n\n\t\t@Override\n\t\tpublic Iterator<String> iterator() {\n\t\t\treturn this.cookies.keySet().iterator();\n\t\t}\n\n\t\t/**\n\t\t * Read a cookie from the HTTP Headers.\n\t\t * \n\t\t * @param name\n\t\t * The cookie's name.\n\t\t * @return The cookie's value if it exists, null otherwise.\n\t\t */\n\t\tpublic String read(String name) {\n\t\t\treturn this.cookies.get(name);\n\t\t}\n\n\t\tpublic void set(Cookie cookie) {\n\t\t\tthis.queue.add(cookie);\n\t\t}\n\n\t\t/**\n\t\t * Sets a cookie.\n\t\t * \n\t\t * @param name\n\t\t * The cookie's name.\n\t\t * @param value\n\t\t * The cookie's value.\n\t\t * @param expires\n\t\t * How many days until the cookie expires.\n\t\t */\n\t\tpublic void set(String name, String value, int expires) {\n\t\t\tthis.queue.add(new Cookie(name, value, Cookie.getHTTPTime(expires)));\n\t\t}\n\n\t\t/**\n\t\t * Internally used by the webserver to add all queued cookies into the\n\t\t * Response's HTTP Headers.\n\t\t * \n\t\t * @param response\n\t\t * The Response object to which headers the queued cookies\n\t\t * will be added.\n\t\t */\n\t\tpublic void unloadQueue(Response response) {\n\t\t\tfor (Cookie cookie : this.queue) {\n\t\t\t\tresponse.addHeader(\"Set-Cookie\", cookie.getHTTPHeader());\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Default threading strategy for NanoHTTPD.\n\t * <p/>\n\t * <p>\n\t * By default, the server spawns a new Thread for every incoming request.\n\t * These are set to <i>daemon</i> status, and named according to the request\n\t * number. The name is useful when profiling the application.\n\t * </p>\n\t */\n\tpublic static class DefaultAsyncRunner implements AsyncRunner {\n\n\t\tprivate long requestCount;\n\n\t\tprivate final List<ClientHandler> running = Collections.synchronizedList(new ArrayList<NanoHTTPD.ClientHandler>());\n\n\t\t/**\n\t\t * @return a list with currently running clients.\n\t\t */\n\t\tpublic List<ClientHandler> getRunning() {\n\t\t\treturn running;\n\t\t}\n\n\t\t@Override\n\t\tpublic void closeAll() {\n\t\t\t// copy of the list for concurrency\n\t\t\tfor (ClientHandler clientHandler : new ArrayList<ClientHandler>(this.running)) {\n\t\t\t\tclientHandler.close();\n\t\t\t}\n\t\t}\n\n\t\t@Override\n\t\tpublic void closed(ClientHandler clientHandler) {\n\t\t\tthis.running.remove(clientHandler);\n\t\t}\n\n\t\t@Override\n\t\tpublic void exec(ClientHandler clientHandler) {\n\t\t\t++this.requestCount;\n\t\t\tThread t = new Thread(clientHandler);\n\t\t\tt.setDaemon(true);\n\t\t\tt.setName(\"NanoHttpd Request Processor (#\" + this.requestCount + \")\");\n\t\t\tthis.running.add(clientHandler);\n\t\t\tt.start();\n\t\t}\n\t}\n\n\t/**\n\t * Default strategy for creating and cleaning up temporary files.\n\t * <p/>\n\t * <p>\n\t * By default, files are created by <code>File.createTempFile()</code> in\n\t * the directory specified.\n\t * </p>\n\t */\n\tpublic static class DefaultTempFile implements TempFile {\n\n\t\tprivate final File file;\n\n\t\tprivate final OutputStream fstream;\n\n\t\tpublic DefaultTempFile(File tempdir) throws IOException {\n\t\t\tthis.file = File.createTempFile(\"NanoHTTPD-\", \"\", tempdir);\n\t\t\tthis.fstream = new FileOutputStream(this.file);\n\t\t}\n\n\t\t@Override\n\t\tpublic void delete() throws Exception {\n\t\t\tsafeClose(this.fstream);\n\t\t\tif (!this.file.delete()) {\n\t\t\t\tthrow new Exception(\"could not delete temporary file: \" + this.file.getAbsolutePath());\n\t\t\t}\n\t\t}\n\n\t\t@Override\n\t\tpublic String getName() {\n\t\t\treturn this.file.getAbsolutePath();\n\t\t}\n\n\t\t@Override\n\t\tpublic OutputStream open() throws Exception {\n\t\t\treturn this.fstream;\n\t\t}\n\t}\n\n\t/**\n\t * Default strategy for creating and cleaning up temporary files.\n\t * <p/>\n\t * <p>\n\t * This class stores its files in the standard location (that is, wherever\n\t * <code>java.io.tmpdir</code> points to). Files are added to an internal\n\t * list, and deleted when no longer needed (that is, when\n\t * <code>clear()</code> is invoked at the end of processing a request).\n\t * </p>\n\t */\n\tpublic static class DefaultTempFileManager implements TempFileManager {\n\n\t\tprivate final File tmpdir;\n\n\t\tprivate final List<TempFile> tempFiles;\n\n\t\tpublic DefaultTempFileManager() {\n\t\t\tthis.tmpdir = new File(System.getProperty(\"java.io.tmpdir\"));\n\t\t\tif (!tmpdir.exists()) {\n\t\t\t\ttmpdir.mkdirs();\n\t\t\t}\n\t\t\tthis.tempFiles = new ArrayList<TempFile>();\n\t\t}\n\n\t\t@Override\n\t\tpublic void clear() {\n\t\t\tfor (TempFile file : this.tempFiles) {\n\t\t\t\ttry {\n\t\t\t\t\tfile.delete();\n\t\t\t\t} catch (Exception ignored) {\n\t\t\t\t\tNanoHTTPD.LOG.log(Level.WARNING, \"could not delete file \", ignored);\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis.tempFiles.clear();\n\t\t}\n\n\t\t@Override\n\t\tpublic TempFile createTempFile(String filename_hint) throws Exception {\n\t\t\tDefaultTempFile tempFile = new DefaultTempFile(this.tmpdir);\n\t\t\tthis.tempFiles.add(tempFile);\n\t\t\treturn tempFile;\n\t\t}\n\t}\n\n\t/**\n\t * Default strategy for creating and cleaning up temporary files.\n\t */\n\tprivate class DefaultTempFileManagerFactory implements TempFileManagerFactory {\n\n\t\t@Override\n\t\tpublic TempFileManager create() {\n\t\t\treturn new DefaultTempFileManager();\n\t\t}\n\t}\n\n\t/**\n\t * Creates a normal ServerSocket for TCP connections\n\t */\n\tpublic static class DefaultServerSocketFactory implements ServerSocketFactory {\n\n\t\t@Override\n\t\tpublic ServerSocket create() throws IOException {\n\t\t\treturn new ServerSocket();\n\t\t}\n\n\t}\n\n\t/**\n\t * Creates a new SSLServerSocket\n\t */\n\tpublic static class SecureServerSocketFactory implements ServerSocketFactory {\n\n\t\tprivate SSLServerSocketFactory sslServerSocketFactory;\n\n\t\tprivate String[] sslProtocols;\n\n\t\tpublic SecureServerSocketFactory(SSLServerSocketFactory sslServerSocketFactory, String[] sslProtocols) {\n\t\t\tthis.sslServerSocketFactory = sslServerSocketFactory;\n\t\t\tthis.sslProtocols = sslProtocols;\n\t\t}\n\n\t\t@Override\n\t\tpublic ServerSocket create() throws IOException {\n\t\t\tSSLServerSocket ss = null;\n\t\t\tss = (SSLServerSocket) this.sslServerSocketFactory.createServerSocket();\n\t\t\tif (this.sslProtocols != null) {\n\t\t\t\tss.setEnabledProtocols(this.sslProtocols);\n\t\t\t} else {\n\t\t\t\tss.setEnabledProtocols(ss.getSupportedProtocols());\n\t\t\t}\n\t\t\tss.setUseClientMode(false);\n\t\t\tss.setWantClientAuth(false);\n\t\t\tss.setNeedClientAuth(false);\n\t\t\treturn ss;\n\t\t}\n\n\t}\n\n\tprivate static final String CONTENT_DISPOSITION_REGEX = \"([ |\\t]*Content-Disposition[ |\\t]*:)(.*)\";\n\n\tprivate static final Pattern CONTENT_DISPOSITION_PATTERN = Pattern.compile(CONTENT_DISPOSITION_REGEX, Pattern.CASE_INSENSITIVE);\n\n\tprivate static final String CONTENT_TYPE_REGEX = \"([ |\\t]*content-type[ |\\t]*:)(.*)\";\n\n\tprivate static final Pattern CONTENT_TYPE_PATTERN = Pattern.compile(CONTENT_TYPE_REGEX, Pattern.CASE_INSENSITIVE);\n\n\tprivate static final String CONTENT_DISPOSITION_ATTRIBUTE_REGEX = \"[ |\\t]*([a-zA-Z]*)[ |\\t]*=[ |\\t]*['|\\\"]([^\\\"^']*)['|\\\"]\";\n\n\tprivate static final Pattern CONTENT_DISPOSITION_ATTRIBUTE_PATTERN = Pattern.compile(CONTENT_DISPOSITION_ATTRIBUTE_REGEX);\n\n\tprotected static class ContentType {\n\n\t\tprivate static final String ASCII_ENCODING = \"US-ASCII\";\n\n\t\tprivate static final String MULTIPART_FORM_DATA_HEADER = \"multipart/form-data\";\n\n\t\tprivate static final String CONTENT_REGEX = \"[ |\\t]*([^/^ ^;^,]+/[^ ^;^,]+)\";\n\n\t\tprivate static final Pattern MIME_PATTERN = Pattern.compile(CONTENT_REGEX, Pattern.CASE_INSENSITIVE);\n\n\t\tprivate static final String CHARSET_REGEX = \"[ |\\t]*(charset)[ |\\t]*=[ |\\t]*['|\\\"]?([^\\\"^'^;^,]*)['|\\\"]?\";\n\n\t\tprivate static final Pattern CHARSET_PATTERN = Pattern.compile(CHARSET_REGEX, Pattern.CASE_INSENSITIVE);\n\n\t\tprivate static final String BOUNDARY_REGEX = \"[ |\\t]*(boundary)[ |\\t]*=[ |\\t]*['|\\\"]?([^\\\"^'^;^,]*)['|\\\"]?\";\n\n\t\tprivate static final Pattern BOUNDARY_PATTERN = Pattern.compile(BOUNDARY_REGEX, Pattern.CASE_INSENSITIVE);\n\n\t\tprivate final String contentTypeHeader;\n\n\t\tprivate final String contentType;\n\n\t\tprivate final String encoding;\n\n\t\tprivate final String boundary;\n\n\t\tpublic ContentType(String contentTypeHeader) {\n\t\t\tthis.contentTypeHeader = contentTypeHeader;\n\t\t\tif (contentTypeHeader != null) {\n\t\t\t\tcontentType = getDetailFromContentHeader(contentTypeHeader, MIME_PATTERN, \"\", 1);\n\t\t\t\tencoding = getDetailFromContentHeader(contentTypeHeader, CHARSET_PATTERN, null, 2);\n\t\t\t} else {\n\t\t\t\tcontentType = \"\";\n\t\t\t\tencoding = \"UTF-8\";\n\t\t\t}\n\t\t\tif (MULTIPART_FORM_DATA_HEADER.equalsIgnoreCase(contentType)) {\n\t\t\t\tboundary = getDetailFromContentHeader(contentTypeHeader, BOUNDARY_PATTERN, null, 2);\n\t\t\t} else {\n\t\t\t\tboundary = null;\n\t\t\t}\n\t\t}\n\n\t\tprivate String getDetailFromContentHeader(String contentTypeHeader, Pattern pattern, String defaultValue, int group) {\n\t\t\tMatcher matcher = pattern.matcher(contentTypeHeader);\n\t\t\treturn matcher.find() ? matcher.group(group) : defaultValue;\n\t\t}\n\n\t\tpublic String getContentTypeHeader() {\n\t\t\treturn contentTypeHeader;\n\t\t}\n\n\t\tpublic String getContentType() {\n\t\t\treturn contentType;\n\t\t}\n\n\t\tpublic String getEncoding() {\n\t\t\treturn encoding == null ? ASCII_ENCODING : encoding;\n\t\t}\n\n\t\tpublic String getBoundary() {\n\t\t\treturn boundary;\n\t\t}\n\n\t\tpublic boolean isMultipart() {\n\t\t\treturn MULTIPART_FORM_DATA_HEADER.equalsIgnoreCase(contentType);\n\t\t}\n\n\t\tpublic ContentType tryUTF8() {\n\t\t\tif (encoding == null) {\n\t\t\t\treturn new ContentType(this.contentTypeHeader + \"; charset=UTF-8\");\n\t\t\t}\n\t\t\treturn this;\n\t\t}\n\t}\n\n\tprotected class HTTPSession implements IHTTPSession {\n\n\t\tprivate static final int REQUEST_BUFFER_LEN = 512;\n\n\t\tprivate static final int MEMORY_STORE_LIMIT = 1024;\n\n\t\tpublic static final int BUFSIZE = 8192;\n\n\t\tpublic static final int MAX_HEADER_SIZE = 1024;\n\n\t\tprivate final TempFileManager tempFileManager;\n\n\t\tprivate final OutputStream outputStream;\n\n\t\tprivate final BufferedInputStream inputStream;\n\n\t\tprivate int splitbyte;\n\n\t\tprivate int rlen;\n\n\t\tprivate String uri;\n\n\t\tprivate Method method;\n\n\t\tprivate Map<String, List<String>> parms;\n\n\t\tprivate Map<String, String> headers;\n\n\t\tprivate CookieHandler cookies;\n\n\t\tprivate String queryParameterString;\n\n\t\tprivate String remoteIp;\n\n\t\tprivate String remoteHostname;\n\n\t\tprivate String protocolVersion;\n\n\t\tpublic HTTPSession(TempFileManager tempFileManager, InputStream inputStream, OutputStream outputStream) {\n\t\t\tthis.tempFileManager = tempFileManager;\n\t\t\tthis.inputStream = new BufferedInputStream(inputStream, HTTPSession.BUFSIZE);\n\t\t\tthis.outputStream = outputStream;\n\t\t}\n\n\t\tpublic HTTPSession(TempFileManager tempFileManager, InputStream inputStream, OutputStream outputStream, InetAddress inetAddress) {\n\t\t\tthis.tempFileManager = tempFileManager;\n\t\t\tthis.inputStream = new BufferedInputStream(inputStream, HTTPSession.BUFSIZE);\n\t\t\tthis.outputStream = outputStream;\n\t\t\tthis.remoteIp = inetAddress.isLoopbackAddress() || inetAddress.isAnyLocalAddress() ? \"127.0.0.1\" : inetAddress.getHostAddress().toString();\n\t\t\tthis.remoteHostname = inetAddress.isLoopbackAddress() || inetAddress.isAnyLocalAddress() ? \"localhost\" : inetAddress.getHostName().toString();\n\t\t\tthis.headers = new HashMap<String, String>();\n\t\t}\n\n\t\t/**\n\t\t * Decodes the sent headers and loads the data into Key/value pairs\n\t\t */\n\t\tprivate void decodeHeader(BufferedReader in, Map<String, String> pre, Map<String, List<String>> parms, Map<String, String> headers) throws ResponseException {\n\t\t\ttry {\n\t\t\t\t// Read the request line\n\t\t\t\tString inLine = in.readLine();\n\t\t\t\tif (inLine == null) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tStringTokenizer st = new StringTokenizer(inLine);\n\t\t\t\tif (!st.hasMoreTokens()) {\n\t\t\t\t\tthrow new ResponseException(Response.Status.BAD_REQUEST, \"BAD REQUEST: Syntax error. Usage: GET /example/file.html\");\n\t\t\t\t}\n\n\t\t\t\tpre.put(\"method\", st.nextToken());\n\n\t\t\t\tif (!st.hasMoreTokens()) {\n\t\t\t\t\tthrow new ResponseException(Response.Status.BAD_REQUEST, \"BAD REQUEST: Missing URI. Usage: GET /example/file.html\");\n\t\t\t\t}\n\n\t\t\t\tString uri = st.nextToken();\n\n\t\t\t\t// Decode parameters from the URI\n\t\t\t\tint qmi = uri.indexOf('?');\n\t\t\t\tif (qmi >= 0) {\n\t\t\t\t\tdecodeParms(uri.substring(qmi + 1), parms);\n\t\t\t\t\turi = decodePercent(uri.substring(0, qmi));\n\t\t\t\t} else {\n\t\t\t\t\turi = decodePercent(uri);\n\t\t\t\t}\n\n\t\t\t\t// If there's another token, its protocol version,\n\t\t\t\t// followed by HTTP headers.\n\t\t\t\t// NOTE: this now forces header names lower case since they are\n\t\t\t\t// case insensitive and vary by client.\n\t\t\t\tif (st.hasMoreTokens()) {\n\t\t\t\t\tprotocolVersion = st.nextToken();\n\t\t\t\t} else {\n\t\t\t\t\tprotocolVersion = \"HTTP/1.1\";\n\t\t\t\t\tNanoHTTPD.LOG.log(Level.FINE, \"no protocol version specified, strange. Assuming HTTP/1.1.\");\n\t\t\t\t}\n\t\t\t\tString line = in.readLine();\n\t\t\t\twhile (line != null && !line.trim().isEmpty()) {\n\t\t\t\t\tint p = line.indexOf(':');\n\t\t\t\t\tif (p >= 0) {\n\t\t\t\t\t\theaders.put(line.substring(0, p).trim().toLowerCase(Locale.US), line.substring(p + 1).trim());\n\t\t\t\t\t}\n\t\t\t\t\tline = in.readLine();\n\t\t\t\t}\n\n\t\t\t\tpre.put(\"uri\", uri);\n\t\t\t} catch (IOException ioe) {\n\t\t\t\tthrow new ResponseException(Response.Status.INTERNAL_ERROR, \"SERVER INTERNAL ERROR: IOException: \" + ioe.getMessage(), ioe);\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Decodes the Multipart Body data and put it into Key/Value pairs.\n\t\t */\n\t\tprivate void decodeMultipartFormData(ContentType contentType, ByteBuffer fbuf, Map<String, List<String>> parms, Map<String, String> files) throws ResponseException {\n\t\t\tint pcount = 0;\n\t\t\ttry {\n\t\t\t\tint[] boundaryIdxs = getBoundaryPositions(fbuf, contentType.getBoundary().getBytes());\n\t\t\t\tif (boundaryIdxs.length < 2) {\n\t\t\t\t\tthrow new ResponseException(Response.Status.BAD_REQUEST, \"BAD REQUEST: Content type is multipart/form-data but contains less than two boundary strings.\");\n\t\t\t\t}\n\n\t\t\t\tbyte[] partHeaderBuff = new byte[MAX_HEADER_SIZE];\n\t\t\t\tfor (int boundaryIdx = 0; boundaryIdx < boundaryIdxs.length - 1; boundaryIdx++) {\n\t\t\t\t\tfbuf.position(boundaryIdxs[boundaryIdx]);\n\t\t\t\t\tint len = (fbuf.remaining() < MAX_HEADER_SIZE) ? fbuf.remaining() : MAX_HEADER_SIZE;\n\t\t\t\t\tfbuf.get(partHeaderBuff, 0, len);\n\t\t\t\t\tBufferedReader in =\n\t\t\t\t\t\t\tnew BufferedReader(new InputStreamReader(new ByteArrayInputStream(partHeaderBuff, 0, len), Charset.forName(contentType.getEncoding())), len);\n\n\t\t\t\t\tint headerLines = 0;\n\t\t\t\t\t// First line is boundary string\n\t\t\t\t\tString mpline = in.readLine();\n\t\t\t\t\theaderLines++;\n\t\t\t\t\tif (mpline == null || !mpline.contains(contentType.getBoundary())) {\n\t\t\t\t\t\tthrow new ResponseException(Response.Status.BAD_REQUEST, \"BAD REQUEST: Content type is multipart/form-data but chunk does not start with boundary.\");\n\t\t\t\t\t}\n\n\t\t\t\t\tString partName = null, fileName = null, partContentType = null;\n\t\t\t\t\t// Parse the reset of the header lines\n\t\t\t\t\tmpline = in.readLine();\n\t\t\t\t\theaderLines++;\n\t\t\t\t\twhile (mpline != null && mpline.trim().length() > 0) {\n\t\t\t\t\t\tMatcher matcher = CONTENT_DISPOSITION_PATTERN.matcher(mpline);\n\t\t\t\t\t\tif (matcher.matches()) {\n\t\t\t\t\t\t\tString attributeString = matcher.group(2);\n\t\t\t\t\t\t\tmatcher = CONTENT_DISPOSITION_ATTRIBUTE_PATTERN.matcher(attributeString);\n\t\t\t\t\t\t\twhile (matcher.find()) {\n\t\t\t\t\t\t\t\tString key = matcher.group(1);\n\t\t\t\t\t\t\t\tif (\"name\".equalsIgnoreCase(key)) {\n\t\t\t\t\t\t\t\t\tpartName = matcher.group(2);\n\t\t\t\t\t\t\t\t} else if (\"filename\".equalsIgnoreCase(key)) {\n\t\t\t\t\t\t\t\t\tfileName = matcher.group(2);\n\t\t\t\t\t\t\t\t\t// add these two line to support multiple\n\t\t\t\t\t\t\t\t\t// files uploaded using the same field Id\n\t\t\t\t\t\t\t\t\tif (!fileName.isEmpty()) {\n\t\t\t\t\t\t\t\t\t\tif (pcount > 0)\n\t\t\t\t\t\t\t\t\t\t\tpartName = partName + String.valueOf(pcount++);\n\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t\tpcount++;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tmatcher = CONTENT_TYPE_PATTERN.matcher(mpline);\n\t\t\t\t\t\tif (matcher.matches()) {\n\t\t\t\t\t\t\tpartContentType = matcher.group(2).trim();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tmpline = in.readLine();\n\t\t\t\t\t\theaderLines++;\n\t\t\t\t\t}\n\t\t\t\t\tint partHeaderLength = 0;\n\t\t\t\t\twhile (headerLines-- > 0) {\n\t\t\t\t\t\tpartHeaderLength = scipOverNewLine(partHeaderBuff, partHeaderLength);\n\t\t\t\t\t}\n\t\t\t\t\t// Read the part data\n\t\t\t\t\tif (partHeaderLength >= len - 4) {\n\t\t\t\t\t\tthrow new ResponseException(Response.Status.INTERNAL_ERROR, \"Multipart header size exceeds MAX_HEADER_SIZE.\");\n\t\t\t\t\t}\n\t\t\t\t\tint partDataStart = boundaryIdxs[boundaryIdx] + partHeaderLength;\n\t\t\t\t\tint partDataEnd = boundaryIdxs[boundaryIdx + 1] - 4;\n\n\t\t\t\t\tfbuf.position(partDataStart);\n\n\t\t\t\t\tList<String> values = parms.get(partName);\n\t\t\t\t\tif (values == null) {\n\t\t\t\t\t\tvalues = new ArrayList<String>();\n\t\t\t\t\t\tparms.put(partName, values);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (partContentType == null) {\n\t\t\t\t\t\t// Read the part into a string\n\t\t\t\t\t\tbyte[] data_bytes = new byte[partDataEnd - partDataStart];\n\t\t\t\t\t\tfbuf.get(data_bytes);\n\n\t\t\t\t\t\tvalues.add(new String(data_bytes, contentType.getEncoding()));\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Read it into a file\n\t\t\t\t\t\tString path = saveTmpFile(fbuf, partDataStart, partDataEnd - partDataStart, fileName);\n\t\t\t\t\t\tif (!files.containsKey(partName)) {\n\t\t\t\t\t\t\tfiles.put(partName, path);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tint count = 2;\n\t\t\t\t\t\t\twhile (files.containsKey(partName + count)) {\n\t\t\t\t\t\t\t\tcount++;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tfiles.put(partName + count, path);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tvalues.add(fileName);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch (ResponseException re) {\n\t\t\t\tthrow re;\n\t\t\t} catch (Exception e) {\n\t\t\t\tthrow new ResponseException(Response.Status.INTERNAL_ERROR, e.toString());\n\t\t\t}\n\t\t}\n\n\t\tprivate int scipOverNewLine(byte[] partHeaderBuff, int index) {\n\t\t\twhile (partHeaderBuff[index] != '\\n') {\n\t\t\t\tindex++;\n\t\t\t}\n\t\t\treturn ++index;\n\t\t}\n\n\t\t/**\n\t\t * Decodes parameters in percent-encoded URI-format ( e.g.\n\t\t * \"name=Jack%20Daniels&pass=Single%20Malt\" ) and adds them to given\n\t\t * Map.\n\t\t */\n\t\tprivate void decodeParms(String parms, Map<String, List<String>> p) {\n\t\t\tif (parms == null) {\n\t\t\t\tthis.queryParameterString = \"\";\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthis.queryParameterString = parms;\n\t\t\tStringTokenizer st = new StringTokenizer(parms, \"&\");\n\t\t\twhile (st.hasMoreTokens()) {\n\t\t\t\tString e = st.nextToken();\n\t\t\t\tint sep = e.indexOf('=');\n\t\t\t\tString key = null;\n\t\t\t\tString value = null;\n\n\t\t\t\tif (sep >= 0) {\n\t\t\t\t\tkey = decodePercent(e.substring(0, sep)).trim();\n\t\t\t\t\tvalue = decodePercent(e.substring(sep + 1));\n\t\t\t\t} else {\n\t\t\t\t\tkey = decodePercent(e).trim();\n\t\t\t\t\tvalue = \"\";\n\t\t\t\t}\n\n\t\t\t\tList<String> values = p.get(key);\n\t\t\t\tif (values == null) {\n\t\t\t\t\tvalues = new ArrayList<String>();\n\t\t\t\t\tp.put(key, values);\n\t\t\t\t}\n\n\t\t\t\tvalues.add(value);\n\t\t\t}\n\t\t}\n\n\t\t@Override\n\t\tpublic void execute() throws IOException {\n\t\t\tResponse r = null;\n\t\t\ttry {\n\t\t\t\t// Read the first 8192 bytes.\n\t\t\t\t// The full header should fit in here.\n\t\t\t\t// Apache's default header limit is 8KB.\n\t\t\t\t// Do NOT assume that a single read will get the entire header\n\t\t\t\t// at once!\n\t\t\t\tbyte[] buf = new byte[HTTPSession.BUFSIZE];\n\t\t\t\tthis.splitbyte = 0;\n\t\t\t\tthis.rlen = 0;\n\n\t\t\t\tint read = -1;\n\t\t\t\tthis.inputStream.mark(HTTPSession.BUFSIZE);\n\t\t\t\ttry {\n\t\t\t\t\tread = this.inputStream.read(buf, 0, HTTPSession.BUFSIZE);\n\t\t\t\t} catch (SSLException e) {\n\t\t\t\t\tthrow e;\n\t\t\t\t} catch (IOException e) {\n\t\t\t\t\tsafeClose(this.inputStream);\n\t\t\t\t\tsafeClose(this.outputStream);\n\t\t\t\t\tthrow new SocketException(\"NanoHttpd Shutdown\");\n\t\t\t\t}\n\t\t\t\tif (read == -1) {\n\t\t\t\t\t// socket was been closed\n\t\t\t\t\tsafeClose(this.inputStream);\n\t\t\t\t\tsafeClose(this.outputStream);\n\t\t\t\t\tthrow new SocketException(\"NanoHttpd Shutdown\");\n\t\t\t\t}\n\t\t\t\twhile (read > 0) {\n\t\t\t\t\tthis.rlen += read;\n\t\t\t\t\tthis.splitbyte = findHeaderEnd(buf, this.rlen);\n\t\t\t\t\tif (this.splitbyte > 0) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tread = this.inputStream.read(buf, this.rlen, HTTPSession.BUFSIZE - this.rlen);\n\t\t\t\t}\n\n\t\t\t\tif (this.splitbyte < this.rlen) {\n\t\t\t\t\tthis.inputStream.reset();\n\t\t\t\t\tthis.inputStream.skip(this.splitbyte);\n\t\t\t\t}\n\n\t\t\t\tthis.parms = new HashMap<String, List<String>>();\n\t\t\t\tif (null == this.headers) {\n\t\t\t\t\tthis.headers = new HashMap<String, String>();\n\t\t\t\t} else {\n\t\t\t\t\tthis.headers.clear();\n\t\t\t\t}\n\n\t\t\t\t// Create a BufferedReader for parsing the header.\n\t\t\t\tBufferedReader hin = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(buf, 0, this.rlen)));\n\n\t\t\t\t// Decode the header into parms and header java properties\n\t\t\t\tMap<String, String> pre = new HashMap<String, String>();\n\t\t\t\tdecodeHeader(hin, pre, this.parms, this.headers);\n\n\t\t\t\tif (null != this.remoteIp) {\n\t\t\t\t\tthis.headers.put(\"remote-addr\", this.remoteIp);\n\t\t\t\t\tthis.headers.put(\"http-client-ip\", this.remoteIp);\n\t\t\t\t}\n\n\t\t\t\tthis.method = Method.lookup(pre.get(\"method\"));\n\t\t\t\tif (this.method == null) {\n\t\t\t\t\tthrow new ResponseException(Response.Status.BAD_REQUEST, \"BAD REQUEST: Syntax error. HTTP verb \" + pre.get(\"method\") + \" unhandled.\");\n\t\t\t\t}\n\n\t\t\t\tthis.uri = pre.get(\"uri\");\n\n\t\t\t\tthis.cookies = new CookieHandler(this.headers);\n\n\t\t\t\tString connection = this.headers.get(\"connection\");\n\t\t\t\tboolean keepAlive = \"HTTP/1.1\".equals(protocolVersion) && (connection == null || !connection.matches(\"(?i).*close.*\"));\n\n\t\t\t\t// Ok, now do the serve()\n\n\t\t\t\t// TODO: long body_size = getBodySize();\n\t\t\t\t// TODO: long pos_before_serve = this.inputStream.totalRead()\n\t\t\t\t// (requires implementation for totalRead())\n\t\t\t\tr = serve(this);\n\t\t\t\t// TODO: this.inputStream.skip(body_size -\n\t\t\t\t// (this.inputStream.totalRead() - pos_before_serve))\n\n\t\t\t\tif (r == null) {\n\t\t\t\t\tthrow new ResponseException(Response.Status.INTERNAL_ERROR, \"SERVER INTERNAL ERROR: Serve() returned a null response.\");\n\t\t\t\t} else {\n\t\t\t\t\tString acceptEncoding = this.headers.get(\"accept-encoding\");\n\t\t\t\t\tthis.cookies.unloadQueue(r);\n\t\t\t\t\tr.setRequestMethod(this.method);\n\t\t\t\t\tr.setGzipEncoding(useGzipWhenAccepted(r) && acceptEncoding != null && acceptEncoding.contains(\"gzip\"));\n\t\t\t\t\tr.setKeepAlive(keepAlive);\n\t\t\t\t\tr.send(this.outputStream);\n\t\t\t\t}\n\t\t\t\tif (!keepAlive || r.isCloseConnection()) {\n\t\t\t\t\tthrow new SocketException(\"NanoHttpd Shutdown\");\n\t\t\t\t}\n\t\t\t} catch (SocketException e) {\n\t\t\t\t// throw it out to close socket object (finalAccept)\n\t\t\t\tthrow e;\n\t\t\t} catch (SocketTimeoutException ste) {\n\t\t\t\t// treat socket timeouts the same way we treat socket exceptions\n\t\t\t\t// i.e. close the stream & finalAccept object by throwing the\n\t\t\t\t// exception up the call stack.\n\t\t\t\tthrow ste;\n\t\t\t} catch (SSLException ssle) {\n\t\t\t\tResponse resp = newFixedLengthResponse(Response.Status.INTERNAL_ERROR, NanoHTTPD.MIME_PLAINTEXT, \"SSL PROTOCOL FAILURE: \" + ssle.getMessage());\n\t\t\t\tresp.send(this.outputStream);\n\t\t\t\tsafeClose(this.outputStream);\n\t\t\t} catch (IOException ioe) {\n\t\t\t\tResponse resp = newFixedLengthResponse(Response.Status.INTERNAL_ERROR, NanoHTTPD.MIME_PLAINTEXT, \"SERVER INTERNAL ERROR: IOException: \" + ioe.getMessage());\n\t\t\t\tresp.send(this.outputStream);\n\t\t\t\tsafeClose(this.outputStream);\n\t\t\t} catch (ResponseException re) {\n\t\t\t\tResponse resp = newFixedLengthResponse(re.getStatus(), NanoHTTPD.MIME_PLAINTEXT, re.getMessage());\n\t\t\t\tresp.send(this.outputStream);\n\t\t\t\tsafeClose(this.outputStream);\n\t\t\t} finally {\n\t\t\t\tsafeClose(r);\n\t\t\t\tthis.tempFileManager.clear();\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Find byte index separating header from body. It must be the last byte\n\t\t * of the first two sequential new lines.\n\t\t */\n\t\tprivate int findHeaderEnd(final byte[] buf, int rlen) {\n\t\t\tint splitbyte = 0;\n\t\t\twhile (splitbyte + 1 < rlen) {\n\n\t\t\t\t// RFC2616\n\t\t\t\tif (buf[splitbyte] == '\\r' && buf[splitbyte + 1] == '\\n' && splitbyte + 3 < rlen && buf[splitbyte + 2] == '\\r' && buf[splitbyte + 3] == '\\n') {\n\t\t\t\t\treturn splitbyte + 4;\n\t\t\t\t}\n\n\t\t\t\t// tolerance\n\t\t\t\tif (buf[splitbyte] == '\\n' && buf[splitbyte + 1] == '\\n') {\n\t\t\t\t\treturn splitbyte + 2;\n\t\t\t\t}\n\t\t\t\tsplitbyte++;\n\t\t\t}\n\t\t\treturn 0;\n\t\t}\n\n\t\t/**\n\t\t * Find the byte positions where multipart boundaries start. This reads\n\t\t * a large block at a time and uses a temporary buffer to optimize\n\t\t * (memory mapped) file access.\n\t\t */\n\t\tprivate int[] getBoundaryPositions(ByteBuffer b, byte[] boundary) {\n\t\t\tint[] res = new int[0];\n\t\t\tif (b.remaining() < boundary.length) {\n\t\t\t\treturn res;\n\t\t\t}\n\n\t\t\tint search_window_pos = 0;\n\t\t\tbyte[] search_window = new byte[4 * 1024 + boundary.length];\n\n\t\t\tint first_fill = (b.remaining() < search_window.length) ? b.remaining() : search_window.length;\n\t\t\tb.get(search_window, 0, first_fill);\n\t\t\tint new_bytes = first_fill - boundary.length;\n\n\t\t\tdo {\n\t\t\t\t// Search the search_window\n\t\t\t\tfor (int j = 0; j < new_bytes; j++) {\n\t\t\t\t\tfor (int i = 0; i < boundary.length; i++) {\n\t\t\t\t\t\tif (search_window[j + i] != boundary[i])\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tif (i == boundary.length - 1) {\n\t\t\t\t\t\t\t// Match found, add it to results\n\t\t\t\t\t\t\tint[] new_res = new int[res.length + 1];\n\t\t\t\t\t\t\tSystem.arraycopy(res, 0, new_res, 0, res.length);\n\t\t\t\t\t\t\tnew_res[res.length] = search_window_pos + j;\n\t\t\t\t\t\t\tres = new_res;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tsearch_window_pos += new_bytes;\n\n\t\t\t\t// Copy the end of the buffer to the start\n\t\t\t\tSystem.arraycopy(search_window, search_window.length - boundary.length, search_window, 0, boundary.length);\n\n\t\t\t\t// Refill search_window\n\t\t\t\tnew_bytes = search_window.length - boundary.length;\n\t\t\t\tnew_bytes = (b.remaining() < new_bytes) ? b.remaining() : new_bytes;\n\t\t\t\tb.get(search_window, boundary.length, new_bytes);\n\t\t\t} while (new_bytes > 0);\n\t\t\treturn res;\n\t\t}\n\n\t\t@Override\n\t\tpublic CookieHandler getCookies() {\n\t\t\treturn this.cookies;\n\t\t}\n\n\t\t@Override\n\t\tpublic final Map<String, String> getHeaders() {\n\t\t\treturn this.headers;\n\t\t}\n\n\t\t@Override\n\t\tpublic final InputStream getInputStream() {\n\t\t\treturn this.inputStream;\n\t\t}\n\n\t\t@Override\n\t\tpublic final Method getMethod() {\n\t\t\treturn this.method;\n\t\t}\n\n\t\t/**\n\t\t * @deprecated use {@link #getParameters()} instead.\n\t\t */\n\t\t@Override\n\t\t@Deprecated\n\t\tpublic final Map<String, String> getParms() {\n\t\t\tMap<String, String> result = new HashMap<String, String>();\n\t\t\tfor (String key : this.parms.keySet()) {\n\t\t\t\tresult.put(key, this.parms.get(key).get(0));\n\t\t\t}\n\n\t\t\treturn result;\n\t\t}\n\n\t\t@Override\n\t\tpublic final Map<String, List<String>> getParameters() {\n\t\t\treturn this.parms;\n\t\t}\n\n\t\t@Override\n\t\tpublic String getQueryParameterString() {\n\t\t\treturn this.queryParameterString;\n\t\t}\n\n\t\tprivate RandomAccessFile getTmpBucket() {\n\t\t\ttry {\n\t\t\t\tTempFile tempFile = this.tempFileManager.createTempFile(null);\n\t\t\t\treturn new RandomAccessFile(tempFile.getName(), \"rw\");\n\t\t\t} catch (Exception e) {\n\t\t\t\tthrow new Error(e); // we won't recover, so throw an error\n\t\t\t}\n\t\t}\n\n\t\t@Override\n\t\tpublic final String getUri() {\n\t\t\treturn this.uri;\n\t\t}\n\n\t\t/**\n\t\t * Deduce body length in bytes. Either from \"content-length\" header or\n\t\t * read bytes.\n\t\t */\n\t\tpublic long getBodySize() {\n\t\t\tif (this.headers.containsKey(\"content-length\")) {\n\t\t\t\treturn Long.parseLong(this.headers.get(\"content-length\"));\n\t\t\t} else if (this.splitbyte < this.rlen) {\n\t\t\t\treturn this.rlen - this.splitbyte;\n\t\t\t}\n\t\t\treturn 0;\n\t\t}\n\n\t\t@Override\n\t\tpublic void parseBody(Map<String, String> files) throws IOException, ResponseException {\n\t\t\tRandomAccessFile randomAccessFile = null;\n\t\t\ttry {\n\t\t\t\tlong size = getBodySize();\n\t\t\t\tByteArrayOutputStream baos = null;\n\t\t\t\tDataOutput requestDataOutput = null;\n\n\t\t\t\t// Store the request in memory or a file, depending on size\n\t\t\t\tif (size < MEMORY_STORE_LIMIT) {\n\t\t\t\t\tbaos = new ByteArrayOutputStream();\n\t\t\t\t\trequestDataOutput = new DataOutputStream(baos);\n\t\t\t\t} else {\n\t\t\t\t\trandomAccessFile = getTmpBucket();\n\t\t\t\t\trequestDataOutput = randomAccessFile;\n\t\t\t\t}\n\n\t\t\t\t// Read all the body and write it to request_data_output\n\t\t\t\tbyte[] buf = new byte[REQUEST_BUFFER_LEN];\n\t\t\t\twhile (this.rlen >= 0 && size > 0) {\n\t\t\t\t\tthis.rlen = this.inputStream.read(buf, 0, (int) Math.min(size, REQUEST_BUFFER_LEN));\n\t\t\t\t\tsize -= this.rlen;\n\t\t\t\t\tif (this.rlen > 0) {\n\t\t\t\t\t\trequestDataOutput.write(buf, 0, this.rlen);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tByteBuffer fbuf = null;\n\t\t\t\tif (baos != null) {\n\t\t\t\t\tfbuf = ByteBuffer.wrap(baos.toByteArray(), 0, baos.size());\n\t\t\t\t} else {\n\t\t\t\t\tfbuf = randomAccessFile.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, randomAccessFile.length());\n\t\t\t\t\trandomAccessFile.seek(0);\n\t\t\t\t}\n\n\t\t\t\t// If the method is POST or PATCH, there may be parameters\n\t\t\t\t// in data section, too, read it:\n\t\t\t\tif (Method.POST.equals(this.method) || Method.PATCH.equals(this.method)) {\n\t\t\t\t\tContentType contentType = new ContentType(this.headers.get(\"content-type\"));\n\t\t\t\t\tif (contentType.isMultipart()) {\n\t\t\t\t\t\tString boundary = contentType.getBoundary();\n\t\t\t\t\t\tif (boundary == null) {\n\t\t\t\t\t\t\tthrow new ResponseException(Response.Status.BAD_REQUEST,\n\t\t\t\t\t\t\t\t\t\"BAD REQUEST: Content type is multipart/form-data but boundary missing. Usage: GET /example/file.html\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdecodeMultipartFormData(contentType, fbuf, this.parms, files);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tbyte[] postBytes = new byte[fbuf.remaining()];\n\t\t\t\t\t\tfbuf.get(postBytes);\n\t\t\t\t\t\tString postLine = new String(postBytes, contentType.getEncoding()).trim();\n\t\t\t\t\t\t// Handle application/x-www-form-urlencoded\n\t\t\t\t\t\tif (\"application/x-www-form-urlencoded\".equalsIgnoreCase(contentType.getContentType())) {\n\t\t\t\t\t\t\tdecodeParms(postLine, this.parms);\n\t\t\t\t\t\t} else if (postLine.length() != 0) {\n\t\t\t\t\t\t\t// Special case for raw POST data => create a\n\t\t\t\t\t\t\t// special files entry \"postData\" with raw content\n\t\t\t\t\t\t\t// data\n\t\t\t\t\t\t\tfiles.put(\"postData\", postLine);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else if (Method.PUT.equals(this.method)) {\n\t\t\t\t\tfiles.put(\"content\", saveTmpFile(fbuf, 0, fbuf.limit(), null));\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\tsafeClose(randomAccessFile);\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Retrieves the content of a sent file and saves it to a temporary\n\t\t * file. The full path to the saved file is returned.\n\t\t */\n\t\tprivate String saveTmpFile(ByteBuffer b, int offset, int len, String filename_hint) {\n\t\t\tString path = \"\";\n\t\t\tif (len > 0) {\n\t\t\t\tFileOutputStream fileOutputStream = null;\n\t\t\t\ttry {\n\t\t\t\t\tTempFile tempFile = this.tempFileManager.createTempFile(filename_hint);\n\t\t\t\t\tByteBuffer src = b.duplicate();\n\t\t\t\t\tfileOutputStream = new FileOutputStream(tempFile.getName());\n\t\t\t\t\tFileChannel dest = fileOutputStream.getChannel();\n\t\t\t\t\tsrc.position(offset).limit(offset + len);\n\t\t\t\t\tdest.write(src.slice());\n\t\t\t\t\tpath = tempFile.getName();\n\t\t\t\t} catch (Exception e) { // Catch exception if any\n\t\t\t\t\tthrow new Error(e); // we won't recover, so throw an error\n\t\t\t\t} finally {\n\t\t\t\t\tsafeClose(fileOutputStream);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn path;\n\t\t}\n\n\t\t@Override\n\t\tpublic String getRemoteIpAddress() {\n\t\t\treturn this.remoteIp;\n\t\t}\n\n\t\t@Override\n\t\tpublic String getRemoteHostName() {\n\t\t\treturn this.remoteHostname;\n\t\t}\n\t}\n\n\t/**\n\t * Handles one session, i.e. parses the HTTP request and returns the\n\t * response.\n\t */\n\tpublic interface IHTTPSession {\n\n\t\tvoid execute() throws IOException;\n\n\t\tCookieHandler getCookies();\n\n\t\tMap<String, String> getHeaders();\n\n\t\tInputStream getInputStream();\n\n\t\tMethod getMethod();\n\n\t\t/**\n\t\t * This method will only return the first value for a given parameter.\n\t\t * You will want to use getParameters if you expect multiple values for\n\t\t * a given key.\n\t\t * \n\t\t * @deprecated use {@link #getParameters()} instead.\n\t\t */\n\t\t@Deprecated\n\t\tMap<String, String> getParms();\n\n\t\tMap<String, List<String>> getParameters();\n\n\t\tString getQueryParameterString();\n\n\t\t/**\n\t\t * @return the path part of the URL.\n\t\t */\n\t\tString getUri();\n\n\t\t/**\n\t\t * Adds the files in the request body to the files map.\n\t\t * \n\t\t * @param files\n\t\t * map to modify\n\t\t */\n\t\tvoid parseBody(Map<String, String> files) throws IOException, ResponseException;\n\n\t\t/**\n\t\t * Get the remote ip address of the requester.\n\t\t * \n\t\t * @return the IP address.\n\t\t */\n\t\tString getRemoteIpAddress();\n\n\t\t/**\n\t\t * Get the remote hostname of the requester.\n\t\t * \n\t\t * @return the hostname.\n\t\t */\n\t\tString getRemoteHostName();\n\t}\n\n\t/**\n\t * HTTP Request methods, with the ability to decode a <code>String</code>\n\t * back to its enum value.\n\t */\n\tpublic enum Method {\n\t\tGET,\n\t\tPUT,\n\t\tPOST,\n\t\tDELETE,\n\t\tHEAD,\n\t\tOPTIONS,\n\t\tTRACE,\n\t\tCONNECT,\n\t\tPATCH,\n\t\tPROPFIND,\n\t\tPROPPATCH,\n\t\tMKCOL,\n\t\tMOVE,\n\t\tCOPY,\n\t\tLOCK,\n\t\tUNLOCK;\n\n\t\tstatic Method lookup(String method) {\n\t\t\tif (method == null)\n\t\t\t\treturn null;\n\n\t\t\ttry {\n\t\t\t\treturn valueOf(method);\n\t\t\t} catch (IllegalArgumentException e) {\n\t\t\t\t// TODO: Log it?\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * HTTP response. Return one of these from serve().\n\t */\n\tpublic static class Response implements Closeable {\n\n\t\tpublic interface IStatus {\n\n\t\t\tString getDescription();\n\n\t\t\tint getRequestStatus();\n\t\t}\n\n\t\t/**\n\t\t * Some HTTP response status codes\n\t\t */\n\t\tpublic enum Status implements IStatus {\n\t\t\tSWITCH_PROTOCOL(101, \"Switching Protocols\"),\n\n\t\t\tOK(200, \"OK\"),\n\t\t\tCREATED(201, \"Created\"),\n\t\t\tACCEPTED(202, \"Accepted\"),\n\t\t\tNO_CONTENT(204, \"No Content\"),\n\t\t\tPARTIAL_CONTENT(206, \"Partial Content\"),\n\t\t\tMULTI_STATUS(207, \"Multi-Status\"),\n\n\t\t\tREDIRECT(301, \"Moved Permanently\"),\n\t\t\t/**\n\t\t\t * Many user agents mishandle 302 in ways that violate the RFC1945\n\t\t\t * spec (i.e., redirect a POST to a GET). 303 and 307 were added in\n\t\t\t * RFC2616 to address this. You should prefer 303 and 307 unless the\n\t\t\t * calling user agent does not support 303 and 307 functionality\n\t\t\t */\n\t\t\t@Deprecated\n\t\t\tFOUND(302, \"Found\"),\n\t\t\tREDIRECT_SEE_OTHER(303, \"See Other\"),\n\t\t\tNOT_MODIFIED(304, \"Not Modified\"),\n\t\t\tTEMPORARY_REDIRECT(307, \"Temporary Redirect\"),\n\n\t\t\tBAD_REQUEST(400, \"Bad Request\"),\n\t\t\tUNAUTHORIZED(401, \"Unauthorized\"),\n\t\t\tFORBIDDEN(403, \"Forbidden\"),\n\t\t\tNOT_FOUND(404, \"Not Found\"),\n\t\t\tMETHOD_NOT_ALLOWED(405, \"Method Not Allowed\"),\n\t\t\tNOT_ACCEPTABLE(406, \"Not Acceptable\"),\n\t\t\tREQUEST_TIMEOUT(408, \"Request Timeout\"),\n\t\t\tCONFLICT(409, \"Conflict\"),\n\t\t\tGONE(410, \"Gone\"),\n\t\t\tLENGTH_REQUIRED(411, \"Length Required\"),\n\t\t\tPRECONDITION_FAILED(412, \"Precondition Failed\"),\n\t\t\tPAYLOAD_TOO_LARGE(413, \"Payload Too Large\"),\n\t\t\tUNSUPPORTED_MEDIA_TYPE(415, \"Unsupported Media Type\"),\n\t\t\tRANGE_NOT_SATISFIABLE(416, \"Requested Range Not Satisfiable\"),\n\t\t\tEXPECTATION_FAILED(417, \"Expectation Failed\"),\n\t\t\tTOO_MANY_REQUESTS(429, \"Too Many Requests\"),\n\n\t\t\tINTERNAL_ERROR(500, \"Internal Server Error\"),\n\t\t\tNOT_IMPLEMENTED(501, \"Not Implemented\"),\n\t\t\tSERVICE_UNAVAILABLE(503, \"Service Unavailable\"),\n\t\t\tUNSUPPORTED_HTTP_VERSION(505, \"HTTP Version Not Supported\");\n\n\t\t\tprivate final int requestStatus;\n\n\t\t\tprivate final String description;\n\n\t\t\tStatus(int requestStatus, String description) {\n\t\t\t\tthis.requestStatus = requestStatus;\n\t\t\t\tthis.description = description;\n\t\t\t}\n\n\t\t\tpublic static Status lookup(int requestStatus) {\n\t\t\t\tfor (Status status : Status.values()) {\n\t\t\t\t\tif (status.getRequestStatus() == requestStatus) {\n\t\t\t\t\t\treturn status;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic String getDescription() {\n\t\t\t\treturn \"\" + this.requestStatus + \" \" + this.description;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic int getRequestStatus() {\n\t\t\t\treturn this.requestStatus;\n\t\t\t}\n\n\t\t}\n\n\t\t/**\n\t\t * Output stream that will automatically send every write to the wrapped\n\t\t * OutputStream according to chunked transfer:\n\t\t * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.6.1\n\t\t */\n\t\tprivate static class ChunkedOutputStream extends FilterOutputStream {\n\n\t\t\tpublic ChunkedOutputStream(OutputStream out) {\n\t\t\t\tsuper(out);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void write(int b) throws IOException {\n\t\t\t\tbyte[] data = {\n\t\t\t\t\t\t(byte) b\n\t\t\t\t};\n\t\t\t\twrite(data, 0, 1);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void write(byte[] b) throws IOException {\n\t\t\t\twrite(b, 0, b.length);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void write(byte[] b, int off, int len) throws IOException {\n\t\t\t\tif (len == 0)\n\t\t\t\t\treturn;\n\t\t\t\tout.write(String.format(\"%x\\r\\n\", len).getBytes());\n\t\t\t\tout.write(b, off, len);\n\t\t\t\tout.write(\"\\r\\n\".getBytes());\n\t\t\t}\n\n\t\t\tpublic void finish() throws IOException {\n\t\t\t\tout.write(\"0\\r\\n\\r\\n\".getBytes());\n\t\t\t}\n\n\t\t}\n\n\t\t/**\n\t\t * HTTP status code after processing, e.g. \"200 OK\", Status.OK\n\t\t */\n\t\tprivate IStatus status;\n\n\t\t/**\n\t\t * MIME type of content, e.g. \"text/html\"\n\t\t */\n\t\tprivate String mimeType;\n\n\t\t/**\n\t\t * Data of the response, may be null.\n\t\t */\n\t\tprivate InputStream data;\n\n\t\tprivate long contentLength;\n\n\t\t/**\n\t\t * Headers for the HTTP response. Use addHeader() to add lines. the\n\t\t * lowercase map is automatically kept up to date.\n\t\t */\n\t\t@SuppressWarnings(\"serial\")\n\t\tprivate final Map<String, String> header = new HashMap<String, String>() {\n\n\t\t\tpublic String put(String key, String value) {\n\t\t\t\tlowerCaseHeader.put(key == null ? key : key.toLowerCase(), value);\n\t\t\t\treturn super.put(key, value);\n\t\t\t};\n\t\t};\n\n\t\t/**\n\t\t * copy of the header map with all the keys lowercase for faster\n\t\t * searching.\n\t\t */\n\t\tprivate final Map<String, String> lowerCaseHeader = new HashMap<String, String>();\n\n\t\t/**\n\t\t * The request method that spawned this response.\n\t\t */\n\t\tprivate Method requestMethod;\n\n\t\t/**\n\t\t * Use chunkedTransfer\n\t\t */\n\t\tprivate boolean chunkedTransfer;\n\n\t\tprivate boolean encodeAsGzip;\n\n\t\tprivate boolean keepAlive;\n\n\t\t/**\n\t\t * Creates a fixed length response if totalBytes>=0, otherwise chunked.\n\t\t */\n\t\tprotected Response(IStatus status, String mimeType, InputStream data, long totalBytes) {\n\t\t\tthis.status = status;\n\t\t\tthis.mimeType = mimeType;\n\t\t\tif (data == null) {\n\t\t\t\tthis.data = new ByteArrayInputStream(new byte[0]);\n\t\t\t\tthis.contentLength = 0L;\n\t\t\t} else {\n\t\t\t\tthis.data = data;\n\t\t\t\tthis.contentLength = totalBytes;\n\t\t\t}\n\t\t\tthis.chunkedTransfer = this.contentLength < 0;\n\t\t\tkeepAlive = true;\n\t\t}\n\n\t\t@Override\n\t\tpublic void close() throws IOException {\n\t\t\tif (this.data != null) {\n\t\t\t\tthis.data.close();\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Adds given line to the header.\n\t\t */\n\t\tpublic void addHeader(String name, String value) {\n\t\t\tthis.header.put(name, value);\n\t\t}\n\n\t\t/**\n\t\t * Indicate to close the connection after the Response has been sent.\n\t\t * \n\t\t * @param close\n\t\t * {@code true} to hint connection closing, {@code false} to\n\t\t * let connection be closed by client.\n\t\t */\n\t\tpublic void closeConnection(boolean close) {\n\t\t\tif (close)\n\t\t\t\tthis.header.put(\"connection\", \"close\");\n\t\t\telse\n\t\t\t\tthis.header.remove(\"connection\");\n\t\t}\n\n\t\t/**\n\t\t * @return {@code true} if connection is to be closed after this\n\t\t * Response has been sent.\n\t\t */\n\t\tpublic boolean isCloseConnection() {\n\t\t\treturn \"close\".equals(getHeader(\"connection\"));\n\t\t}\n\n\t\tpublic InputStream getData() {\n\t\t\treturn this.data;\n\t\t}\n\n\t\tpublic String getHeader(String name) {\n\t\t\treturn this.lowerCaseHeader.get(name.toLowerCase());\n\t\t}\n\n\t\tpublic String getMimeType() {\n\t\t\treturn this.mimeType;\n\t\t}\n\n\t\tpublic Method getRequestMethod() {\n\t\t\treturn this.requestMethod;\n\t\t}\n\n\t\tpublic IStatus getStatus() {\n\t\t\treturn this.status;\n\t\t}\n\n\t\tpublic void setGzipEncoding(boolean encodeAsGzip) {\n\t\t\tthis.encodeAsGzip = encodeAsGzip;\n\t\t}\n\n\t\tpublic void setKeepAlive(boolean useKeepAlive) {\n\t\t\tthis.keepAlive = useKeepAlive;\n\t\t}\n\n\t\t/**\n\t\t * Sends given response to the socket.\n\t\t */\n\t\tprotected void send(OutputStream outputStream) {\n\t\t\tSimpleDateFormat gmtFrmt = new SimpleDateFormat(\"E, d MMM yyyy HH:mm:ss 'GMT'\", Locale.US);\n\t\t\tgmtFrmt.setTimeZone(TimeZone.getTimeZone(\"GMT\"));\n\n\t\t\ttry {\n\t\t\t\tif (this.status == null) {\n\t\t\t\t\tthrow new Error(\"sendResponse(): Status can't be null.\");\n\t\t\t\t}\n\t\t\t\tPrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream, new ContentType(this.mimeType).getEncoding())), false);\n\t\t\t\tpw.append(\"HTTP/1.1 \").append(this.status.getDescription()).append(\" \\r\\n\");\n\t\t\t\tif (this.mimeType != null) {\n\t\t\t\t\tprintHeader(pw, \"Content-Type\", this.mimeType);\n\t\t\t\t}\n\t\t\t\tif (getHeader(\"date\") == null) {\n\t\t\t\t\tprintHeader(pw, \"Date\", gmtFrmt.format(new Date()));\n\t\t\t\t}\n\t\t\t\tfor (Entry<String, String> entry : this.header.entrySet()) {\n\t\t\t\t\tprintHeader(pw, entry.getKey(), entry.getValue());\n\t\t\t\t}\n\t\t\t\tif (getHeader(\"connection\") == null) {\n\t\t\t\t\tprintHeader(pw, \"Connection\", (this.keepAlive ? \"keep-alive\" : \"close\"));\n\t\t\t\t}\n\t\t\t\tif (getHeader(\"content-length\") != null) {\n\t\t\t\t\tencodeAsGzip = false;\n\t\t\t\t}\n\t\t\t\tif (encodeAsGzip) {\n\t\t\t\t\tprintHeader(pw, \"Content-Encoding\", \"gzip\");\n\t\t\t\t\tsetChunkedTransfer(true);\n\t\t\t\t}\n\t\t\t\tlong pending = this.data != null ? this.contentLength : 0;\n\t\t\t\tif (this.requestMethod != Method.HEAD && this.chunkedTransfer) {\n\t\t\t\t\tprintHeader(pw, \"Transfer-Encoding\", \"chunked\");\n\t\t\t\t} else if (!encodeAsGzip) {\n\t\t\t\t\tpending = sendContentLengthHeaderIfNotAlreadyPresent(pw, pending);\n\t\t\t\t}\n\t\t\t\tpw.append(\"\\r\\n\");\n\t\t\t\tpw.flush();\n\t\t\t\tsendBodyWithCorrectTransferAndEncoding(outputStream, pending);\n\t\t\t\toutputStream.flush();\n\t\t\t\tsafeClose(this.data);\n\t\t\t} catch (IOException ioe) {\n\t\t\t\tNanoHTTPD.LOG.log(Level.SEVERE, \"Could not send response to the client\", ioe);\n\t\t\t}\n\t\t}\n\n\t\t@SuppressWarnings(\"static-method\")\n\t\tprotected void printHeader(PrintWriter pw, String key, String value) {\n\t\t\tpw.append(key).append(\": \").append(value).append(\"\\r\\n\");\n\t\t}\n\n\t\tprotected long sendContentLengthHeaderIfNotAlreadyPresent(PrintWriter pw, long defaultSize) {\n\t\t\tString contentLengthString = getHeader(\"content-length\");\n\t\t\tlong size = defaultSize;\n\t\t\tif (contentLengthString != null) {\n\t\t\t\ttry {\n\t\t\t\t\tsize = Long.parseLong(contentLengthString);\n\t\t\t\t} catch (NumberFormatException ex) {\n\t\t\t\t\tLOG.severe(\"content-length was no number \" + contentLengthString);\n\t\t\t\t}\n\t\t\t}\n\t\t\tpw.print(\"Content-Length: \" + size + \"\\r\\n\");\n\t\t\treturn size;\n\t\t}\n\n\t\tprivate void sendBodyWithCorrectTransferAndEncoding(OutputStream outputStream, long pending) throws IOException {\n\t\t\tif (this.requestMethod != Method.HEAD && this.chunkedTransfer) {\n\t\t\t\tChunkedOutputStream chunkedOutputStream = new ChunkedOutputStream(outputStream);\n\t\t\t\tsendBodyWithCorrectEncoding(chunkedOutputStream, -1);\n\t\t\t\tchunkedOutputStream.finish();\n\t\t\t} else {\n\t\t\t\tsendBodyWithCorrectEncoding(outputStream, pending);\n\t\t\t}\n\t\t}\n\n\t\tprivate void sendBodyWithCorrectEncoding(OutputStream outputStream, long pending) throws IOException {\n\t\t\tif (encodeAsGzip) {\n\t\t\t\tGZIPOutputStream gzipOutputStream = new GZIPOutputStream(outputStream);\n\t\t\t\tsendBody(gzipOutputStream, -1);\n\t\t\t\tgzipOutputStream.finish();\n\t\t\t} else {\n\t\t\t\tsendBody(outputStream, pending);\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Sends the body to the specified OutputStream. The pending parameter\n\t\t * limits the maximum amounts of bytes sent unless it is -1, in which\n\t\t * case everything is sent.\n\t\t * \n\t\t * @param outputStream\n\t\t * the OutputStream to send data to\n\t\t * @param pending\n\t\t * -1 to send everything, otherwise sets a max limit to the\n\t\t * number of bytes sent\n\t\t * @throws IOException\n\t\t * if something goes wrong while sending the data.\n\t\t */\n\t\tprivate void sendBody(OutputStream outputStream, long pending) throws IOException {\n\t\t\tlong BUFFER_SIZE = 16 * 1024;\n\t\t\tbyte[] buff = new byte[(int) BUFFER_SIZE];\n\t\t\tboolean sendEverything = pending == -1;\n\t\t\twhile (pending > 0 || sendEverything) {\n\t\t\t\tlong bytesToRead = sendEverything ? BUFFER_SIZE : Math.min(pending, BUFFER_SIZE);\n\t\t\t\tint read = this.data.read(buff, 0, (int) bytesToRead);\n\t\t\t\tif (read <= 0) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\toutputStream.write(buff, 0, read);\n\t\t\t\tif (!sendEverything) {\n\t\t\t\t\tpending -= read;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tpublic void setChunkedTransfer(boolean chunkedTransfer) {\n\t\t\tthis.chunkedTransfer = chunkedTransfer;\n\t\t}\n\n\t\tpublic void setData(InputStream data) {\n\t\t\tthis.data = data;\n\t\t}\n\n\t\tpublic void setMimeType(String mimeType) {\n\t\t\tthis.mimeType = mimeType;\n\t\t}\n\n\t\tpublic void setRequestMethod(Method requestMethod) {\n\t\t\tthis.requestMethod = requestMethod;\n\t\t}\n\n\t\tpublic void setStatus(IStatus status) {\n\t\t\tthis.status = status;\n\t\t}\n\t}\n\n\tpublic static final class ResponseException extends Exception {\n\n\t\tprivate static final long serialVersionUID = 6569838532917408380L;\n\n\t\tprivate final Response.Status status;\n\n\t\tpublic ResponseException(Response.Status status, String message) {\n\t\t\tsuper(message);\n\t\t\tthis.status = status;\n\t\t}\n\n\t\tpublic ResponseException(Response.Status status, String message, Exception e) {\n\t\t\tsuper(message, e);\n\t\t\tthis.status = status;\n\t\t}\n\n\t\tpublic Response.Status getStatus() {\n\t\t\treturn this.status;\n\t\t}\n\t}\n\n\t/**\n\t * The runnable that will be used for the main listening thread.\n\t */\n\tpublic class ServerRunnable implements Runnable {\n\n\t\tprivate final int timeout;\n\n\t\tprivate IOException bindException;\n\n\t\tprivate boolean hasBinded = false;\n\n\t\tpublic ServerRunnable(int timeout) {\n\t\t\tthis.timeout = timeout;\n\t\t}\n\n\t\t@Override\n\t\tpublic void run() {\n\t\t\ttry {\n\t\t\t\tmyServerSocket.bind(hostname != null ? new InetSocketAddress(hostname, myPort) : new InetSocketAddress(myPort));\n\t\t\t\thasBinded = true;\n\t\t\t} catch (IOException e) {\n\t\t\t\tthis.bindException = e;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tdo {\n\t\t\t\ttry {\n\t\t\t\t\tfinal Socket finalAccept = NanoHTTPD.this.myServerSocket.accept();\n\t\t\t\t\tif (this.timeout > 0) {\n\t\t\t\t\t\tfinalAccept.setSoTimeout(this.timeout);\n\t\t\t\t\t}\n\t\t\t\t\tfinal InputStream inputStream = finalAccept.getInputStream();\n\t\t\t\t\tNanoHTTPD.this.asyncRunner.exec(createClientHandler(finalAccept, inputStream));\n\t\t\t\t} catch (IOException e) {\n\t\t\t\t\tNanoHTTPD.LOG.log(Level.FINE, \"Communication with the client broken\", e);\n\t\t\t\t}\n\t\t\t} while (!NanoHTTPD.this.myServerSocket.isClosed());\n\t\t}\n\t}\n\n\t/**\n\t * A temp file.\n\t * <p/>\n\t * <p>\n\t * Temp files are responsible for managing the actual temporary storage and\n\t * cleaning themselves up when no longer needed.\n\t * </p>\n\t */\n\tpublic interface TempFile {\n\n\t\tpublic void delete() throws Exception;\n\n\t\tpublic String getName();\n\n\t\tpublic OutputStream open() throws Exception;\n\t}\n\n\t/**\n\t * Temp file manager.\n\t * <p/>\n\t * <p>\n\t * Temp file managers are created 1-to-1 with incoming requests, to create\n\t * and cleanup temporary files created as a result of handling the request.\n\t * </p>\n\t */\n\tpublic interface TempFileManager {\n\n\t\tvoid clear();\n\n\t\tpublic TempFile createTempFile(String filename_hint) throws Exception;\n\t}\n\n\t/**\n\t * Factory to create temp file managers.\n\t */\n\tpublic interface TempFileManagerFactory {\n\n\t\tpublic TempFileManager create();\n\t}\n\n\t/**\n\t * Factory to create ServerSocketFactories.\n\t */\n\tpublic interface ServerSocketFactory {\n\n\t\tpublic ServerSocket create() throws IOException;\n\n\t}\n\n\t/**\n\t * Maximum time to wait on Socket.getInputStream().read() (in milliseconds)\n\t * This is required as the Keep-Alive HTTP connections would otherwise block\n\t * the socket reading thread forever (or as long the browser is open).\n\t */\n\tpublic static final int SOCKET_READ_TIMEOUT = 5000;\n\n\t/**\n\t * Common MIME type for dynamic content: plain text\n\t */\n\tpublic static final String MIME_PLAINTEXT = \"text/plain\";\n\n\t/**\n\t * Common MIME type for dynamic content: html\n\t */\n\tpublic static final String MIME_HTML = \"text/html\";\n\n\t/**\n\t * Pseudo-Parameter to use to store the actual query string in the\n\t * parameters map for later re-processing.\n\t */\n\tprivate static final String QUERY_STRING_PARAMETER = \"NanoHttpd.QUERY_STRING\";\n\n\t/**\n\t * logger to log to.\n\t */\n\tprivate static final Logger LOG = Logger.getLogger(NanoHTTPD.class.getName());\n\n\t/**\n\t * Hashtable mapping (String)FILENAME_EXTENSION -> (String)MIME_TYPE\n\t */\n\tprotected static Map<String, String> MIME_TYPES;\n\n\tpublic static Map<String, String> mimeTypes() {\n\t\tif (MIME_TYPES == null) {\n\t\t\tMIME_TYPES = new HashMap<String, String>();\n\t\t\tloadMimeTypes(MIME_TYPES, \"META-INF/nanohttpd/default-mimetypes.properties\");\n\t\t\tloadMimeTypes(MIME_TYPES, \"META-INF/nanohttpd/mimetypes.properties\");\n\t\t\tif (MIME_TYPES.isEmpty()) {\n\t\t\t\tLOG.log(Level.WARNING, \"no mime types found in the classpath! please provide mimetypes.properties\");\n\t\t\t}\n\t\t}\n\t\treturn MIME_TYPES;\n\t}\n\n\t@SuppressWarnings({\n\t\t\"unchecked\",\n\t\t\"rawtypes\"\n\t})\n\tprivate static void loadMimeTypes(Map<String, String> result, String resourceName) {\n\t\ttry {\n\t\t\tEnumeration<URL> resources = NanoHTTPD.class.getClassLoader().getResources(resourceName);\n\t\t\twhile (resources.hasMoreElements()) {\n\t\t\t\tURL url = (URL) resources.nextElement();\n\t\t\t\tProperties properties = new Properties();\n\t\t\t\tInputStream stream = null;\n\t\t\t\ttry {\n\t\t\t\t\tstream = url.openStream();\n\t\t\t\t\tproperties.load(stream);\n\t\t\t\t} catch (IOException e) {\n\t\t\t\t\tLOG.log(Level.SEVERE, \"could not load mimetypes from \" + url, e);\n\t\t\t\t} finally {\n\t\t\t\t\tsafeClose(stream);\n\t\t\t\t}\n\t\t\t\tresult.putAll((Map) properties);\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\tLOG.log(Level.INFO, \"no mime types available at \" + resourceName);\n\t\t}\n\t};\n\n\t/**\n\t * Creates an SSLSocketFactory for HTTPS. Pass a loaded KeyStore and an\n\t * array of loaded KeyManagers. These objects must properly\n\t * loaded/initialized by the caller.\n\t */\n\tpublic static SSLServerSocketFactory makeSSLSocketFactory(KeyStore loadedKeyStore, KeyManager[] keyManagers) throws IOException {\n\t\tSSLServerSocketFactory res = null;\n\t\ttry {\n\t\t\tTrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());\n\t\t\ttrustManagerFactory.init(loadedKeyStore);\n\t\t\tSSLContext ctx = SSLContext.getInstance(\"TLS\");\n\t\t\tctx.init(keyManagers, trustManagerFactory.getTrustManagers(), null);\n\t\t\tres = ctx.getServerSocketFactory();\n\t\t} catch (Exception e) {\n\t\t\tthrow new IOException(e.getMessage());\n\t\t}\n\t\treturn res;\n\t}\n\n\t/**\n\t * Creates an SSLSocketFactory for HTTPS. Pass a loaded KeyStore and a\n\t * loaded KeyManagerFactory. These objects must properly loaded/initialized\n\t * by the caller.\n\t */\n\tpublic static SSLServerSocketFactory makeSSLSocketFactory(KeyStore loadedKeyStore, KeyManagerFactory loadedKeyFactory) throws IOException {\n\t\ttry {\n\t\t\treturn makeSSLSocketFactory(loadedKeyStore, loadedKeyFactory.getKeyManagers());\n\t\t} catch (Exception e) {\n\t\t\tthrow new IOException(e.getMessage());\n\t\t}\n\t}\n\n\t/**\n\t * Creates an SSLSocketFactory for HTTPS. Pass a KeyStore resource with your\n\t * certificate and passphrase\n\t */\n\tpublic static SSLServerSocketFactory makeSSLSocketFactory(String keyAndTrustStoreClasspathPath, char[] passphrase) throws IOException {\n\t\ttry {\n\t\t\tKeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());\n\t\t\tInputStream keystoreStream = NanoHTTPD.class.getResourceAsStream(keyAndTrustStoreClasspathPath);\n\n\t\t\tif (keystoreStream == null) {\n\t\t\t\tthrow new IOException(\"Unable to load keystore from classpath: \" + keyAndTrustStoreClasspathPath);\n\t\t\t}\n\n\t\t\tkeystore.load(keystoreStream, passphrase);\n\t\t\tKeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());\n\t\t\tkeyManagerFactory.init(keystore, passphrase);\n\t\t\treturn makeSSLSocketFactory(keystore, keyManagerFactory);\n\t\t} catch (Exception e) {\n\t\t\tthrow new IOException(e.getMessage());\n\t\t}\n\t}\n\n\t/**\n\t * Get MIME type from file name extension, if possible\n\t * \n\t * @param uri\n\t * the string representing a file\n\t * @return the connected mime/type\n\t */\n\tpublic static String getMimeTypeForFile(String uri) {\n\t\tint dot = uri.lastIndexOf('.');\n\t\tString mime = null;\n\t\tif (dot >= 0) {\n\t\t\tmime = mimeTypes().get(uri.substring(dot + 1).toLowerCase());\n\t\t}\n\t\treturn mime == null ? \"application/octet-stream\" : mime;\n\t}\n\n\tprivate static final void safeClose(Object closeable) {\n\t\ttry {\n\t\t\tif (closeable != null) {\n\t\t\t\tif (closeable instanceof Closeable) {\n\t\t\t\t\t((Closeable) closeable).close();\n\t\t\t\t} else if (closeable instanceof Socket) {\n\t\t\t\t\t((Socket) closeable).close();\n\t\t\t\t} else if (closeable instanceof ServerSocket) {\n\t\t\t\t\t((ServerSocket) closeable).close();\n\t\t\t\t} else {\n\t\t\t\t\tthrow new IllegalArgumentException(\"Unknown object to close\");\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\tNanoHTTPD.LOG.log(Level.SEVERE, \"Could not close\", e);\n\t\t}\n\t}\n\n\tprivate final String hostname;\n\n\tprivate final int myPort;\n\n\tprivate volatile ServerSocket myServerSocket;\n\n\tprivate ServerSocketFactory serverSocketFactory = new DefaultServerSocketFactory();\n\n\tprivate Thread myThread;\n\n\t/**\n\t * Pluggable strategy for asynchronously executing requests.\n\t */\n\tprotected AsyncRunner asyncRunner;\n\n\t/**\n\t * Pluggable strategy for creating and cleaning up temporary files.\n\t */\n\tprivate TempFileManagerFactory tempFileManagerFactory;\n\n\t/**\n\t * Constructs an HTTP server on given port.\n\t */\n\tpublic NanoHTTPD(int port) {\n\t\tthis(null, port);\n\t}\n\n\t// -------------------------------------------------------------------------------\n\t// //\n\t//\n\t// Threading Strategy.\n\t//\n\t// -------------------------------------------------------------------------------\n\t// //\n\n\t/**\n\t * Constructs an HTTP server on given hostname and port.\n\t */\n\tpublic NanoHTTPD(String hostname, int port) {\n\t\tthis.hostname = hostname;\n\t\tthis.myPort = port;\n\t\tsetTempFileManagerFactory(new DefaultTempFileManagerFactory());\n\t\tsetAsyncRunner(new DefaultAsyncRunner());\n\t}\n\n\t/**\n\t * Forcibly closes all connections that are open.\n\t */\n\tpublic synchronized void closeAllConnections() {\n\t\tstop();\n\t}\n\n\t/**\n\t * create a instance of the client handler, subclasses can return a subclass\n\t * of the ClientHandler.\n\t * \n\t * @param finalAccept\n\t * the socket the cleint is connected to\n\t * @param inputStream\n\t * the input stream\n\t * @return the client handler\n\t */\n\tprotected ClientHandler createClientHandler(final Socket finalAccept, final InputStream inputStream) {\n\t\treturn new ClientHandler(inputStream, finalAccept);\n\t}\n\n\t/**\n\t * Instantiate the server runnable, can be overwritten by subclasses to\n\t * provide a subclass of the ServerRunnable.\n\t * \n\t * @param timeout\n\t * the socet timeout to use.\n\t * @return the server runnable.\n\t */\n\tprotected ServerRunnable createServerRunnable(final int timeout) {\n\t\treturn new ServerRunnable(timeout);\n\t}\n\n\t/**\n\t * Decode parameters from a URL, handing the case where a single parameter\n\t * name might have been supplied several times, by return lists of values.\n\t * In general these lists will contain a single element.\n\t * \n\t * @param parms\n\t * original <b>NanoHTTPD</b> parameters values, as passed to the\n\t * <code>serve()</code> method.\n\t * @return a map of <code>String</code> (parameter name) to\n\t * <code>List<String></code> (a list of the values supplied).\n\t */\n\tprotected static Map<String, List<String>> decodeParameters(Map<String, String> parms) {\n\t\treturn decodeParameters(parms.get(NanoHTTPD.QUERY_STRING_PARAMETER));\n\t}\n\n\t// -------------------------------------------------------------------------------\n\t// //\n\n\t/**\n\t * Decode parameters from a URL, handing the case where a single parameter\n\t * name might have been supplied several times, by return lists of values.\n\t * In general these lists will contain a single element.\n\t * \n\t * @param queryString\n\t * a query string pulled from the URL.\n\t * @return a map of <code>String</code> (parameter name) to\n\t * <code>List<String></code> (a list of the values supplied).\n\t */\n\tprotected static Map<String, List<String>> decodeParameters(String queryString) {\n\t\tMap<String, List<String>> parms = new HashMap<String, List<String>>();\n\t\tif (queryString != null) {\n\t\t\tStringTokenizer st = new StringTokenizer(queryString, \"&\");\n\t\t\twhile (st.hasMoreTokens()) {\n\t\t\t\tString e = st.nextToken();\n\t\t\t\tint sep = e.indexOf('=');\n\t\t\t\tString propertyName = sep >= 0 ? decodePercent(e.substring(0, sep)).trim() : decodePercent(e).trim();\n\t\t\t\tif (!parms.containsKey(propertyName)) {\n\t\t\t\t\tparms.put(propertyName, new ArrayList<String>());\n\t\t\t\t}\n\t\t\t\tString propertyValue = sep >= 0 ? decodePercent(e.substring(sep + 1)) : null;\n\t\t\t\tif (propertyValue != null) {\n\t\t\t\t\tparms.get(propertyName).add(propertyValue);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn parms;\n\t}\n\n\t/**\n\t * Decode percent encoded <code>String</code> values.\n\t * \n\t * @param str\n\t * the percent encoded <code>String</code>\n\t * @return expanded form of the input, for example \"foo%20bar\" becomes\n\t * \"foo bar\"\n\t */\n\tprotected static String decodePercent(String str) {\n\t\tString decoded = null;\n\t\ttry {\n\t\t\tdecoded = URLDecoder.decode(str, \"UTF8\");\n\t\t} catch (UnsupportedEncodingException ignored) {\n\t\t\tNanoHTTPD.LOG.log(Level.WARNING, \"Encoding not supported, ignored\", ignored);\n\t\t}\n\t\treturn decoded;\n\t}\n\n\t/**\n\t * @return true if the gzip compression should be used if the client\n\t * accespts it. Default this option is on for text content and off\n\t * for everything. Override this for custom semantics.\n\t */\n\t@SuppressWarnings(\"static-method\")\n\tprotected boolean useGzipWhenAccepted(Response r) {\n\t\treturn r.getMimeType() != null && (r.getMimeType().toLowerCase().contains(\"text/\") || r.getMimeType().toLowerCase().contains(\"/json\"));\n\t}\n\n\tpublic final int getListeningPort() {\n\t\treturn this.myServerSocket == null ? -1 : this.myServerSocket.getLocalPort();\n\t}\n\n\tpublic final boolean isAlive() {\n\t\treturn wasStarted() && !this.myServerSocket.isClosed() && this.myThread.isAlive();\n\t}\n\n\tpublic ServerSocketFactory getServerSocketFactory() {\n\t\treturn serverSocketFactory;\n\t}\n\n\tpublic void setServerSocketFactory(ServerSocketFactory serverSocketFactory) {\n\t\tthis.serverSocketFactory = serverSocketFactory;\n\t}\n\n\tpublic String getHostname() {\n\t\treturn hostname;\n\t}\n\n\tpublic TempFileManagerFactory getTempFileManagerFactory() {\n\t\treturn tempFileManagerFactory;\n\t}\n\n\t/**\n\t * Call before start() to serve over HTTPS instead of HTTP\n\t */\n\tpublic void makeSecure(SSLServerSocketFactory sslServerSocketFactory, String[] sslProtocols) {\n\t\tthis.serverSocketFactory = new SecureServerSocketFactory(sslServerSocketFactory, sslProtocols);\n\t}\n\n\t/**\n\t * Create a response with unknown length (using HTTP 1.1 chunking).\n\t */\n\tpublic static Response newChunkedResponse(IStatus status, String mimeType, InputStream data) {\n\t\treturn new Response(status, mimeType, data, -1);\n\t}\n\n\t/**\n\t * Create a response with known length.\n\t */\n\tpublic static Response newFixedLengthResponse(IStatus status, String mimeType, InputStream data, long totalBytes) {\n\t\treturn new Response(status, mimeType, data, totalBytes);\n\t}\n\n\t/**\n\t * Create a text response with known length.\n\t */\n\tpublic static Response newFixedLengthResponse(IStatus status, String mimeType, String txt) {\n\t\tContentType contentType = new ContentType(mimeType);\n\t\tif (txt == null) {\n\t\t\treturn newFixedLengthResponse(status, mimeType, new ByteArrayInputStream(new byte[0]), 0);\n\t\t} else {\n\t\t\tbyte[] bytes;\n\t\t\ttry {\n\t\t\t\tCharsetEncoder newEncoder = Charset.forName(contentType.getEncoding()).newEncoder();\n\t\t\t\tif (!newEncoder.canEncode(txt)) {\n\t\t\t\t\tcontentType = contentType.tryUTF8();\n\t\t\t\t}\n\t\t\t\tbytes = txt.getBytes(contentType.getEncoding());\n\t\t\t} catch (UnsupportedEncodingException e) {\n\t\t\t\tNanoHTTPD.LOG.log(Level.SEVERE, \"encoding problem, responding nothing\", e);\n\t\t\t\tbytes = new byte[0];\n\t\t\t}\n\t\t\treturn newFixedLengthResponse(status, contentType.getContentTypeHeader(), new ByteArrayInputStream(bytes), bytes.length);\n\t\t}\n\t}\n\n\t/**\n\t * Create a text response with known length.\n\t */\n\tpublic static Response newFixedLengthResponse(String msg) {\n\t\treturn newFixedLengthResponse(Status.OK, NanoHTTPD.MIME_HTML, msg);\n\t}\n\n\t/**\n\t * Override this to customize the server.\n\t * <p/>\n\t * <p/>\n\t * (By default, this returns a 404 \"Not Found\" plain text error response.)\n\t * \n\t * @param session\n\t * The HTTP session\n\t * @return HTTP response, see class Response for details\n\t */\n\tpublic Response serve(IHTTPSession session) {\n\t\tMap<String, String> files = new HashMap<String, String>();\n\t\tMethod method = session.getMethod();\n\t\tif (Method.PUT.equals(method) || Method.POST.equals(method) || Method.PATCH.equals(method)) {\n\t\t\ttry {\n\t\t\t\tsession.parseBody(files);\n\t\t\t} catch (IOException ioe) {\n\t\t\t\treturn newFixedLengthResponse(Response.Status.INTERNAL_ERROR, NanoHTTPD.MIME_PLAINTEXT, \"SERVER INTERNAL ERROR: IOException: \" + ioe.getMessage());\n\t\t\t} catch (ResponseException re) {\n\t\t\t\treturn newFixedLengthResponse(re.getStatus(), NanoHTTPD.MIME_PLAINTEXT, re.getMessage());\n\t\t\t}\n\t\t}\n\n\t\tMap<String, String> parms = session.getParms();\n\t\tparms.put(NanoHTTPD.QUERY_STRING_PARAMETER, session.getQueryParameterString());\n\t\treturn serve(session.getUri(), method, session.getHeaders(), parms, files);\n\t}\n\n\t/**\n\t * Override this to customize the server.\n\t * <p/>\n\t * <p/>\n\t * (By default, this returns a 404 \"Not Found\" plain text error response.)\n\t * \n\t * @param uri\n\t * Percent-decoded URI without parameters, for example\n\t * \"/index.cgi\"\n\t * @param method\n\t * \"GET\", \"POST\" etc.\n\t * @param parms\n\t * Parsed, percent decoded parameters from URI and, in case of\n\t * POST, data.\n\t * @param headers\n\t * Header entries, percent decoded\n\t * @return HTTP response, see class Response for details\n\t */\n\t@Deprecated\n\tpublic Response serve(String uri, Method method, Map<String, String> headers, Map<String, String> parms, Map<String, String> files) {\n\t\treturn newFixedLengthResponse(Response.Status.NOT_FOUND, NanoHTTPD.MIME_PLAINTEXT, \"Not Found\");\n\t}\n\n\t/**\n\t * Pluggable strategy for asynchronously executing requests.\n\t * \n\t * @param asyncRunner\n\t * new strategy for handling threads.\n\t */\n\tpublic void setAsyncRunner(AsyncRunner asyncRunner) {\n\t\tthis.asyncRunner = asyncRunner;\n\t}\n\n\t/**\n\t * Pluggable strategy for creating and cleaning up temporary files.\n\t * \n\t * @param tempFileManagerFactory\n\t * new strategy for handling temp files.\n\t */\n\tpublic void setTempFileManagerFactory(TempFileManagerFactory tempFileManagerFactory) {\n\t\tthis.tempFileManagerFactory = tempFileManagerFactory;\n\t}\n\n\t/**\n\t * Start the server.\n\t * \n\t * @throws IOException\n\t * if the socket is in use.\n\t */\n\tpublic void start() throws IOException {\n\t\tstart(NanoHTTPD.SOCKET_READ_TIMEOUT);\n\t}\n\n\t/**\n\t * Starts the server (in setDaemon(true) mode).\n\t */\n\tpublic void start(final int timeout) throws IOException {\n\t\tstart(timeout, true);\n\t}\n\n\t/**\n\t * Start the server.\n\t * \n\t * @param timeout\n\t * timeout to use for socket connections.\n\t * @param daemon\n\t * start the thread daemon or not.\n\t * @throws IOException\n\t * if the socket is in use.\n\t */\n\tpublic void start(final int timeout, boolean daemon) throws IOException {\n\t\tthis.myServerSocket = this.getServerSocketFactory().create();\n\t\tthis.myServerSocket.setReuseAddress(true);\n\n\t\tServerRunnable serverRunnable = createServerRunnable(timeout);\n\t\tthis.myThread = new Thread(serverRunnable);\n\t\tthis.myThread.setDaemon(daemon);\n\t\tthis.myThread.setName(\"NanoHttpd Main Listener\");\n\t\tthis.myThread.start();\n\t\twhile (!serverRunnable.hasBinded && serverRunnable.bindException == null) {\n\t\t\ttry {\n\t\t\t\tThread.sleep(10L);\n\t\t\t} catch (Throwable e) {\n\t\t\t\t// on android this may not be allowed, that's why we\n\t\t\t\t// catch throwable the wait should be very short because we are\n\t\t\t\t// just waiting for the bind of the socket\n\t\t\t}\n\t\t}\n\t\tif (serverRunnable.bindException != null) {\n\t\t\tthrow serverRunnable.bindException;\n\t\t}\n\t}\n\n\t/**\n\t * Stop the server.\n\t */\n\tpublic void stop() {\n\t\ttry {\n\t\t\tsafeClose(this.myServerSocket);\n\t\t\tthis.asyncRunner.closeAll();\n\t\t\tif (this.myThread != null) {\n\t\t\t\tthis.myThread.join();\n\t\t\t}\n\t\t} catch (Exception e) {\n\t\t\tNanoHTTPD.LOG.log(Level.SEVERE, \"Could not stop all connections\", e);\n\t\t}\n\t}\n\n\tpublic final boolean wasStarted() {\n\t\treturn this.myServerSocket != null && this.myThread != null;\n\t}\n}",
"public interface IHTTPSession {\n\n\tvoid execute() throws IOException;\n\n\tCookieHandler getCookies();\n\n\tMap<String, String> getHeaders();\n\n\tInputStream getInputStream();\n\n\tMethod getMethod();\n\n\t/**\n\t * This method will only return the first value for a given parameter.\n\t * You will want to use getParameters if you expect multiple values for\n\t * a given key.\n\t * \n\t * @deprecated use {@link #getParameters()} instead.\n\t */\n\t@Deprecated\n\tMap<String, String> getParms();\n\n\tMap<String, List<String>> getParameters();\n\n\tString getQueryParameterString();\n\n\t/**\n\t * @return the path part of the URL.\n\t */\n\tString getUri();\n\n\t/**\n\t * Adds the files in the request body to the files map.\n\t * \n\t * @param files\n\t * map to modify\n\t */\n\tvoid parseBody(Map<String, String> files) throws IOException, ResponseException;\n\n\t/**\n\t * Get the remote ip address of the requester.\n\t * \n\t * @return the IP address.\n\t */\n\tString getRemoteIpAddress();\n\n\t/**\n\t * Get the remote hostname of the requester.\n\t * \n\t * @return the hostname.\n\t */\n\tString getRemoteHostName();\n}",
"public static class Response implements Closeable {\n\n\tpublic interface IStatus {\n\n\t\tString getDescription();\n\n\t\tint getRequestStatus();\n\t}\n\n\t/**\n\t * Some HTTP response status codes\n\t */\n\tpublic enum Status implements IStatus {\n\t\tSWITCH_PROTOCOL(101, \"Switching Protocols\"),\n\n\t\tOK(200, \"OK\"),\n\t\tCREATED(201, \"Created\"),\n\t\tACCEPTED(202, \"Accepted\"),\n\t\tNO_CONTENT(204, \"No Content\"),\n\t\tPARTIAL_CONTENT(206, \"Partial Content\"),\n\t\tMULTI_STATUS(207, \"Multi-Status\"),\n\n\t\tREDIRECT(301, \"Moved Permanently\"),\n\t\t/**\n\t\t * Many user agents mishandle 302 in ways that violate the RFC1945\n\t\t * spec (i.e., redirect a POST to a GET). 303 and 307 were added in\n\t\t * RFC2616 to address this. You should prefer 303 and 307 unless the\n\t\t * calling user agent does not support 303 and 307 functionality\n\t\t */\n\t\t@Deprecated\n\t\tFOUND(302, \"Found\"),\n\t\tREDIRECT_SEE_OTHER(303, \"See Other\"),\n\t\tNOT_MODIFIED(304, \"Not Modified\"),\n\t\tTEMPORARY_REDIRECT(307, \"Temporary Redirect\"),\n\n\t\tBAD_REQUEST(400, \"Bad Request\"),\n\t\tUNAUTHORIZED(401, \"Unauthorized\"),\n\t\tFORBIDDEN(403, \"Forbidden\"),\n\t\tNOT_FOUND(404, \"Not Found\"),\n\t\tMETHOD_NOT_ALLOWED(405, \"Method Not Allowed\"),\n\t\tNOT_ACCEPTABLE(406, \"Not Acceptable\"),\n\t\tREQUEST_TIMEOUT(408, \"Request Timeout\"),\n\t\tCONFLICT(409, \"Conflict\"),\n\t\tGONE(410, \"Gone\"),\n\t\tLENGTH_REQUIRED(411, \"Length Required\"),\n\t\tPRECONDITION_FAILED(412, \"Precondition Failed\"),\n\t\tPAYLOAD_TOO_LARGE(413, \"Payload Too Large\"),\n\t\tUNSUPPORTED_MEDIA_TYPE(415, \"Unsupported Media Type\"),\n\t\tRANGE_NOT_SATISFIABLE(416, \"Requested Range Not Satisfiable\"),\n\t\tEXPECTATION_FAILED(417, \"Expectation Failed\"),\n\t\tTOO_MANY_REQUESTS(429, \"Too Many Requests\"),\n\n\t\tINTERNAL_ERROR(500, \"Internal Server Error\"),\n\t\tNOT_IMPLEMENTED(501, \"Not Implemented\"),\n\t\tSERVICE_UNAVAILABLE(503, \"Service Unavailable\"),\n\t\tUNSUPPORTED_HTTP_VERSION(505, \"HTTP Version Not Supported\");\n\n\t\tprivate final int requestStatus;\n\n\t\tprivate final String description;\n\n\t\tStatus(int requestStatus, String description) {\n\t\t\tthis.requestStatus = requestStatus;\n\t\t\tthis.description = description;\n\t\t}\n\n\t\tpublic static Status lookup(int requestStatus) {\n\t\t\tfor (Status status : Status.values()) {\n\t\t\t\tif (status.getRequestStatus() == requestStatus) {\n\t\t\t\t\treturn status;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn null;\n\t\t}\n\n\t\t@Override\n\t\tpublic String getDescription() {\n\t\t\treturn \"\" + this.requestStatus + \" \" + this.description;\n\t\t}\n\n\t\t@Override\n\t\tpublic int getRequestStatus() {\n\t\t\treturn this.requestStatus;\n\t\t}\n\n\t}\n\n\t/**\n\t * Output stream that will automatically send every write to the wrapped\n\t * OutputStream according to chunked transfer:\n\t * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.6.1\n\t */\n\tprivate static class ChunkedOutputStream extends FilterOutputStream {\n\n\t\tpublic ChunkedOutputStream(OutputStream out) {\n\t\t\tsuper(out);\n\t\t}\n\n\t\t@Override\n\t\tpublic void write(int b) throws IOException {\n\t\t\tbyte[] data = {\n\t\t\t\t\t(byte) b\n\t\t\t};\n\t\t\twrite(data, 0, 1);\n\t\t}\n\n\t\t@Override\n\t\tpublic void write(byte[] b) throws IOException {\n\t\t\twrite(b, 0, b.length);\n\t\t}\n\n\t\t@Override\n\t\tpublic void write(byte[] b, int off, int len) throws IOException {\n\t\t\tif (len == 0)\n\t\t\t\treturn;\n\t\t\tout.write(String.format(\"%x\\r\\n\", len).getBytes());\n\t\t\tout.write(b, off, len);\n\t\t\tout.write(\"\\r\\n\".getBytes());\n\t\t}\n\n\t\tpublic void finish() throws IOException {\n\t\t\tout.write(\"0\\r\\n\\r\\n\".getBytes());\n\t\t}\n\n\t}\n\n\t/**\n\t * HTTP status code after processing, e.g. \"200 OK\", Status.OK\n\t */\n\tprivate IStatus status;\n\n\t/**\n\t * MIME type of content, e.g. \"text/html\"\n\t */\n\tprivate String mimeType;\n\n\t/**\n\t * Data of the response, may be null.\n\t */\n\tprivate InputStream data;\n\n\tprivate long contentLength;\n\n\t/**\n\t * Headers for the HTTP response. Use addHeader() to add lines. the\n\t * lowercase map is automatically kept up to date.\n\t */\n\t@SuppressWarnings(\"serial\")\n\tprivate final Map<String, String> header = new HashMap<String, String>() {\n\n\t\tpublic String put(String key, String value) {\n\t\t\tlowerCaseHeader.put(key == null ? key : key.toLowerCase(), value);\n\t\t\treturn super.put(key, value);\n\t\t};\n\t};\n\n\t/**\n\t * copy of the header map with all the keys lowercase for faster\n\t * searching.\n\t */\n\tprivate final Map<String, String> lowerCaseHeader = new HashMap<String, String>();\n\n\t/**\n\t * The request method that spawned this response.\n\t */\n\tprivate Method requestMethod;\n\n\t/**\n\t * Use chunkedTransfer\n\t */\n\tprivate boolean chunkedTransfer;\n\n\tprivate boolean encodeAsGzip;\n\n\tprivate boolean keepAlive;\n\n\t/**\n\t * Creates a fixed length response if totalBytes>=0, otherwise chunked.\n\t */\n\tprotected Response(IStatus status, String mimeType, InputStream data, long totalBytes) {\n\t\tthis.status = status;\n\t\tthis.mimeType = mimeType;\n\t\tif (data == null) {\n\t\t\tthis.data = new ByteArrayInputStream(new byte[0]);\n\t\t\tthis.contentLength = 0L;\n\t\t} else {\n\t\t\tthis.data = data;\n\t\t\tthis.contentLength = totalBytes;\n\t\t}\n\t\tthis.chunkedTransfer = this.contentLength < 0;\n\t\tkeepAlive = true;\n\t}\n\n\t@Override\n\tpublic void close() throws IOException {\n\t\tif (this.data != null) {\n\t\t\tthis.data.close();\n\t\t}\n\t}\n\n\t/**\n\t * Adds given line to the header.\n\t */\n\tpublic void addHeader(String name, String value) {\n\t\tthis.header.put(name, value);\n\t}\n\n\t/**\n\t * Indicate to close the connection after the Response has been sent.\n\t * \n\t * @param close\n\t * {@code true} to hint connection closing, {@code false} to\n\t * let connection be closed by client.\n\t */\n\tpublic void closeConnection(boolean close) {\n\t\tif (close)\n\t\t\tthis.header.put(\"connection\", \"close\");\n\t\telse\n\t\t\tthis.header.remove(\"connection\");\n\t}\n\n\t/**\n\t * @return {@code true} if connection is to be closed after this\n\t * Response has been sent.\n\t */\n\tpublic boolean isCloseConnection() {\n\t\treturn \"close\".equals(getHeader(\"connection\"));\n\t}\n\n\tpublic InputStream getData() {\n\t\treturn this.data;\n\t}\n\n\tpublic String getHeader(String name) {\n\t\treturn this.lowerCaseHeader.get(name.toLowerCase());\n\t}\n\n\tpublic String getMimeType() {\n\t\treturn this.mimeType;\n\t}\n\n\tpublic Method getRequestMethod() {\n\t\treturn this.requestMethod;\n\t}\n\n\tpublic IStatus getStatus() {\n\t\treturn this.status;\n\t}\n\n\tpublic void setGzipEncoding(boolean encodeAsGzip) {\n\t\tthis.encodeAsGzip = encodeAsGzip;\n\t}\n\n\tpublic void setKeepAlive(boolean useKeepAlive) {\n\t\tthis.keepAlive = useKeepAlive;\n\t}\n\n\t/**\n\t * Sends given response to the socket.\n\t */\n\tprotected void send(OutputStream outputStream) {\n\t\tSimpleDateFormat gmtFrmt = new SimpleDateFormat(\"E, d MMM yyyy HH:mm:ss 'GMT'\", Locale.US);\n\t\tgmtFrmt.setTimeZone(TimeZone.getTimeZone(\"GMT\"));\n\n\t\ttry {\n\t\t\tif (this.status == null) {\n\t\t\t\tthrow new Error(\"sendResponse(): Status can't be null.\");\n\t\t\t}\n\t\t\tPrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream, new ContentType(this.mimeType).getEncoding())), false);\n\t\t\tpw.append(\"HTTP/1.1 \").append(this.status.getDescription()).append(\" \\r\\n\");\n\t\t\tif (this.mimeType != null) {\n\t\t\t\tprintHeader(pw, \"Content-Type\", this.mimeType);\n\t\t\t}\n\t\t\tif (getHeader(\"date\") == null) {\n\t\t\t\tprintHeader(pw, \"Date\", gmtFrmt.format(new Date()));\n\t\t\t}\n\t\t\tfor (Entry<String, String> entry : this.header.entrySet()) {\n\t\t\t\tprintHeader(pw, entry.getKey(), entry.getValue());\n\t\t\t}\n\t\t\tif (getHeader(\"connection\") == null) {\n\t\t\t\tprintHeader(pw, \"Connection\", (this.keepAlive ? \"keep-alive\" : \"close\"));\n\t\t\t}\n\t\t\tif (getHeader(\"content-length\") != null) {\n\t\t\t\tencodeAsGzip = false;\n\t\t\t}\n\t\t\tif (encodeAsGzip) {\n\t\t\t\tprintHeader(pw, \"Content-Encoding\", \"gzip\");\n\t\t\t\tsetChunkedTransfer(true);\n\t\t\t}\n\t\t\tlong pending = this.data != null ? this.contentLength : 0;\n\t\t\tif (this.requestMethod != Method.HEAD && this.chunkedTransfer) {\n\t\t\t\tprintHeader(pw, \"Transfer-Encoding\", \"chunked\");\n\t\t\t} else if (!encodeAsGzip) {\n\t\t\t\tpending = sendContentLengthHeaderIfNotAlreadyPresent(pw, pending);\n\t\t\t}\n\t\t\tpw.append(\"\\r\\n\");\n\t\t\tpw.flush();\n\t\t\tsendBodyWithCorrectTransferAndEncoding(outputStream, pending);\n\t\t\toutputStream.flush();\n\t\t\tsafeClose(this.data);\n\t\t} catch (IOException ioe) {\n\t\t\tNanoHTTPD.LOG.log(Level.SEVERE, \"Could not send response to the client\", ioe);\n\t\t}\n\t}\n\n\t@SuppressWarnings(\"static-method\")\n\tprotected void printHeader(PrintWriter pw, String key, String value) {\n\t\tpw.append(key).append(\": \").append(value).append(\"\\r\\n\");\n\t}\n\n\tprotected long sendContentLengthHeaderIfNotAlreadyPresent(PrintWriter pw, long defaultSize) {\n\t\tString contentLengthString = getHeader(\"content-length\");\n\t\tlong size = defaultSize;\n\t\tif (contentLengthString != null) {\n\t\t\ttry {\n\t\t\t\tsize = Long.parseLong(contentLengthString);\n\t\t\t} catch (NumberFormatException ex) {\n\t\t\t\tLOG.severe(\"content-length was no number \" + contentLengthString);\n\t\t\t}\n\t\t}\n\t\tpw.print(\"Content-Length: \" + size + \"\\r\\n\");\n\t\treturn size;\n\t}\n\n\tprivate void sendBodyWithCorrectTransferAndEncoding(OutputStream outputStream, long pending) throws IOException {\n\t\tif (this.requestMethod != Method.HEAD && this.chunkedTransfer) {\n\t\t\tChunkedOutputStream chunkedOutputStream = new ChunkedOutputStream(outputStream);\n\t\t\tsendBodyWithCorrectEncoding(chunkedOutputStream, -1);\n\t\t\tchunkedOutputStream.finish();\n\t\t} else {\n\t\t\tsendBodyWithCorrectEncoding(outputStream, pending);\n\t\t}\n\t}\n\n\tprivate void sendBodyWithCorrectEncoding(OutputStream outputStream, long pending) throws IOException {\n\t\tif (encodeAsGzip) {\n\t\t\tGZIPOutputStream gzipOutputStream = new GZIPOutputStream(outputStream);\n\t\t\tsendBody(gzipOutputStream, -1);\n\t\t\tgzipOutputStream.finish();\n\t\t} else {\n\t\t\tsendBody(outputStream, pending);\n\t\t}\n\t}\n\n\t/**\n\t * Sends the body to the specified OutputStream. The pending parameter\n\t * limits the maximum amounts of bytes sent unless it is -1, in which\n\t * case everything is sent.\n\t * \n\t * @param outputStream\n\t * the OutputStream to send data to\n\t * @param pending\n\t * -1 to send everything, otherwise sets a max limit to the\n\t * number of bytes sent\n\t * @throws IOException\n\t * if something goes wrong while sending the data.\n\t */\n\tprivate void sendBody(OutputStream outputStream, long pending) throws IOException {\n\t\tlong BUFFER_SIZE = 16 * 1024;\n\t\tbyte[] buff = new byte[(int) BUFFER_SIZE];\n\t\tboolean sendEverything = pending == -1;\n\t\twhile (pending > 0 || sendEverything) {\n\t\t\tlong bytesToRead = sendEverything ? BUFFER_SIZE : Math.min(pending, BUFFER_SIZE);\n\t\t\tint read = this.data.read(buff, 0, (int) bytesToRead);\n\t\t\tif (read <= 0) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\toutputStream.write(buff, 0, read);\n\t\t\tif (!sendEverything) {\n\t\t\t\tpending -= read;\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void setChunkedTransfer(boolean chunkedTransfer) {\n\t\tthis.chunkedTransfer = chunkedTransfer;\n\t}\n\n\tpublic void setData(InputStream data) {\n\t\tthis.data = data;\n\t}\n\n\tpublic void setMimeType(String mimeType) {\n\t\tthis.mimeType = mimeType;\n\t}\n\n\tpublic void setRequestMethod(Method requestMethod) {\n\t\tthis.requestMethod = requestMethod;\n\t}\n\n\tpublic void setStatus(IStatus status) {\n\t\tthis.status = status;\n\t}\n}"
] | import fi.iki.elonen.NanoHTTPD;
import fi.iki.elonen.NanoHTTPD.IHTTPSession;
import fi.iki.elonen.NanoHTTPD.Response;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import synapticloop.nanohttpd.handler.Handler;
import synapticloop.nanohttpd.router.Routable;
import synapticloop.nanohttpd.router.RouteMaster;
import synapticloop.nanohttpd.utils.HttpUtils;
import synapticloop.nanohttpd.utils.MimeTypeMapper; | package synapticloop.nanohttpd.servant;
/*
* Copyright (c) 2013-2020 synapticloop.
*
* All rights reserved.
*
* This source code and any derived binaries are covered by the terms and
* conditions of the Licence agreement ("the Licence"). You may not use this
* source code or any derived binaries except in compliance with the Licence.
* A copy of the Licence is available in the file named LICENCE shipped with
* this source code or binaries.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* Licence for the specific language governing permissions and limitations
* under the Licence.
*/
public class StaticFileServant extends Routable {
private static final Logger LOGGER = Logger.getLogger(StaticFileServant.class.getSimpleName());
public StaticFileServant(String routeContext) {
super(routeContext);
}
@Override | public Response serve(File rootDir, IHTTPSession httpSession) { | 7 |
dima767/inspektr | inspektr-audit/src/main/java/com/github/inspektr/audit/AuditTrailManagementAspect.java | [
"public interface AuditActionResolver {\n\t\n\n /**\n * Resolve the action for the audit event.\n * \n * @param auditableTarget\n * @param retval\tThe returned value\n * @param audit the Audit annotation that may contain additional information.\n * @return\tThe resource String\n */\n String resolveFrom(JoinPoint auditableTarget, Object retval, Audit audit);\n \n /**\n * Resolve the action for the audit event that has incurred\n * an exception.\n * \n * @param auditableTarget\n * @param exception\tThe exception incurred when the join point proceeds.\n * @param audit the Audit annotation that may contain additional information.\n * @return\tThe resource String\n */\n String resolveFrom(JoinPoint auditableTarget, Exception exception, Audit audit);\n\n}",
"public interface AuditResourceResolver {\n\n /**\n * Resolve the auditable resource.\n * \n * @param target the join point that contains the arguments.\n * @param returnValue\tThe returned value\n * @return\tThe resource String.\n */\n String[] resolveFrom(JoinPoint target, Object returnValue);\n \n /**\n * Resolve the auditable resource for an audit-able action that has\n * incurred an exception.\n * \n * @param target the join point that contains the arguments.\n * @param exception\tThe exception incurred when the join point proceeds.\n * @return\tThe resource String.\n */\n String[] resolveFrom(JoinPoint target, Exception exception);\n}",
"public interface PrincipalResolver {\n\n /**\n * Default String that can be used when the user is anonymous.\n */\n final String ANONYMOUS_USER = \"audit:anonymous\";\n\n /**\n * Default String that can be used when the user cannot be determined.\n */\n final String UNKNOWN_USER = \"audit:unknown\";\n\n /**\n * Resolve the principal performing an audit-able action.\n * <p>\n * Note, this method should NEVER throw an exception *unless* the expectation is that a failed resolution causes\n * the entire transaction to fail. Otherwise use {@link com.github.inspektr.common.spi.PrincipalResolver#UNKNOWN_USER}.\n * \n * @param auditTarget the join point where we're auditing.\n * @param returnValue the returned value\n * @return\tThe principal as a String. CANNOT be NULL.\n */\n String resolveFrom(JoinPoint auditTarget, Object returnValue);\n \n /**\n * Resolve the principal performing an audit-able action that has incurred\n * an exception.\n * <p>\n * Note, this method should NEVER throw an exception *unless* the expectation is that a failed resolution causes\n * the entire transaction to fail. Otherwise use {@link com.github.inspektr.common.spi.PrincipalResolver#UNKNOWN_USER}.\n * \n * @param auditTarget the join point where we're auditing.\n * @param exception\tThe exception incurred when the join point proceeds.\n * @return\tThe principal as a String. CANNOT be NULL.\n */\n String resolveFrom(JoinPoint auditTarget, Exception exception);\n\n /**\n * Called when there is no other way to resolve the principal (i.e. an error was captured, auditing was not\n * called, etc.)\n * <p>\n * Note, this method should NEVER throw an exception *unless* the expectation is that a failed resolution causes\n * the entire transaction to fail. Otherwise use {@link com.github.inspektr.common.spi.PrincipalResolver#UNKNOWN_USER}.\n *\n * @return the principal. CANNOT be NULL.\n */\n String resolve();\n}",
"public interface ClientInfoResolver {\n\t\n\t/**\n\t * Resolve the ClientInfo from the provided arguments and return value.\n\t * \n\t * @param joinPoint the point where the join occurred.\n\t * @param retVal the return value from the method call.\n\t * @return the constructed ClientInfo object. Should never return null!\n\t */\n\tClientInfo resolveFrom(JoinPoint joinPoint, Object retVal);\n}",
"public final class DefaultClientInfoResolver implements ClientInfoResolver {\n\t\n\tprivate final Logger log = LoggerFactory.getLogger(getClass());\n\n\tpublic ClientInfo resolveFrom(final JoinPoint joinPoint, final Object retVal) {\n\t\tfinal ClientInfo clientInfo = ClientInfoHolder.getClientInfo();\n\t\t\n\t\tif (clientInfo != null) {\n\t\t\treturn clientInfo;\n\t\t}\n\t\t\n\t\tlog.warn(\"No ClientInfo could be found. Returning empty ClientInfo object.\");\n\t\t\n\t\treturn ClientInfo.EMPTY_CLIENT_INFO;\n\t}\n}",
"public final class ClientInfo {\n\n public static ClientInfo EMPTY_CLIENT_INFO = new ClientInfo();\n\t\n\t/** IP Address of the server (local). */\n\tprivate final String serverIpAddress;\n\t\n\t/** IP Address of the client (Remote) */\n\tprivate final String clientIpAddress;\n\t\n\tprivate ClientInfo() {\n\t\tthis((String) null, (String) null);\n\t}\n\t\n\tpublic ClientInfo(final HttpServletRequest request) {\n\t\tthis(request.getLocalAddr(), request.getRemoteAddr());\n\t}\n\n public ClientInfo(final HttpServletRequest request, final String alternateLocation) {\n this(request.getLocalAddr(), request.getHeader(alternateLocation) != null ? request.getHeader(alternateLocation) : request.getRemoteAddr());\n }\n\t\n\tpublic ClientInfo(final String serverIpAddress, final String clientIpAddress) {\n\t\tthis.serverIpAddress = serverIpAddress == null ? \"unknown\" : serverIpAddress;\n\t\tthis.clientIpAddress = clientIpAddress == null ? \"unknown\" : clientIpAddress;\n\t}\n\n\tpublic String getServerIpAddress() {\n\t\treturn this.serverIpAddress;\n\t}\n\n\tpublic String getClientIpAddress() {\n\t\treturn this.clientIpAddress;\n\t}\n}"
] | import com.github.inspektr.common.spi.PrincipalResolver;
import com.github.inspektr.common.spi.ClientInfoResolver;
import com.github.inspektr.common.spi.DefaultClientInfoResolver;
import com.github.inspektr.common.web.ClientInfo;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Aspect;
import com.github.inspektr.audit.annotation.Audit;
import com.github.inspektr.audit.annotation.Audits;
import com.github.inspektr.audit.spi.AuditActionResolver;
import com.github.inspektr.audit.spi.AuditResourceResolver; | /**
* Licensed to Inspektr under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Inspektr licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a
* copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.github.inspektr.audit;
/**
* A POJO style aspect modularizing management of an audit trail data concern.
*
* @author Dmitriy Kopylenko
* @author Scott Battaglia
* @version $Revision$ $Date$
* @since 1.0
*/
@Aspect
public final class AuditTrailManagementAspect {
private final PrincipalResolver auditPrincipalResolver;
private final Map<String, AuditActionResolver> auditActionResolvers;
private final Map<String, AuditResourceResolver> auditResourceResolvers;
private final List<AuditTrailManager> auditTrailManagers;
private final String applicationCode;
| private ClientInfoResolver clientInfoResolver = new DefaultClientInfoResolver(); | 3 |
bitcraze/crazyflie-android-client | src/se/bitcraze/crazyfliecontrol/bootloader/BootloaderActivity.java | [
"public class BootVersion {\n\n public final static int CF1_PROTO_VER_0 = 0x00;\n public final static int CF1_PROTO_VER_1 = 0x01;\n public final static int CF2_PROTO_VER = 0x10;\n\n public static String toVersionString(int ver) {\n if (ver == BootVersion.CF1_PROTO_VER_0 || ver == BootVersion.CF1_PROTO_VER_1) {\n return \"Crazyflie Nano Quadcopter (1.0)\";\n } else if (ver == BootVersion.CF2_PROTO_VER) {\n return \"Crazyflie 2.0\";\n }\n return \"Unknown\";\n }\n\n}",
"public class Bootloader {\n\n final Logger mLogger = LoggerFactory.getLogger(\"Bootloader\");\n\n private static ObjectMapper mMapper = new ObjectMapper(); // can reuse, share globally\n private static final String MANIFEST_FILENAME = \"manifest.json\";\n private Cloader mCload;\n private boolean mCancelled = false;\n private List<BootloaderListener> mBootloaderListeners = Collections.synchronizedList(new LinkedList<BootloaderListener>());\n\n /**\n * Init the communication class by starting to communicate with the\n * link given. clink is the link address used after resetting to the\n * bootloader.\n *\n * The device is actually considered to be in firmware mode.\n */\n public Bootloader(CrtpDriver driver) {\n this.mCload = new Cloader(driver);\n mMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);\n }\n\n public Cloader getCloader() {\n return this.mCload;\n }\n\n public boolean startBootloader(boolean warmboot) {\n boolean started = false;\n\n if (warmboot) {\n mLogger.info(\"startBootloader: warmboot\");\n\n //TODO\n //self._cload.open_bootloader_uri(self.clink)\n //this.mCload.openBootloaderConnection(connectionData);\n started = this.mCload.resetToBootloader(TargetTypes.NRF51); //is NRF51 correct here?\n if (started) {\n started = this.mCload.checkLinkAndGetInfo(TargetTypes.STM32);\n }\n } else {\n mLogger.info(\"startBootloader: coldboot\");\n ConnectionData bootloaderConnection = this.mCload.scanForBootloader();\n\n // Workaround for libusb on Windows (open/close too fast)\n //time.sleep(1)\n\n if (bootloaderConnection != null) {\n mLogger.info(\"startBootloader: bootloader connection found\");\n try {\n this.mCload.setConnectionData(bootloaderConnection);\n this.mCload.openBootloaderConnection();\n started = this.mCload.checkLinkAndGetInfo(TargetTypes.STM32); //TODO: what is the real parameter for this?\n } catch (IOException e) {\n mLogger.warn(e.getMessage());\n started = false;\n }\n } else {\n mLogger.info(\"startBootloader: bootloader connection NOT found\");\n started = false;\n }\n\n if (started) {\n int protocolVersion = this.mCload.getProtocolVersion();\n if (protocolVersion == BootVersion.CF1_PROTO_VER_0 ||\n protocolVersion == BootVersion.CF1_PROTO_VER_1) {\n // Nothing to do\n } else if (protocolVersion == BootVersion.CF2_PROTO_VER) {\n this.mCload.requestInfoUpdate(TargetTypes.NRF51);\n } else {\n mLogger.debug(\"Bootloader protocol \" + String.format(\"0x%02X\", protocolVersion) + \" not supported!\");\n }\n\n mLogger.info(\"startBootloader: started\");\n } else {\n mLogger.info(\"startBootloader: not started\");\n }\n }\n return started;\n }\n\n public Target getTarget(int targetId) {\n return this.mCload.requestInfoUpdate(targetId);\n }\n\n public int getProtocolVersion() {\n return this.mCload.getProtocolVersion();\n }\n\n /**\n * Read a flash page from the specified target\n */\n public byte[] readCF1Config() {\n Target target = this.mCload.getTargets().get(TargetTypes.STM32); //CF1\n int configPage = target.getFlashPages() - 1;\n\n return this.mCload.readFlash(0xFF, configPage);\n }\n\n public boolean writeCF1Config(byte[] data) {\n Target target = this.mCload.getTargets().get(TargetTypes.STM32); //CF1\n int configPage = target.getFlashPages() - 1;\n FlashTarget toFlash = new FlashTarget(target, data, \"CF1 config\", configPage);\n return internalFlash(toFlash);\n }\n\n //TODO: improve\n public static byte[] readFile(File file) throws IOException {\n byte[] fileData = new byte[(int) file.length()];\n Logger logger = LoggerFactory.getLogger(\"Bootloader\");\n logger.debug(\"readFile: \" + file.getName() + \", size: \" + file.length());\n RandomAccessFile raf = null;\n try {\n raf = new RandomAccessFile(file.getAbsoluteFile(), \"r\");\n raf.readFully(fileData);\n } finally {\n if (raf != null) {\n try {\n raf.close();\n } catch (IOException ioe) {\n logger.error(ioe.getMessage());\n }\n }\n }\n return fileData;\n }\n\n public boolean flash(File file) throws IOException {\n // assume stm32 if no target name is specified and file extension is \".bin\"\n if (file.getName().endsWith(\".bin\")) {\n mLogger.info(\"Assuming STM32 for file \" + file.getName() + \".\");\n return flash(file, \"stm32\");\n }\n return flash(file, \"\");\n }\n\n // Method is used by ECT Bootloader!\n public boolean flash(File file, String... targetNames) throws IOException {\n List<FlashTarget> filesToFlash = getFlashTargets(file, targetNames);\n if (filesToFlash.isEmpty()) {\n mLogger.error(\"Found no files to flash.\");\n return false;\n }\n int fileCounter = 0;\n for (FlashTarget ft : filesToFlash) {\n if (!internalFlash(ft, fileCounter, filesToFlash.size())) {\n return false;\n };\n fileCounter++;\n }\n return true;\n }\n\n // package private for tests\n /* package private */ List<FlashTarget> getFlashTargets(File file, String... targetNames) throws IOException {\n List<FlashTarget> filesToFlash = new ArrayList<FlashTarget>();\n\n if (!file.exists()) {\n mLogger.error(file + \" not found.\");\n return filesToFlash;\n }\n\n // check if supplied targetNames are known TargetTypes, if so, continue, else return\n\n if (isZipFile(file)) {\n // unzip\n unzip(file);\n\n // read manifest.json\n File basePath = new File(file.getAbsoluteFile().getParent() + \"/\" + getFileNameWithoutExtension(file));\n File manifestFile = new File(basePath.getAbsolutePath(), MANIFEST_FILENAME);\n if (basePath.exists() && manifestFile.exists()) {\n Manifest mf = null;\n try {\n mf = readManifest(manifestFile);\n } catch (IOException ioe) {\n mLogger.error(\"Error while trying to read manifest file:\\n\" + ioe.getMessage());\n }\n //TODO: improve error handling\n if (mf == null) {\n return filesToFlash;\n }\n Set<String> files = mf.getFiles().keySet();\n\n // iterate over file names in manifest.json\n for (String fileName : files) {\n FirmwareDetails firmwareDetails = mf.getFiles().get(fileName);\n Target t = this.mCload.getTargets().get(TargetTypes.fromString(firmwareDetails.getTarget()));\n if (t != null) {\n // use path to extracted file\n //File flashFile = new File(file.getParent() + \"/\" + file.getName() + \"/\" + fileName);\n File flashFile = new File(basePath.getAbsolutePath(), fileName);\n FlashTarget ft = new FlashTarget(t, readFile(flashFile), firmwareDetails.getType(), t.getStartPage()); //TODO: does startPage HAVE to be an extra argument!? (it's already included in Target)\n // add flash target\n // if no target names are specified, flash everything\n if (targetNames == null || targetNames.length == 0 || targetNames[0].isEmpty()) {\n // deal with different platforms (CF1, CF2)\n // TODO: simplify\n if (t.getFlashPages() == 128 && \"cf1\".equalsIgnoreCase(firmwareDetails.getPlatform())) { //128 = CF 1.0\n filesToFlash.add(ft);\n // deal with STM32 and NRF51 for CF2 (different no of flash pages)\n } else if ((t.getFlashPages() == 1024 || t.getFlashPages() == 232) && \"cf2\".equalsIgnoreCase(firmwareDetails.getPlatform())) { //1024 = CF 2.0\n filesToFlash.add(ft);\n }\n } else {\n // else flash only files whose targets are contained in targetNames\n if (Arrays.asList(targetNames).contains(firmwareDetails.getTarget())) {\n filesToFlash.add(ft);\n }\n }\n } else {\n mLogger.error(\"No target found for \" + firmwareDetails.getTarget());\n }\n }\n } else {\n mLogger.error(\"Zip file \" + file.getName() + \" does not include a \" + MANIFEST_FILENAME);\n }\n } else { // File is not a Zip file\n // add single flash target\n if (targetNames == null || targetNames.length != 1) {\n mLogger.error(\"Not an archive, must supply ONE target to flash.\");\n } else {\n for (String tn : targetNames) {\n if (!tn.isEmpty()) {\n Target target = this.mCload.getTargets().get(TargetTypes.fromString(tn));\n FlashTarget ft = new FlashTarget(target, readFile(file), \"binary\", target.getStartPage());\n filesToFlash.add(ft);\n }\n }\n }\n }\n return filesToFlash;\n }\n\n private void unzip(File zipFile) {\n mLogger.debug(\"Trying to unzip \" + zipFile + \"...\");\n InputStream fis = null;\n ZipInputStream zis = null;\n FileOutputStream fos = null;\n String parent = zipFile.getAbsoluteFile().getParent();\n\n try {\n fis = new FileInputStream(zipFile);\n zis = new ZipInputStream(new BufferedInputStream(fis));\n ZipEntry ze;\n while ((ze = zis.getNextEntry()) != null) {\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n byte[] buffer = new byte[1024];\n int count;\n while ((count = zis.read(buffer)) != -1) {\n baos.write(buffer, 0, count);\n }\n String filename = ze.getName();\n byte[] bytes = baos.toByteArray();\n // write files\n File filePath = new File(parent + \"/\" + getFileNameWithoutExtension(zipFile) + \"/\" + filename);\n // create subdir\n filePath.getParentFile().mkdirs();\n fos = new FileOutputStream(filePath);\n fos.write(bytes);\n //check\n if(filePath.exists() && filePath.length() > 0) {\n mLogger.debug(filename + \" successfully extracted to \" + filePath.getAbsolutePath());\n } else {\n mLogger.error(filename + \" was not extracted.\");\n }\n }\n } catch (FileNotFoundException ffe) {\n mLogger.error(ffe.getMessage());\n } catch (IOException ioe) {\n mLogger.error(ioe.getMessage());\n } finally {\n if (zis != null) {\n try {\n zis.close();\n } catch (IOException e) {\n mLogger.error(e.getMessage());\n }\n }\n if (fos != null) {\n try {\n fos.close();\n } catch (IOException e) {\n mLogger.error(e.getMessage());\n }\n }\n\n }\n }\n\n private static String getFileNameWithoutExtension (File file) {\n return file.getName().substring(0, file.getName().length()-4);\n }\n\n /**\n * Basic check if a file is a Zip file\n *\n * @param file potential zip file\n * @return true if file is a Zip file, false otherwise\n */\n //TODO: how can this be improved?\n private boolean isZipFile(File file) {\n if (file != null && file.exists() && file.getName().endsWith(\".zip\")) {\n ZipFile zf = null;\n try {\n zf = new ZipFile(file);\n return zf.size() > 0;\n } catch (ZipException e) {\n mLogger.error(e.getMessage());\n } catch (IOException e) {\n mLogger.error(e.getMessage());\n } finally {\n if (zf != null) {\n try {\n zf.close();\n } catch (IOException e) {\n mLogger.error(e.getMessage());\n }\n }\n }\n }\n return false;\n }\n\n /**\n * Reset to firmware depending on protocol version\n *\n * @return true if successful, false otherwise\n */\n public boolean resetToFirmware() {\n int targetType = -1;\n if (this.mCload.getProtocolVersion() == BootVersion.CF2_PROTO_VER) {\n targetType = TargetTypes.NRF51;\n } else {\n targetType = TargetTypes.STM32;\n }\n return this.mCload.resetToFirmware(targetType);\n }\n\n public void close() {\n mLogger.debug(\"Bootloader close()\");\n if (this.mCload != null) {\n this.mCload.close();\n }\n }\n\n private boolean internalFlash(FlashTarget target) {\n return internalFlash(target, 1, 1);\n }\n\n // def _internal_flash(self, target, current_file_number=1, total_files=1):\n private boolean internalFlash(FlashTarget flashTarget, int currentFileNo, int totalFiles) {\n Target t_data = flashTarget.getTarget();\n byte[] image = flashTarget.getData();\n int pageSize = t_data.getPageSize();\n int startPage = flashTarget.getStartPage();\n\n String flashingTo = \"Flashing to \" + TargetTypes.toString(t_data.getId()) + \" (\" + flashTarget.getType() + \")\";\n mLogger.info(flashingTo);\n notifyUpdateStatus(flashingTo);\n\n //if len(image) > ((t_data.flash_pages - start_page) * t_data.page_size):\n if (image.length > ((t_data.getFlashPages() - startPage) * pageSize)) {\n mLogger.error(\"Error: Not enough space to flash the image file.\");\n //raise Exception()\n return false;\n }\n\n int noOfPages = (image.length / pageSize) + 1;\n mLogger.info(image.length - 1 + \" bytes (\" + noOfPages + \" pages) \");\n\n // For each page\n int bufferCounter = 0; // Buffer counter\n int i = 0;\n for (i = 0; i < ((image.length - 1) / pageSize) + 1; i++) {\n // Load the buffer\n int end = 0;\n if (((i + 1) * pageSize) > image.length) {\n //buff = image[i * t_data.page_size:]\n end = image.length;\n } else {\n //buff = image[i * t_data.page_size:(i + 1) * t_data.page_size])\n end = (i + 1) * pageSize;\n }\n byte[] buffer = Arrays.copyOfRange(image, i * pageSize, end);\n\n notifyUpdateProgress(i+1, noOfPages);\n\n if (isCancelled()) {\n break;\n }\n\n this.mCload.uploadBuffer(t_data.getId(), bufferCounter, 0, buffer);\n\n bufferCounter++;\n\n // Flash when the complete buffers are full\n if (bufferCounter >= t_data.getBufferPages()) {\n String buffersFull = \"Flashing page \" + (i+1) + \"...\";\n mLogger.info(buffersFull);\n notifyUpdateStatus(buffersFull);\n notifyUpdateProgress(i+1, noOfPages);\n if (!this.mCload.writeFlash(t_data.getId(), 0, startPage + i - (bufferCounter - 1), bufferCounter)) {\n handleFlashError();\n //raise Exception()\n return false;\n }\n bufferCounter = 0;\n }\n }\n if (isCancelled()) {\n mLogger.info(\"Flashing cancelled!\");\n return false;\n }\n if (bufferCounter > 0) {\n mLogger.info(\"BufferCounter: \" + bufferCounter);\n notifyUpdateProgress(i, noOfPages);\n if (!this.mCload.writeFlash(t_data.getId(), 0, (startPage + ((image.length - 1) / pageSize)) - (bufferCounter - 1), bufferCounter)) {\n handleFlashError();\n //raise Exception()\n return false;\n }\n }\n mLogger.info(\"Flashing done!\");\n notifyUpdateStatus(\"Flashing done!\");\n return true;\n }\n\n private boolean isCancelled() {\n return mCancelled;\n }\n\n public void cancel() {\n this.mCancelled = true;\n if (mCload != null) {\n mCload.cancel();\n }\n }\n\n private void handleFlashError() {\n String errorMessage = \"Error during flash operation (\" + this.mCload.getErrorMessage() + \"). Maybe wrong radio link?\";\n mLogger.error(errorMessage);\n notifyUpdateError(errorMessage);\n }\n\n\n /* Bootloader listener */\n\n public void addBootloaderListener(BootloaderListener bl) {\n this.mBootloaderListeners.add(bl);\n }\n\n public void removeBootloaderListener(BootloaderListener bl) {\n this.mBootloaderListeners.remove(bl);\n }\n\n private void notifyUpdateProgress(int progress, int max) {\n for (BootloaderListener bootloaderListener : mBootloaderListeners) {\n bootloaderListener.updateProgress(progress, max);\n }\n }\n\n private void notifyUpdateStatus(String status) {\n for (BootloaderListener bootloaderListener : mBootloaderListeners) {\n bootloaderListener.updateStatus(status);\n }\n }\n\n private void notifyUpdateError(String error) {\n for (BootloaderListener bootloaderListener : mBootloaderListeners) {\n bootloaderListener.updateError(error);\n }\n }\n\n public interface BootloaderListener {\n\n public void updateProgress(int progress, int max);\n\n public void updateStatus(String status);\n\n public void updateError(String error);\n\n }\n\n /* package private */ class FlashTarget {\n\n private Target mTarget;\n private byte[] mData = new byte[0];\n private String mType = \"\";\n private int mStartPage;\n\n public FlashTarget(Target target, byte[] data, String type, int startPage) {\n this.mTarget = target;\n this.mData = data;\n this.mType = type;\n this.mStartPage = startPage;\n }\n\n public byte[] getData() {\n return mData;\n }\n\n public Target getTarget() {\n return mTarget;\n }\n\n public int getStartPage() {\n return mStartPage;\n }\n\n public String getType() {\n return mType;\n }\n\n @Override\n public String toString() {\n return \"FlashTarget [target ID=\" + TargetTypes.toString(mTarget.getId()) + \", data.length=\" + mData.length + \", type=\" + mType + \", startPage=\" + mStartPage + \"]\";\n }\n\n }\n\n public static Manifest readManifest (File file) throws IOException {\n String errorMessage = \"\";\n try {\n return mMapper.readValue(file, Manifest.class);\n } catch (JsonParseException jpe) {\n errorMessage = jpe.getMessage();\n } catch (JsonMappingException jme) {\n errorMessage = jme.getMessage();\n }\n LoggerFactory.getLogger(\"Bootloader\").error(\"Error while parsing manifest \" + file.getName() + \": \" + errorMessage);\n return null;\n }\n\n public static void writeManifest (String fileName, Manifest manifest) throws IOException {\n String errorMessage = \"\";\n mMapper.enable(SerializationFeature.INDENT_OUTPUT);\n try {\n mMapper.writeValue(new File(fileName), manifest);\n return;\n } catch (JsonGenerationException jge) {\n errorMessage = jge.getMessage();\n } catch (JsonMappingException jme) {\n errorMessage = jme.getMessage();\n }\n LoggerFactory.getLogger(\"Bootloader\").error(\"Could not save manifest to file \" + fileName + \".\\n\" + errorMessage);\n }\n}",
"public interface BootloaderListener {\n\n public void updateProgress(int progress, int max);\n\n public void updateStatus(String status);\n\n public void updateError(String error);\n\n}",
"public class FirmwareRelease implements Comparable<FirmwareRelease> {\n\n private String mTagName;\n private String mName;\n private String mCreatedAt;\n\n private String mAssetName;\n private int mSize;\n private String mBrowserDownloadUrl;\n private String mReleaseNotes;\n\n private final SimpleDateFormat inputFormatter = new SimpleDateFormat(\"yyyy-MM-dd'T'HH:mm:ss'Z'\", Locale.US);\n private final SimpleDateFormat outputFormatter = new SimpleDateFormat(\"yyyy-MM-dd\", Locale.US);\n\n public FirmwareRelease() {\n }\n\n public FirmwareRelease(String tagName, String name, String createdAt) {\n this.mTagName = tagName;\n this.mName = name;\n\n try {\n Date date = inputFormatter.parse(createdAt);\n this.mCreatedAt = outputFormatter.format(date);\n } catch (ParseException e) {\n this.mCreatedAt = createdAt;\n }\n }\n\n public String getTagName() {\n return mTagName;\n }\n\n public String getName() {\n return mName;\n }\n\n public String getCreatedAt() {\n return mCreatedAt;\n }\n\n public void setAsset(String assetName, int assetSize, String URL) {\n this.mAssetName = assetName;\n this.mSize = assetSize;\n this.mBrowserDownloadUrl = URL;\n }\n\n public String getAssetName() {\n return mAssetName;\n }\n\n public int getAssetSize() {\n return mSize;\n }\n\n public String getBrowserDownloadUrl() {\n return mBrowserDownloadUrl;\n }\n\n public void setReleaseNotes(String releaseNotes) {\n this.mReleaseNotes = releaseNotes;\n }\n\n public String getReleaseNotes() {\n return mReleaseNotes;\n }\n\n public String getType() {\n // TODO: make this more reliable\n String lcAssetName = mAssetName.toLowerCase(Locale.US);\n if (lcAssetName.startsWith(\"cf1\") || lcAssetName.startsWith(\"crazyflie1\")) {\n return \"CF1\";\n } else if (lcAssetName.startsWith(\"cf2\") || lcAssetName.startsWith(\"crazyflie2\") || lcAssetName.startsWith(\"cflie2\") || lcAssetName.startsWith(\"firmware-cf2\")) {\n return \"CF2\";\n } else if (lcAssetName.startsWith(\"crazyflie-\")) {\n return \"CF1 & CF2\";\n } else if (lcAssetName.startsWith(\"firmware-tag\")) {\n return \"TAG\";\n } else {\n return \"Unknown\";\n }\n }\n\n @Override\n public String toString() {\n return \"Firmware [mTagName=\" + mTagName + \", mName=\" + mName + \", mCreatedAt=\" + mCreatedAt + \"]\";\n }\n\n @Override\n public int compareTo(FirmwareRelease another) {\n return this.mTagName.compareTo(another.getTagName());\n }\n\n}",
"public class RadioDriver extends CrtpDriver {\n\n private final static Logger mLogger = LoggerFactory.getLogger(\"RadioDriver\");\n\n private Crazyradio mCradio;\n private Thread mRadioDriverThread;\n\n private CrazyUsbInterface mUsbInterface;\n\n private final BlockingQueue<CrtpPacket> mOutQueue = new LinkedBlockingQueue<CrtpPacket>();\n //TODO: Limit size of out queue to avoid \"ReadBack\" effect?\n private final BlockingQueue<CrtpPacket> mInQueue = new LinkedBlockingQueue<CrtpPacket>();\n\n private ConnectionData mConnectionData;\n \n /**\n * Create the link driver\n */\n public RadioDriver(CrazyUsbInterface usbInterface) {\n this.mUsbInterface = usbInterface;\n this.mCradio = null;\n this.mRadioDriverThread = null;\n }\n\n /* (non-Javadoc)\n * @see se.bitcraze.crazyflie.lib.crtp.CrtpDriver#connect()\n */\n public void connect() {\n if (this.mConnectionData == null) {\n throw new IllegalStateException(\"ConnectionData must be set before attempting to connect to Crazyradio.\");\n }\n if(mCradio == null) {\n notifyConnectionRequested();\n// try {\n// mUsbInterface.initDevice(Crazyradio.CRADIO_VID, Crazyradio.CRADIO_PID);\n// } catch (IOException e) {\n// throw new IOException(\"Make sure that the Crazyradio (PA) is connected.\");\n// }\n this.mCradio = new Crazyradio(mUsbInterface);\n } else {\n mLogger.error(\"Crazyradio already open\");\n }\n\n /*\n if self.cradio is None:\n self.cradio = Crazyradio(devid=int(uri_data.group(1)))\n else:\n raise Exception(\"Link already open!\")\n */\n\n if (this.mCradio.getVersion() >= 0.4) {\n this.mCradio.setArc(10);\n } else {\n mLogger.warn(\"Radio version <0.4 will be obsolete soon!\");\n }\n\n this.mCradio.setChannel(mConnectionData.getChannel());\n this.mCradio.setDatarate(mConnectionData.getDataRate());\n\n /*\n if uri_data.group(9):\n addr = \"{:X}\".format(int(uri_data.group(9)))\n new_addr = struct.unpack(\"<BBBBB\", binascii.unhexlify(addr))\n self.cradio.set_address(new_addr)\n */\n\n // Launch the comm thread\n startSendReceiveThread();\n }\n\n /**\n * Sets the connection data (channel and data rate)\n * \n * @param connectionData channel and data rate\n */\n public void setConnectionData(ConnectionData connectionData) {\n this.mConnectionData = connectionData;\n }\n\n /*\n * Receive a packet though the link. This call is blocking but will\n * timeout and return None if a timeout is supplied.\n */\n @Override\n public CrtpPacket receivePacket(int time) {\n try {\n return mInQueue.poll((long) time, TimeUnit.SECONDS);\n } catch (InterruptedException e) {\n mLogger.error(\"InterruptedException: \" + e.getMessage());\n return null;\n }\n }\n\n /*\n * Send the packet though the link\n *\n * (non-Javadoc)\n * @see cflib.crtp.CrtpDriver#sendPacket(cflib.crtp.CrtpPacket)\n */\n @Override\n public void sendPacket(CrtpPacket packet) {\n if (this.mCradio == null) {\n return;\n }\n\n //TODO: does it make sense to be able to queue packets even though\n //the connection is not established yet?\n\n /*\n try:\n self.out_queue.put(pk, True, 2)\n except Queue.Full:\n if self.link_error_callback:\n self.link_error_callback(\"RadioDriver: Could not send packet to copter\")\n */\n\n // this.mOutQueue.addLast(packet);\n try {\n this.mOutQueue.put(packet);\n } catch (InterruptedException e) {\n mLogger.error(\"InterruptedException: \" + e.getMessage());\n }\n }\n\n /*\n * Close the link.\n *\n * (non-Javadoc)\n * @see cflib.crtp.CrtpDriver#close()\n */\n @Override\n public void disconnect() {\n mLogger.debug(\"disconnect()\");\n // Stop the comm thread\n stopSendReceiveThread();\n // Avoid NPE because packets are still processed\n try {\n Thread.sleep(100);\n } catch (InterruptedException e) {\n mLogger.error(\"Interrupted during disconnect: \" + e.getMessage());\n }\n if(this.mCradio != null) {\n this.mCradio.disconnect();\n this.mCradio = null;\n }\n notifyDisconnected();\n }\n\n public List<ConnectionData> scanInterface() {\n return scanInterface(mCradio, mUsbInterface);\n }\n\n /**\n * Scan interface for Crazyflies\n */\n private static List<ConnectionData> scanInterface(Crazyradio crazyRadio, CrazyUsbInterface crazyUsbInterface) {\n List<ConnectionData> connectionDataList = new ArrayList<ConnectionData>();\n\n if(crazyRadio == null) {\n crazyRadio = new Crazyradio(crazyUsbInterface);\n } else {\n mLogger.error(\"Cannot scan for links while the link is open!\");\n //TODO: throw exception?\n }\n\n mLogger.info(\"Found Crazyradio with version \" + crazyRadio.getVersion() + \" and serial number \" + crazyRadio.getSerialNumber());\n\n crazyRadio.setArc(1);\n\n// crazyRadio.setDataRate(CrazyradioLink.DR_250KPS);\n// List<Integer> scanRadioChannels250k = crazyRadio.scanChannels();\n// for(Integer channel : scanRadioChannels250k) {\n// connectionDataList.add(new ConnectionData(channel, CrazyradioLink.DR_250KPS));\n// }\n// crazyRadio.setDataRate(CrazyradioLink.DR_1MPS);\n// List<Integer> scanRadioChannels1m = crazyRadio.scanChannels();\n// for(Integer channel : scanRadioChannels1m) {\n// connectionDataList.add(new ConnectionData(channel, CrazyradioLink.DR_1MPS));\n// }\n// crazyRadio.setDataRate(CrazyradioLink.DR_2MPS);\n// List<Integer> scanRadioChannels2m = crazyRadio.scanChannels();\n// for(Integer channel : scanRadioChannels2m) {\n// connectionDataList.add(new ConnectionData(channel, CrazyradioLink.DR_2MPS));\n// }\n\n try {\n connectionDataList = Arrays.asList(crazyRadio.scanChannels());\n } catch (IOException e) {\n mLogger.error(e.getMessage());\n }\n\n// crazyRadio.close();\n// crazyRadio = null;\n\n return connectionDataList;\n }\n\n public boolean scanSelected(ConnectionData connectionData, byte[] packet) {\n if (mCradio == null) {\n mCradio = new Crazyradio(mUsbInterface);\n }\n return mCradio.scanSelected(connectionData.getChannel(), connectionData.getDataRate(), packet);\n }\n\n public boolean setBootloaderAddress(byte[] newAddress) {\n if (newAddress.length != 5) {\n mLogger.error(\"Radio address should be 5 bytes long\");\n return false;\n }\n // self.link.pause()\n stopSendReceiveThread();\n\n int SET_BOOTLOADER_ADDRESS = 0x11; // Only implemented on Crazyflie version 0x00\n //TODO: is there a more elegant way to do this?\n //pkdata = (0xFF, 0xFF, 0x11) + tuple(new_address)\n byte[] pkData = new byte[newAddress.length + 3];\n pkData[0] = (byte) 0xFF;\n pkData[1] = (byte) 0xFF;\n pkData[2] = (byte) SET_BOOTLOADER_ADDRESS;\n System.arraycopy(newAddress, 0, pkData, 3, newAddress.length);\n\n for (int i = 0; i < 10; i++) {\n mLogger.debug(\"Trying to set new radio address\");\n //self.link.cradio.set_address((0xE7,) * 5)\n mCradio.setAddress(new byte[]{(byte) 0xE7, (byte) 0xE7, (byte) 0xE7, (byte) 0xE7, (byte) 0xE7});\n mCradio.sendPacket(pkData);\n //self.link.cradio.set_address(tuple(new_address))\n mCradio.setAddress(newAddress);\n //if self.link.cradio.send_packet((0xff,)).ack:\n RadioAck ack = mCradio.sendPacket(new byte[] {(byte) 0xFF});\n if (ack != null) {\n mLogger.info(\"Bootloader set to radio address \" + Utilities.getHexString(newAddress));\n startSendReceiveThread();\n return true;\n }\n }\n //this.mDriver.restart();\n startSendReceiveThread();\n return false;\n }\n\n private void startSendReceiveThread() {\n if (mRadioDriverThread == null) {\n //self._thread = _RadioDriverThread(self.cradio, self.in_queue, self.out_queue, link_quality_callback, link_error_callback)\n RadioDriverThread rDT = new RadioDriverThread();\n mRadioDriverThread = new Thread(rDT);\n mRadioDriverThread.start();\n }\n }\n\n private void stopSendReceiveThread() {\n if (this.mRadioDriverThread != null) {\n this.mRadioDriverThread.interrupt();\n this.mRadioDriverThread = null;\n }\n }\n\n /**\n * Radio link receiver thread is used to read data from the Crazyradio USB driver.\n */\n private class RadioDriverThread implements Runnable {\n\n final Logger mLogger = LoggerFactory.getLogger(this.getClass().getSimpleName());\n\n private final static int RETRYCOUNT_BEFORE_DISCONNECT = 10;\n private int mRetryBeforeDisconnect;\n\n /**\n * Create the object\n */\n public RadioDriverThread() {\n this.mRetryBeforeDisconnect = RETRYCOUNT_BEFORE_DISCONNECT;\n }\n\n /**\n * Run the receiver thread\n *\n * (non-Javadoc)\n * @see java.lang.Runnable#run()\n */\n public void run() {\n byte[] dataOut = Crazyradio.NULL_PACKET;\n\n double waitTime = 0;\n int emptyCtr = 0;\n\n while(mCradio != null && !Thread.currentThread().isInterrupted()) {\n try {\n\n /*\n try:\n ackStatus = self.cradio.send_packet(dataOut)\n except Exception as e:\n import traceback\n self.link_error_callback(\"Error communicating with crazy radio\"\n \" ,it has probably been unplugged!\\n\"\n \"Exception:%s\\n\\n%s\" % (e,\n traceback.format_exc()))\n */\n RadioAck ackStatus = mCradio.sendPacket(dataOut);\n\n // Analyze the data packet\n if (ackStatus == null) {\n notifyConnectionLost(\"Dongle communication error (ackStatus == null)\");\n mLogger.warn(\"Dongle communication error (ackStatus == null)\");\n continue;\n }\n\n notifyLinkQualityUpdated((10 - ackStatus.getRetry()) * 10);\n\n // If no copter, retry\n //TODO: how is this actually possible?\n if (!ackStatus.isAck()) {\n this.mRetryBeforeDisconnect--;\n if (this.mRetryBeforeDisconnect == 0) {\n notifyConnectionLost(\"Too many packets lost\");\n mLogger.warn(\"Too many packets lost\");\n }\n continue;\n }\n this.mRetryBeforeDisconnect = RETRYCOUNT_BEFORE_DISCONNECT;\n\n byte[] data = ackStatus.getData();\n\n // if there is a copter in range, the packet is analyzed and the next packet to send is prepared\n if (data != null && data.length > 0) {\n CrtpPacket inPacket = new CrtpPacket(data);\n mInQueue.put(inPacket);\n\n waitTime = 0;\n emptyCtr = 0;\n } else {\n emptyCtr += 1;\n if (emptyCtr > 10) {\n emptyCtr = 10;\n // Relaxation time if the last 10 packets where empty\n waitTime = 0.01;\n } else {\n waitTime = 0;\n }\n }\n\n // get the next packet to send after relaxation (wait 10ms)\n CrtpPacket outPacket = mOutQueue.poll((long) waitTime, TimeUnit.SECONDS);\n\n if (outPacket != null) {\n dataOut = outPacket.toByteArray();\n } else {\n dataOut = Crazyradio.NULL_PACKET;\n }\n// Thread.sleep(10);\n } catch (InterruptedException e) {\n mLogger.debug(\"RadioDriverThread was interrupted.\");\n notifyLinkQualityUpdated(0);\n break;\n }\n }\n\n }\n }\n\n @Override\n public boolean isConnected() {\n return this.mRadioDriverThread != null;\n }\n\n}",
"public class MainActivity extends Activity {\n\n private static final String LOG_TAG = \"CrazyflieControl\";\n private static final int MY_PERMISSIONS_REQUEST_LOCATION = 42;\n\n private JoystickView mJoystickViewLeft;\n private JoystickView mJoystickViewRight;\n private FlightDataView mFlightDataView;\n\n private ScrollView mConsoleScrollView;\n private TextView mConsoleTextView;\n\n private SharedPreferences mPreferences;\n\n private IController mController;\n private GamepadController mGamepadController;\n\n private String mRadioChannelDefaultValue;\n private String mRadioDatarateDefaultValue;\n\n private boolean mDoubleBackToExitPressedOnce = false;\n private Controls mControls;\n private SoundPool mSoundPool;\n private boolean mLoaded;\n private int mSoundConnect;\n private int mSoundDisconnect;\n\n private ImageButton mToggleConnectButton;\n private ImageButton mRingEffectButton;\n private ImageButton mHeadlightButton;\n private ImageButton mBuzzerSoundButton;\n private File mCacheDir;\n\n private TextView mTextView_battery;\n private TextView mTextView_linkQuality;\n private MainPresenter mPresenter;\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n mPresenter = new MainPresenter(this);\n\n setDefaultPreferenceValues();\n\n mTextView_battery = (TextView) findViewById(R.id.battery_text);\n mTextView_linkQuality = (TextView) findViewById(R.id.linkQuality_text);\n\n setBatteryLevel(-1.0f);\n setLinkQualityText(\"N/A\");\n\n mControls = new Controls(this, mPreferences);\n mControls.setDefaultPreferenceValues(getResources());\n\n //Default controller\n mJoystickViewLeft = (JoystickView) findViewById(R.id.joystick_left);\n mJoystickViewRight = (JoystickView) findViewById(R.id.joystick_right);\n mJoystickViewRight.setLeft(false);\n mController = new TouchController(mControls, this, mJoystickViewLeft, mJoystickViewRight);\n\n //initialize gamepad controller\n mGamepadController = new GamepadController(mControls, this, mPreferences);\n mGamepadController.setDefaultPreferenceValues(getResources());\n\n //initialize buttons\n mToggleConnectButton = (ImageButton) findViewById(R.id.imageButton_connect);\n initializeMenuButtons();\n\n mFlightDataView = (FlightDataView) findViewById(R.id.flightdataview);\n\n mConsoleScrollView = (ScrollView) findViewById(R.id.console_scrollView);\n mConsoleTextView = (TextView) findViewById(R.id.console_textView);\n registerForContextMenu(mConsoleTextView);\n\n //action buttons\n mRingEffectButton = (ImageButton) findViewById(R.id.button_ledRing);\n mHeadlightButton = (ImageButton) findViewById(R.id.button_headLight);\n mBuzzerSoundButton = (ImageButton) findViewById(R.id.button_buzzerSound);\n\n IntentFilter filter = new IntentFilter();\n filter.addAction(this.getPackageName()+\".USB_PERMISSION\");\n filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);\n filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);\n registerReceiver(mUsbReceiver, filter);\n\n initializeSounds();\n\n setCacheDir();\n }\n\n private void initializeSounds() {\n this.setVolumeControlStream(AudioManager.STREAM_MUSIC);\n // Load sounds\n mSoundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);\n mSoundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {\n @Override\n public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {\n mLoaded = true;\n }\n });\n mSoundConnect = mSoundPool.load(this, R.raw.proxima, 1);\n mSoundDisconnect = mSoundPool.load(this, R.raw.tejat, 1);\n }\n\n private void setCacheDir() {\n if (isExternalStorageWriteable()) {\n Log.d(LOG_TAG, \"External storage is writeable.\");\n if (mCacheDir == null) {\n File appDir = getApplicationContext().getExternalFilesDir(null);\n mCacheDir = new File(appDir, \"TOC_cache\");\n mCacheDir.mkdirs();\n }\n } else {\n Log.d(LOG_TAG, \"External storage is not writeable.\");\n mCacheDir = null;\n }\n }\n\n private boolean isExternalStorageWriteable() {\n String state = Environment.getExternalStorageState();\n return Environment.MEDIA_MOUNTED.equals(state);\n }\n\n private void setDefaultPreferenceValues(){\n // Set default preference values\n PreferenceManager.setDefaultValues(this, R.xml.preferences, false);\n // Initialize preferences\n mPreferences = PreferenceManager.getDefaultSharedPreferences(this);\n\n mRadioChannelDefaultValue = getString(R.string.preferences_radio_channel_defaultValue);\n mRadioDatarateDefaultValue = getString(R.string.preferences_radio_datarate_defaultValue);\n }\n\n private void checkScreenLock() {\n boolean isScreenLock = mPreferences.getBoolean(PreferencesActivity.KEY_PREF_SCREEN_ROTATION_LOCK_BOOL, false);\n if(isScreenLock){\n this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);\n } else{\n this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);\n }\n }\n\n private void checkConsole() {\n boolean showConsole = mPreferences.getBoolean(PreferencesActivity.KEY_PREF_SHOW_CONSOLE_BOOL, false);\n if (showConsole) {\n mConsoleScrollView.setVisibility(View.VISIBLE);\n } else {\n mConsoleScrollView.setVisibility(View.INVISIBLE);\n }\n }\n\n private void initializeMenuButtons() {\n mToggleConnectButton.setOnClickListener(new View.OnClickListener() {\n\n @Override\n public void onClick(View v) {\n\n try {\n if (mPresenter != null && mPresenter.getCrazyflie() != null && mPresenter.getCrazyflie().isConnected()) {\n mPresenter.disconnect();\n } else {\n // TODO: FIXME\n if(isCrazyradioAvailable(MainActivity.this)) {\n connectCrazyradio();\n } else {\n connectBlePreChecks();\n }\n }\n } catch (IllegalStateException e) {\n Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();\n }\n }\n });\n\n ImageButton settingsButton = (ImageButton) findViewById(R.id.imageButton_settings);\n settingsButton.setOnClickListener(new View.OnClickListener() {\n\n @Override\n public void onClick(View v) {\n Intent intent = new Intent(MainActivity.this, PreferencesActivity.class);\n startActivity(intent);\n }\n });\n }\n\n private void connectCrazyradio() {\n int radioChannel = Integer.parseInt(mPreferences.getString(PreferencesActivity.KEY_PREF_RADIO_CHANNEL, mRadioChannelDefaultValue));\n int radioDatarate = Integer.parseInt(mPreferences.getString(PreferencesActivity.KEY_PREF_RADIO_DATARATE, mRadioDatarateDefaultValue));\n mPresenter.connectCrazyradio(radioChannel, radioDatarate, mCacheDir);\n }\n\n private void connectBlePreChecks() {\n // Check if Bluetooth LE is supported by the Android version\n if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {\n Log.e(LOG_TAG, Build.VERSION.SDK_INT + \"does not support Bluetooth LE.\");\n Toast.makeText(this, Build.VERSION.SDK_INT + \"does not support Bluetooth LE. Please use a Crazyradio to connect to the Crazyflie instead.\", Toast.LENGTH_LONG).show();\n return;\n }\n // Check if Bluetooth LE is supported by the hardware\n if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {\n Log.e(LOG_TAG, \"Device does not support Bluetooth LE.\");\n Toast.makeText(this, \"Device does not support Bluetooth LE. Please use a Crazyradio to connect to the Crazyflie instead.\", Toast.LENGTH_LONG).show();\n return;\n }\n // Since Android version 6, ACCESS_COARSE_LOCATION is required for Bluetooth scanning\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {\n Log.e(LOG_TAG, \"Android version >= 6 requires ACCESS_COARSE_LOCATION permissions for Bluetooth scanning.\");\n requestPermissions(Manifest.permission.ACCESS_COARSE_LOCATION, MY_PERMISSIONS_REQUEST_LOCATION);\n } else {\n connectBle();\n }\n }\n\n private void connectBle() {\n boolean writeWithResponse = mPreferences.getBoolean(PreferencesActivity.KEY_PREF_BLATENCY_BOOL, false);\n Log.d(LOG_TAG, \"Using bluetooth write with response - \" + writeWithResponse);\n mPresenter.connectBle(writeWithResponse, mCacheDir);\n }\n\n private void checkLocationSettings() {\n LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);\n boolean isEnabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER);\n if (!isEnabled) {\n final AlertDialog.Builder builder = new AlertDialog.Builder(this);\n builder.setTitle(\"Location Access\");\n builder.setMessage(\"The app needs location access for Bluetooth scanning. Please enable it in the settings menu.\");\n builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {\n @Override\n public void onClick(DialogInterface dialogInterface, int i) {\n Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);\n startActivity(intent);\n }\n });\n builder.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {\n @Override\n public void onClick(DialogInterface dialogInterface, int i) {\n Log.d(LOG_TAG, \"Location access request has been denied.\");\n }\n });\n builder.show();\n } else {\n connectBle();\n }\n\n }\n\n private void requestPermissions(String permission, int request) {\n if (ContextCompat.checkSelfPermission(MainActivity.this, permission) != PackageManager.PERMISSION_GRANTED) {\n // Permission is not granted. Should we show an explanation?\n if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, permission)) {\n // Show an explanation to the user *asynchronously* -- don't block this thread waiting for the user's response!\n // After the user sees the explanation, try again to request the permission.\n Log.d(LOG_TAG, \"ACCESS_COARSE_LOCATION permission request has been denied.\");\n //Toast.makeText(this, \"Android version >= 6 requires ACCESS_COARSE_LOCATION permissions for Bluetooth scanning.\", Toast.LENGTH_LONG).show();\n ActivityCompat.requestPermissions(MainActivity.this, new String[]{permission}, request);\n } else {\n ActivityCompat.requestPermissions(MainActivity.this, new String[]{permission}, request);\n }\n } else {\n // Permission has already been granted\n checkLocationSettings();\n }\n }\n\n @Override\n public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {\n switch (requestCode) {\n case MY_PERMISSIONS_REQUEST_LOCATION: {\n // If request is cancelled, the result arrays are empty.\n if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {\n // permission was granted, yay! Do the contacts-related task you need to do.\n checkLocationSettings();\n } else {\n // permission denied, boo! Disable the functionality that depends on this permission.\n Log.d(LOG_TAG, \"ACCESS_COARSE_LOCATION permission request has been denied.\");\n Toast.makeText(this, \"Android version >= 6 requires ACCESS_COARSE_LOCATION permissions for Bluetooth scanning.\", Toast.LENGTH_LONG).show();\n }\n }\n }\n }\n\n @Override\n public void onResume() {\n super.onResume();\n //TODO: improve\n PreferencesActivity.setDefaultJoystickSize(this);\n mJoystickViewLeft.setPreferences(mPreferences);\n mJoystickViewRight.setPreferences(mPreferences);\n mControls.setControlConfig();\n mGamepadController.setControlConfig();\n resetInputMethod();\n checkScreenLock();\n checkConsole();\n //disable action buttons\n mRingEffectButton.setEnabled(false);\n mHeadlightButton.setEnabled(false);\n mBuzzerSoundButton.setEnabled(false);\n if (mPreferences.getBoolean(PreferencesActivity.KEY_PREF_IMMERSIVE_MODE_BOOL, false)) {\n setHideyBar();\n }\n //mJoystickViewLeft.requestLayout();\n }\n\n @Override\n protected void onRestart() {\n super.onRestart();\n }\n\n @Override\n protected void onPause() {\n super.onPause();\n Log.d(LOG_TAG, \"onPause()\");\n if (mControls != null) {\n mControls.resetAxisValues();\n }\n if (mController != null) {\n mController.disable();\n }\n updateFlightData();\n mPresenter.disconnect();\n }\n\n @Override\n protected void onDestroy() {\n Log.d(LOG_TAG, \"onDestroy()\");\n unregisterReceiver(mUsbReceiver);\n mSoundPool.release();\n mSoundPool = null;\n mPresenter.onDestroy();\n super.onDestroy();\n }\n\n @Override\n public void onBackPressed() {\n if (mDoubleBackToExitPressedOnce) {\n super.onBackPressed();\n return;\n }\n this.mDoubleBackToExitPressedOnce = true;\n Toast.makeText(this, \"Please click BACK again to exit\", Toast.LENGTH_SHORT).show();\n new Handler().postDelayed(new Runnable() {\n\n @Override\n public void run() {\n mDoubleBackToExitPressedOnce = false;\n\n }\n }, 2000);\n }\n\n @Override\n public void onWindowFocusChanged(boolean hasFocus) {\n super.onWindowFocusChanged(hasFocus);\n if(mPreferences.getBoolean(PreferencesActivity.KEY_PREF_IMMERSIVE_MODE_BOOL, false) && hasFocus){\n new Handler().postDelayed(new Runnable() {\n @Override\n public void run() {\n setHideyBar();\n }\n }, 2000);\n }\n }\n\n @Override\n public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {\n if (v.getId() == R.id.console_textView) {\n AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;\n menu.add(Menu.NONE, 0, 0, \"Copy to clipboard\");\n menu.add(Menu.NONE, 1, 1, \"Clear console\");\n }\n }\n\n @Override\n public boolean onContextItemSelected(MenuItem item) {\n switch (item.getItemId()) {\n case 0:\n ClipboardManager cm = (ClipboardManager) getApplicationContext().getSystemService(Context.CLIPBOARD_SERVICE);\n ClipData clipData = ClipData.newPlainText(\"console text\", mConsoleTextView.getText());\n cm.setPrimaryClip(clipData);\n showToastie(\"Copied to clipboard\");\n break;\n case 1:\n mConsoleTextView.setText(\"\");\n showToastie(\"Console cleared\");\n break;\n default:\n break;\n }\n return true;\n }\n\n @TargetApi(Build.VERSION_CODES.KITKAT)\n private void setHideyBar() {\n Log.i(LOG_TAG, \"Activating immersive mode\");\n int uiOptions = getWindow().getDecorView().getSystemUiVisibility();\n int newUiOptions = uiOptions;\n\n if(Build.VERSION.SDK_INT >= 14){\n newUiOptions |= View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;\n }\n if(Build.VERSION.SDK_INT >= 16){\n newUiOptions |= View.SYSTEM_UI_FLAG_FULLSCREEN;\n }\n if(Build.VERSION.SDK_INT >= 18){\n newUiOptions |= View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;\n }\n getWindow().getDecorView().setSystemUiVisibility(newUiOptions);\n }\n\n //TODO: fix indirection\n public void updateFlightData(){\n mFlightDataView.updateFlightData(mController.getPitch(), mController.getRoll(), mController.getThrust(), mController.getYaw());\n }\n\n public void appendToConsole(String text) {\n final String ftext = text;\n runOnUiThread(new Runnable() {\n @Override\n public void run() {\n mConsoleTextView.append(\"\\n\" + ftext);\n mConsoleScrollView.post(new Runnable() {\n @Override\n public void run() {\n mConsoleScrollView.fullScroll(ScrollView.FOCUS_DOWN);\n }\n });\n }\n });\n }\n\n @Override\n public boolean dispatchGenericMotionEvent(MotionEvent event) {\n // Check that the event came from a joystick since a generic motion event could be almost anything.\n if ((event.getSource() & InputDevice.SOURCE_CLASS_JOYSTICK) != 0 && event.getAction() == MotionEvent.ACTION_MOVE && mController instanceof GamepadController) {\n mGamepadController.dealWithMotionEvent(event);\n updateFlightData();\n return true;\n } else {\n return super.dispatchGenericMotionEvent(event);\n }\n }\n\n @Override\n public boolean dispatchKeyEvent(KeyEvent event) {\n // do not call super if key event comes from a gamepad, otherwise the buttons can quit the app\n if (isJoystickButton(event.getKeyCode()) && mController instanceof GamepadController) {\n mGamepadController.dealWithKeyEvent(event);\n // exception for OUYA controllers\n if (!Build.MODEL.toUpperCase(Locale.getDefault()).contains(\"OUYA\")) {\n return true;\n }\n }\n return super.dispatchKeyEvent(event);\n }\n\n // this workaround is necessary because DPad buttons are not considered to be \"Gamepad buttons\"\n private static boolean isJoystickButton(int keyCode) {\n switch (keyCode) {\n case KeyEvent.KEYCODE_DPAD_CENTER:\n case KeyEvent.KEYCODE_DPAD_LEFT:\n case KeyEvent.KEYCODE_DPAD_RIGHT:\n case KeyEvent.KEYCODE_DPAD_DOWN:\n return true;\n default:\n return KeyEvent.isGamepadButton(keyCode);\n }\n }\n\n private void resetInputMethod() {\n mController.disable();\n updateFlightData();\n switch (mControls.getControllerType()) {\n case 0:\n // Use GyroscopeController if activated in the preferences\n if (mControls.isUseGyro()) {\n mController = new GyroscopeController(mControls, this, mJoystickViewLeft, mJoystickViewRight);\n } else {\n // TODO: reuse existing touch controller?\n mController = new TouchController(mControls, this, mJoystickViewLeft, mJoystickViewRight);\n }\n break;\n case 1:\n // TODO: show warning if no game pad is found?\n mController = mGamepadController;\n break;\n default:\n break;\n\n }\n mController.enable();\n Toast.makeText(this, \"Using \" + mController.getControllerName(), Toast.LENGTH_SHORT).show();\n }\n\n private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {\n\n public void onReceive(Context context, Intent intent) {\n String action = intent.getAction();\n Log.d(LOG_TAG, \"mUsbReceiver action: \" + action);\n if ((MainActivity.this.getPackageName()+\".USB_PERMISSION\").equals(action)) {\n //reached only when USB permission on physical connect was canceled and \"Connect\" or \"Radio Scan\" is clicked\n synchronized (this) {\n UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);\n if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {\n if (device != null) {\n Toast.makeText(MainActivity.this, \"Crazyradio attached\", Toast.LENGTH_SHORT).show();\n }\n } else {\n Log.d(LOG_TAG, \"permission denied for device \" + device);\n }\n }\n }\n if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {\n UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);\n if (device != null && UsbLinkAndroid.isUsbDevice(device, Crazyradio.CRADIO_VID, Crazyradio.CRADIO_PID)) {\n Log.d(LOG_TAG, \"Crazyradio detached\");\n Toast.makeText(MainActivity.this, \"Crazyradio detached\", Toast.LENGTH_SHORT).show();\n playSound(mSoundDisconnect);\n if (mPresenter != null && mPresenter.getCrazyflie() != null) {\n Log.d(LOG_TAG, \"linkDisconnect()\");\n mPresenter.disconnect();\n }\n }\n }\n if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {\n UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);\n if (device != null && UsbLinkAndroid.isUsbDevice(device, Crazyradio.CRADIO_VID, Crazyradio.CRADIO_PID)) {\n Log.d(LOG_TAG, \"Crazyradio attached\");\n Toast.makeText(MainActivity.this, \"Crazyradio attached\", Toast.LENGTH_SHORT).show();\n playSound(mSoundConnect);\n }\n }\n }\n };\n\n private void playSound(int sound){\n if (mLoaded) {\n float volume = 1.0f;\n mSoundPool.play(sound, volume, volume, 1, 0, 1f);\n }\n }\n\n // extra method for onClick attribute in XML\n public void switchLedRingEffect(View view) {\n if (mPresenter != null) {\n mPresenter.runAltAction(\"ring.effect\");\n }\n }\n\n // extra method for onClick attribute in XML\n public void toggleHeadlight(View view) {\n if (mPresenter != null) {\n mPresenter.runAltAction(\"ring.headlightEnable\");\n }\n }\n\n // extra method for onClick attribute in XML\n public void playBuzzerSound(View view) {\n if (mPresenter != null) {\n mPresenter.runAltAction(\"sound.effect:10\");\n }\n }\n\n public MainPresenter getPresenter() {\n return mPresenter;\n }\n\n public IController getController(){\n return mController;\n }\n\n public Controls getControls(){\n return mControls;\n }\n\n public static boolean isCrazyradioAvailable(Context context) {\n UsbManager usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);\n if (usbManager == null) {\n throw new IllegalArgumentException(\"UsbManager == null!\");\n }\n List<UsbDevice> usbDeviceList = UsbLinkAndroid.findUsbDevices(usbManager, (short) Crazyradio.CRADIO_VID, (short) Crazyradio.CRADIO_PID);\n return !usbDeviceList.isEmpty();\n }\n\n public void setBatteryLevel(float battery) {\n float normalizedBattery = battery - 3.0f;\n int batteryPercentage = (int) (normalizedBattery * 100);\n if (battery == -1f) {\n batteryPercentage = 0;\n } else if (normalizedBattery < 0f && normalizedBattery > -1f) {\n batteryPercentage = 0;\n } else if (normalizedBattery > 1f) {\n batteryPercentage = 100;\n }\n //TODO: FIXME\n final int fBatteryPercentage = batteryPercentage;\n runOnUiThread(new Runnable() {\n @Override\n public void run() {\n mTextView_battery.setText(format(R.string.battery_text, fBatteryPercentage));\n }\n });\n }\n\n public void setLinkQualityText(final String quality){\n runOnUiThread(new Runnable() {\n @Override\n public void run() {\n mTextView_linkQuality.setText(format(R.string.linkQuality_text, quality));\n }\n });\n }\n\n private String format(int identifier, Object o){\n return String.format(getResources().getString(identifier), o);\n }\n\n public void showToastie(final String message) {\n runOnUiThread(new Runnable() {\n @Override\n public void run() {\n Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();\n }\n });\n }\n\n public void setConnectionButtonConnected() {\n setConnectionButtonBackground(R.drawable.custom_button_connected);\n }\n\n public void setConnectionButtonConnectedBle() {\n setConnectionButtonBackground(R.drawable.custom_button_connected_ble);\n }\n\n public void setConnectionButtonDisconnected() {\n setConnectionButtonBackground(R.drawable.custom_button);\n }\n\n public void setConnectionButtonBackground(final int drawable) {\n runOnUiThread(new Runnable() {\n @Override\n public void run() {\n mToggleConnectButton.setBackgroundDrawable(getResources().getDrawable(drawable));\n }\n });\n }\n\n public void setBuzzerSoundButtonEnablement(final boolean enabled) {\n runOnUiThread(new Runnable() {\n @Override\n public void run() {\n mBuzzerSoundButton.setEnabled(enabled);\n }\n });\n }\n\n public void setRingEffectButtonEnablement(final boolean enabled) {\n runOnUiThread(new Runnable() {\n @Override\n public void run() {\n mRingEffectButton.setEnabled(enabled);\n }\n });\n }\n\n public void setHeadlightButtonEnablement(final boolean enabled) {\n runOnUiThread(new Runnable() {\n @Override\n public void run() {\n mHeadlightButton.setEnabled(enabled);\n }\n });\n }\n\n public void toggleHeadlightButtonColor(final boolean toggle) {\n runOnUiThread(new Runnable() {\n @Override\n public void run() {\n mHeadlightButton.setColorFilter(toggle ? Color.parseColor(\"#00FF00\") : Color.BLACK);\n }\n });\n }\n\n public void disableButtonsAndResetBatteryLevel() {\n setRingEffectButtonEnablement(false);\n setHeadlightButtonEnablement(false);\n setBuzzerSoundButtonEnablement(false);\n setBatteryLevel(-1.0f);\n }\n}",
"public class UsbLinkAndroid implements CrazyUsbInterface{\n\n private static final String LOG_TAG = \"UsbLinkAndroid\";\n\n private static int TRANSFER_TIMEOUT = 1000;\n\n private UsbManager mUsbManager;\n private UsbDevice mUsbDevice;\n private UsbInterface mIntf;\n private UsbEndpoint mEpIn;\n private UsbEndpoint mEpOut;\n private UsbDeviceConnection mConnection;\n private Context mContext;\n\n\n private static PendingIntent mPermissionIntent;\n\n\n public UsbLinkAndroid(Context context) throws IOException {\n this.mContext = context;\n }\n\n /**\n * Initialize the USB device. Determines endpoints and prepares communication.\n *\n * @param vid\n * @param pid\n * @throws IOException if the device cannot be opened\n * @throws SecurityException\n */\n public void initDevice(int vid, int pid) throws IOException, SecurityException {\n mUsbManager = (UsbManager) mContext.getSystemService(Context.USB_SERVICE);\n if (mUsbManager == null) {\n throw new IllegalArgumentException(\"UsbManager == null!\");\n }\n\n List<UsbDevice> usbDevices = findUsbDevices(mUsbManager, (short) vid, (short) pid);\n if (usbDevices.isEmpty() || usbDevices.get(0) == null) {\n throw new IOException(\"USB device not found. (VID: \" + vid + \", PID: \" + pid + \")\");\n }\n // TODO: Only gets the first USB device that is found\n this.mUsbDevice = usbDevices.get(0);\n\n //request permissions\n if (mUsbDevice != null && !mUsbManager.hasPermission(mUsbDevice)) {\n Log.d(LOG_TAG, \"Request permission\");\n mPermissionIntent = PendingIntent.getBroadcast(mContext, 0, new Intent(mContext.getPackageName()+\".USB_PERMISSION\"), 0);\n mUsbManager.requestPermission(mUsbDevice, mPermissionIntent);\n } else if (mUsbDevice != null && mUsbManager.hasPermission(mUsbDevice)) {\n Log.d(LOG_TAG, \"Has permission\");\n } else {\n Log.d(LOG_TAG, \"device == null\");\n return;\n }\n\n Log.d(LOG_TAG, \"setDevice \" + this.mUsbDevice);\n // find interface\n if (this.mUsbDevice.getInterfaceCount() != 1) {\n Log.e(LOG_TAG, \"Could not find interface\");\n return;\n }\n mIntf = this.mUsbDevice.getInterface(0);\n // device should have two endpoints\n if (mIntf.getEndpointCount() != 2) {\n Log.e(LOG_TAG, \"Could not find endpoints\");\n return;\n }\n // endpoints should be of type bulk\n UsbEndpoint ep = mIntf.getEndpoint(0);\n if (ep.getType() != UsbConstants.USB_ENDPOINT_XFER_BULK) {\n Log.e(LOG_TAG, \"Endpoint is not of type bulk\");\n return;\n }\n // check endpoint direction\n if (ep.getDirection() == UsbConstants.USB_DIR_IN) {\n mEpIn = mIntf.getEndpoint(0);\n mEpOut = mIntf.getEndpoint(1);\n } else {\n mEpIn = mIntf.getEndpoint(1);\n mEpOut = mIntf.getEndpoint(0);\n }\n\n UsbDeviceConnection connection = mUsbManager.openDevice(mUsbDevice);\n if (connection != null && connection.claimInterface(mIntf, true)) {\n Log.d(LOG_TAG, \"open SUCCESS\");\n mConnection = connection;\n } else {\n Log.d(LOG_TAG, \"open FAIL\");\n throw new IOException(\"could not open usb connection\");\n }\n }\n\n /* (non-Javadoc)\n * @see se.bitcraze.crazyflie.lib.IUsbLink#releaseInterface()\n */\n public void releaseInterface() {\n Log.d(LOG_TAG, \"releaseInterface()\");\n if (mConnection != null && mIntf != null){\n mConnection.releaseInterface(mIntf);\n mConnection = null;\n mIntf = null;\n }\n }\n\n /* (non-Javadoc)\n * @see se.bitcraze.crazyflie.lib.IUsbLink#sendControlTransfer(int, int, int, int, byte[])\n */\n public int sendControlTransfer(int requestType, int request, int value, int index, byte[] data){\n if(mConnection != null){\n int dataLength = (data == null) ? 0 : data.length;\n return mConnection.controlTransfer(requestType, request, value, index, data, dataLength, TRANSFER_TIMEOUT);\n }\n return -1;\n }\n\n /* (non-Javadoc)\n * @see se.bitcraze.crazyflie.lib.IUsbLink#sendBulkTransfer(byte[], byte[])\n */\n public int sendBulkTransfer(byte[] data, byte[] receiveData){\n int returnCode = -1;\n if(mConnection != null){\n mConnection.bulkTransfer(mEpOut, data, data.length, TRANSFER_TIMEOUT);\n returnCode = mConnection.bulkTransfer(mEpIn, receiveData, receiveData.length, TRANSFER_TIMEOUT);\n }\n return returnCode;\n }\n\n @Override\n public void bulkWrite(byte[] data) {\n }\n\n @Override\n public byte[] bulkRead() {\n return null;\n }\n\n public UsbDeviceConnection getConnection(){\n return mConnection;\n }\n\n @Override\n public List<UsbDevice> findDevices(int vid, int pid) {\n return findUsbDevices(mUsbManager, (short) vid, (short) pid);\n }\n\n public static List<UsbDevice> findUsbDevices(UsbManager usbManager, int vendorId, int productId) {\n List<UsbDevice> usbDeviceList = new ArrayList<UsbDevice>();\n if (usbManager != null) {\n HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();\n // Iterate over USB devices\n for (Entry<String, UsbDevice> e : deviceList.entrySet()) {\n Log.i(LOG_TAG, \"String: \" + e.getKey() + \" \" + e.getValue().getVendorId() + \" \" + e.getValue().getProductId());\n UsbDevice device = e.getValue();\n if (device.getVendorId() == vendorId && device.getProductId() == productId) {\n usbDeviceList.add(device);\n }\n }\n }\n return usbDeviceList;\n }\n\n /* (non-Javadoc)\n * @see se.bitcraze.crazyflie.lib.IUsbLink#getFirmwareVersion()\n */\n public float getFirmwareVersion() {\n if (mConnection == null) {\n Log.e(LOG_TAG, \"getFirmwareVersion: mConnection is null!\");\n return 0.0f;\n }\n byte[] rawDescs = mConnection.getRawDescriptors();\n return Float.parseFloat(Integer.toHexString(rawDescs[13] & 0x0ff) + \".\" + Integer.toHexString(rawDescs[12] & 0x0ff));\n }\n\n /* (non-Javadoc)\n * @see se.bitcraze.crazyflielib.IUsbLink#getSerialNumber()\n */\n public String getSerialNumber() {\n if (mConnection == null) {\n Log.e(LOG_TAG, \"getSerialNumber: mConnection is null!\");\n return \"UNKNOWN\";\n }\n return mConnection.getSerial();\n }\n\n /* (non-Javadoc)\n * @see se.bitcraze.crazyflie.lib.IUsbLink#isUsbConnected()\n */\n public boolean isUsbConnected() {\n return mUsbDevice != null && mConnection != null;\n }\n\n public static boolean isUsbDevice(UsbDevice usbDevice, int vid, int pid) {\n return usbDevice.getVendorId() == vid && usbDevice.getProductId() == pid;\n }\n\n //TODO: redundant?\n public boolean isUsbDeviceConnected(int vid, int pid) {\n return isUsbConnected() && isUsbDevice(mUsbDevice, vid, pid);\n }\n\n}"
] | import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import se.bitcraze.crazyflie.lib.bootloader.BootVersion;
import se.bitcraze.crazyflie.lib.bootloader.Bootloader;
import se.bitcraze.crazyflie.lib.bootloader.Bootloader.BootloaderListener;
import se.bitcraze.crazyflie.lib.bootloader.FirmwareRelease;
import se.bitcraze.crazyflie.lib.crazyradio.RadioDriver;
import se.bitcraze.crazyfliecontrol2.MainActivity;
import se.bitcraze.crazyfliecontrol2.R;
import se.bitcraze.crazyfliecontrol2.UsbLinkAndroid;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.text.Spannable;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import javax.net.ssl.HttpsURLConnection; | int fileLength = connection.getContentLength();
// download the file
File outputFile = new File(BootloaderActivity.this.getExternalFilesDir(null) + "/" + BootloaderActivity.BOOTLOADER_DIR + "/" + tagName + "/", fileName);
outputFile.getParentFile().mkdirs();
input = connection.getInputStream();
output = new FileOutputStream(outputFile);
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
// allow canceling
if (isCancelled()) {
input.close();
return null;
}
total += count;
// publishing the progress....
if (fileLength > 0) { // only if total length is known
publishProgress((int) (total * 100 / fileLength));
}
output.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null) {
output.close();
}
if (input != null) {
input.close();
}
} catch (IOException ignored) {
}
if (connection != null) {
connection.disconnect();
}
}
return null;
}
@Override
protected String doInBackground(FirmwareRelease... sFirmwareRelease) {
mSelectedFirmwareRelease = sFirmwareRelease[0];
if (mSelectedFirmwareRelease != null) {
if (mFirmwareDownloader.isFileAlreadyDownloaded(mSelectedFirmwareRelease.getTagName() + "/" + mSelectedFirmwareRelease.getAssetName())) {
mAlreadyDownloaded = true;
return null;
}
String browserDownloadUrl = mSelectedFirmwareRelease.getBrowserDownloadUrl();
if (mFirmwareDownloader.isNetworkAvailable()) {
return downloadFile(browserDownloadUrl, mSelectedFirmwareRelease.getAssetName(), mSelectedFirmwareRelease.getTagName());
} else {
Log.d(LOG_TAG, "Network connection not available.");
return "No network connection available.\nPlease check your connectivity.";
}
} else {
return "Selected firmware does not have assets.";
}
}
@Override
protected void onPreExecute() {
super.onPreExecute();
// take CPU lock to prevent CPU from going off if the user presses the power button during download
PowerManager pm = (PowerManager) BootloaderActivity.this.getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName());
mWakeLock.acquire();
mProgressBar.setProgress(0);
}
@Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
// if we get here, length is known, now set indeterminate to false
mProgressBar.setIndeterminate(false);
mProgressBar.setMax(100);
mProgressBar.setProgress(progress[0]);
}
@Override
protected void onPostExecute(String result) {
mWakeLock.release();
if (result != null) {
//flash firmware once firmware is downloaded
appendConsole("Firmware download failed: " + result);
stopFlashProcess(false);
} else {
//flash firmware once firmware is downloaded
if (mAlreadyDownloaded) {
appendConsole("Firmware file already downloaded.");
} else {
appendConsole("Firmware downloaded.");
}
startBootloader();
}
}
}
private void startBootloader() {
if (!mFirmwareDownloader.isFileAlreadyDownloaded(mSelectedFirmwareRelease.getTagName() + "/" + mSelectedFirmwareRelease.getAssetName())) {
appendConsoleError("Firmware file can not be found.");
stopFlashProcess(false);
return;
}
try {
//fail quickly, when Crazyradio is not connected
//TODO: fix when BLE is used as well
//TODO: extract this to RadioDriver class?
if (!MainActivity.isCrazyradioAvailable(this)) {
appendConsoleError("Please make sure that a Crazyradio (PA) is connected.");
stopFlashProcess(false);
return;
} | mBootloader = new Bootloader(new RadioDriver(new UsbLinkAndroid(BootloaderActivity.this))); | 6 |
icecondor/android | src/com/icecondor/nest/service/AlarmReceiver.java | [
"public class Condor extends Service {\n\n private Client api;\n private boolean clientAuthenticated;\n private String authApiCall;\n private Database db;\n private Prefs prefs;\n private PendingIntent wake_alarm_intent;\n private AlarmManager alarmManager;\n private BatteryReceiver batteryReceiver;\n private LocationManager locationManager;\n private GpsReceiver gpsReceiver;\n private CellReceiver cellReceiver;\n private final HashMap<String, Integer> activityApiQueue = new HashMap<String, Integer>();\n protected Handler apiThreadHandler;\n private NotificationBar notificationBar;\n private GpsLocation lastLocation;\n\tprivate ConnectivityManager connectivityManager;\n\t\n @Override\n public void onCreate() {\n Log.d(Constants.APP_TAG, \"** Condor onCreate \"+new DateTime()+\" **\");\n }\n\n @Override\n public int onStartCommand(Intent intent, int flags, int startId) {\n String start_reason = \"started\";\n Log.d(Constants.APP_TAG, \"Condor onStartCommand flags \"+flags+\" startId \"+startId);\n if(intent == null) {\n Log.d(Constants.APP_TAG, \"Condor null intent - restarted after kill\");\n start_reason = \"restarted\";\n }\n if(db == null) { /* init only once */\n handleCommand(intent);\n } else {\n start_reason += \" (skipped init)\";\n }\n //db.append(new Start(start_reason));\n\n // We want this service to continue running until it is explicitly\n // stopped, so return sticky.\n return START_STICKY;\n }\n\n public void handleCommand(Intent intent) {\n Log.d(Constants.APP_TAG, \"Condor handleCommand \"+intent);\n Context ctx = getApplicationContext();\n\n /* Preferences */\n prefs = new Prefs(ctx);\n\n /* Database */\n Log.d(Constants.APP_TAG, \"Condor opening database. was \"+db);\n db = new Database(ctx);\n db.open();\n\n /* Device ID */\n ensureDeviceID();\n\n /* Receive Alarms */\n alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);\n AlarmReceiver alarm_receiver = new AlarmReceiver();\n registerReceiver(alarm_receiver, new IntentFilter(Constants.ACTION_WAKE_ALARM));\n wake_alarm_intent = PendingIntent.getBroadcast(getApplicationContext(),\n 0,\n new Intent(Constants.ACTION_WAKE_ALARM),\n 0);\n\n /* Battery Monitor */\n batteryReceiver = new BatteryReceiver();\n setupBatteryMonitor();\n\n /* Location Manager */\n locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);\n gpsReceiver = new GpsReceiver(this);\n cellReceiver = new CellReceiver(this);\n restoreLastLocation();\n\n /* Connection Manager */\n connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);\n\n /* Notification Bar */\n notificationBar = new NotificationBar(this);\n\n /* API */\n api = new Client(prefs.getApiUrl(), new ApiActions());\n if(prefs.isAuthenticatedUser() && isRecording()) {\n Log.d(Constants.APP_TAG, \"Condor isRecording is ON.\");\n startRecording();\n }\n }\n\n private void ensureDeviceID() {\n String deviceId = getDeviceID();\n if(deviceId == null) {\n deviceId = \"device-\"+UUID.randomUUID();\n prefs.setDeviceId(deviceId);\n }\n }\n\n private String getDeviceID() {\n return prefs.getDeviceId();\n }\n\n public void startApi() {\n long time;\n if(lastLocation == null) {\n time = System.currentTimeMillis();\n } else {\n \ttime = lastLocation.getDateTime().getMillis();\n }\n notificationBar.updateText(\"Waiting for first location.\", time);\n api.connect();\n }\n\n public void stopApi() {\n notificationBar.cancel();\n api.stop();\n }\n\n protected void startAlarm() {\n // clear any existing alarms\n stopAlarm();\n int seconds = prefs.getRecordingFrequencyInSeconds();\n int minutes = seconds / 60;\n Log.d(Constants.APP_TAG, \"condor startAlarm at \"+minutes+\" minutes\");\n alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,\n System.currentTimeMillis(),\n seconds*1000,\n wake_alarm_intent);\n }\n\n protected void stopAlarm() {\n alarmManager.cancel(wake_alarm_intent);\n Log.d(Constants.APP_TAG, \"condor stopAlarm\");\n }\n\n protected void setupBatteryMonitor() {\n /* Battery */\n registerReceiver(batteryReceiver,\n new IntentFilter(Intent.ACTION_BATTERY_CHANGED));\n registerReceiver(batteryReceiver,\n new IntentFilter(Intent.ACTION_POWER_CONNECTED));\n registerReceiver(batteryReceiver,\n new IntentFilter(Intent.ACTION_POWER_DISCONNECTED));\n }\n\n protected void startGpsMonitor() {\n int seconds = prefs.getRecordingFrequencyInSeconds();\n Log.d(Constants.APP_TAG,\"condor requesting GPS updates every \"+seconds/60+\" minutes\");\n locationManager.requestLocationUpdates(\n LocationManager.GPS_PROVIDER,\n seconds*1000,\n 0.0F, gpsReceiver);\n }\n\n protected void stopGpsMonitor() {\n Log.d(Constants.APP_TAG,\"condor unrequesting GPS updates\");\n locationManager.removeUpdates(gpsReceiver);\n }\n\n public void gpsOneShot() {\n \tlocationManager.requestSingleUpdate(LocationManager.GPS_PROVIDER, gpsReceiver, null);\n }\n \n protected void startNetworkMonitor() {\n int seconds = prefs.getRecordingFrequencyInSeconds();\n Log.d(Constants.APP_TAG,\"condor requesting NETWORK updates every \"+seconds/60+\" minutes\");\n locationManager.requestLocationUpdates(\n LocationManager.NETWORK_PROVIDER,\n seconds*1000,\n 0.0F, cellReceiver);\n }\n\n protected void stopNetworkMonitor() {\n Log.d(Constants.APP_TAG,\"condor unrequesting NETWORK updates\");\n locationManager.removeUpdates(cellReceiver);\n }\n\n /* public methods */\n public States getNetworkState() {\n return api.getState();\n }\n\n public boolean isConnected() {\n return api.getState() == Client.States.CONNECTED;\n }\n\n public boolean isAuthenticated() {\n return clientAuthenticated;\n }\n\n public String testToken(String token) {\n return api.accountAuthSession(token, getDeviceID());\n }\n\n public boolean isBatteryValid() {\n return batteryReceiver.isLastBatteryValid();\n }\n\n public int getBattPercent() {\n return batteryReceiver.getLastBatteryLevel();\n }\n\n public boolean getBattAc() {\n return batteryReceiver.isOnAcPower();\n }\n\n public boolean isRecording() {\n return prefs.isOnOff();\n }\n\n public void setRecording(boolean onOff) {\n Log.d(Constants.APP_TAG, \"condor setRecording(\"+onOff+\")\");\n boolean oldOnOff = isRecording();\n prefs.setOnOff(onOff);\n if(!oldOnOff && onOff) {\n // transition to on\n configChange(\"recording\", onOff);\n startRecording();\n }\n if(oldOnOff && !onOff) {\n // transition to off\n configChange(\"recording\", onOff);\n stopRecording();\n }\n }\n\n public void configChange(String key, boolean value) {\n configChange(key, value ? \"on\" : \"off\");\n }\n\n public void configChange(String key, String value) {\n db.append(new Config(key, value));\n }\n\n public void startRecording() {\n startApi();\n startAlarm();\n if(prefs.isGpsOn()) {\n //startGpsMonitor();\n \tgpsOneShot();\n }\n if(prefs.isCellOn() || prefs.isWifiOn()) {\n startNetworkMonitor();\n }\n }\n\n public void stopRecording() {\n stopApi();\n stopGpsMonitor();\n stopNetworkMonitor();\n stopAlarm();\n }\n\n public void connectNow() {\n api.connect();\n }\n\n public void disconnect() {\n api.stop();\n }\n\n public void clearHistory() {\n db.emptyTable(Database.TABLE_ACTIVITIES);\n }\n\n public void pushActivities() {\n Cursor unsynced = db.activitiesLastUnsynced();\n int count = unsynced.getCount();\n Log.d(Constants.APP_TAG, \"condor pushActivities unsynced count \"+count);\n if(count > 0) {\n unsynced.moveToFirst();\n String json = unsynced.getString(unsynced.getColumnIndex(Database.ACTIVITIES_JSON));\n JSONObject activity;\n try {\n activity = new JSONObject(json);\n int rowId = unsynced.getInt(unsynced.getColumnIndex(Database.ROW_ID));\n String apiId = api.activityAdd(activity);\n activityApiQueue.put(apiId, rowId);\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n unsynced.close();\n }\n\n public boolean isUnsyncedPriorityWaiting() {\n return db.activitiesUnsyncedCount(\"location\") > 0;\n }\n\n /* Callbacks from network client */\n public class ApiActions implements ClientActions {\n @Override\n public void onConnecting(URI url, int attempts) {\n Log.d(Constants.APP_TAG, \"Condor connecting to \"+url);\n String status = url.toString();\n if(attempts > 0) {\n status += \" attempt #\"+attempts;\n }\n db.append(new Connecting(status));\n binder.onConnecting(url);\n }\n @Override\n public void onConnected() {\n db.append(new Connected(\"server connected\"));\n binder.onConnected();\n if(prefs.isAuthenticatedUser()){\n authApiCall = api.accountAuthSession(prefs.getAuthenticationToken(), getDeviceID());\n }\n }\n @Override\n public void onDisconnected() {\n clientAuthenticated = false;\n db.append(new Disconnected(\"socket closed\"));\n binder.onDisconnected();\n if(isRecording()) {\n if(prefs.isPersistentReconnect() || isUnsyncedPriorityWaiting()) {\n Log.d(Constants.APP_TAG, \"condor onDisconnected. reconnecting.\");\n api.reconnect();\n }\n }\n }\n @Override\n public void onConnectTimeout() {\n binder.onConnectTimeout();\n if(isRecording()) {\n api.reconnect();\n }\n }\n @Override\n public void onConnectException(Exception ex) {\n binder.onConnectException(ex);\n }\n @Override\n public void onMessage(JSONObject msg) {\n String apiId;\n try {\n if(msg.has(\"id\")) {\n apiId = msg.getString(\"id\");\n if(activityApiQueue.containsKey(apiId)){\n int rowId = activityApiQueue.get(apiId);\n activityApiQueue.remove(apiId);\n db.markActivitySynced(rowId);\n binder.onNewActivity();\n JSONObject actJson = db.activityJson(rowId);\n Log.d(Constants.APP_TAG,\"condor marked as synced \"+rowId+\" \"+actJson);\n if(actJson.getString(\"type\").equals(\"location\")) {\n notifyPosition(actJson);\n }\n pushActivities();\n }\n if(msg.has(\"result\")){\n JSONObject result = msg.getJSONObject(\"result\");\n binder.onApiResult(apiId, result);\n }\n if(msg.has(\"error\")){\n JSONObject result = msg.getJSONObject(\"error\");\n binder.onApiError(apiId, result);\n }\n }\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n\n public void notifyPosition(JSONObject actJson) throws JSONException {\n GpsLocation loc = new GpsLocation(actJson);\n int count = Math.abs((int)(loc.getPoint().getAccuracy() * 3.28084 / 264));\n String unit = \"block\";\n if(count > 1) { unit = \"blocks\"; }\n String provider = loc.getPoint().getProvider().toUpperCase();\n if(provider.equals(\"NETWORK\")) {\n if(loc.getPoint().getAccuracy() < 200) {\n provider = \"wifi\";\n } else {\n provider = \"cell tower\";\n }\n }\n String msg = \"Located within \"+count+\" \"+unit+\" using \"+provider+\".\";\n notificationBar.updateText(msg);\n }\n\n @Override\n public void onMessageTimeout(String id) {\n try {\n JSONObject err = new JSONObject();\n err.put(\"reason\", \"timeout\");\n binder.onApiError(id, err);\n Log.d(Constants.APP_TAG, \"condor: onMessageTimeout. disconnecting\");\n db.append(new Disconnected(\"onMessageTimeout #\"+id));\n api.disconnect();\n if(isRecording()) {\n if(prefs.isPersistentReconnect() || isUnsyncedPriorityWaiting()) {\n Log.d(Constants.APP_TAG, \"condor onMessageTimeout. reconnecting.\");\n api.reconnect();\n }\n }\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n }\n\n /* API actions */\n public void doAccountAuth(String email) {\n api.accountAuthEmail(email, getDeviceID());\n }\n\n public String doUserDetail() {\n return api.userDetail();\n }\n\n /* Emit signals to the bound Activity/UI */\n public class LocalBinder extends Binder implements UiActions {\n public Handler handler;\n public UiActions callback;\n public Condor getService() {\n return Condor.this;\n }\n /* handler setup */\n public void setHandler(Handler handler, UiActions callback) {\n Log.d(Constants.APP_TAG, \"condor: localBinder: setHandler \"+handler);\n this.handler = handler;\n this.callback = callback;\n }\n public void clearHandler() {\n Log.d(Constants.APP_TAG, \"condor: localBinder: clearHandler \");\n this.handler.removeCallbacksAndMessages(null);\n this.handler = null;\n this.callback = null;\n }\n public boolean hasHandler() {\n if(handler != null && callback != null) {\n return true;\n } else {\n return false;\n }\n }\n\n /* Relay messages to UI */\n @Override\n public void onConnecting(final URI uri) {\n if(hasHandler()) {\n handler.post(new Runnable() {\n @Override\n public void run() {\n callback.onConnecting(uri);\n callback.onNewActivity();\n }\n });\n }\n }\n @Override\n public void onConnected() {\n if(hasHandler()) {\n handler.post(new Runnable() {\n @Override\n public void run() {\n callback.onConnected();\n callback.onNewActivity();\n }\n });\n }\n }\n @Override\n public void onDisconnected() {\n if(hasHandler()) {\n handler.post(new Runnable() {\n @Override\n public void run() {\n callback.onDisconnected();\n callback.onNewActivity();\n }\n });\n }\n }\n @Override\n public void onConnectTimeout() {\n if(hasHandler()) {\n handler.post(new Runnable() {\n @Override\n public void run() {\n callback.onConnectTimeout();\n callback.onNewActivity();\n }\n });\n }\n }\n @Override\n public void onConnectException(Exception ex) {\n final Exception fex = ex;\n if(hasHandler()) {\n handler.post(new Runnable() {\n @Override\n public void run() {\n callback.onConnectException(fex);\n callback.onNewActivity();\n }\n });\n }\n }\n @Override\n public void onNewActivity() {\n if(hasHandler()) {\n handler.post(new Runnable() {\n @Override\n public void run() {\n callback.onNewActivity();\n }\n });\n }\n }\n @Override\n public void onApiResult(String _id, JSONObject _result) {\n final String id = _id;\n final JSONObject result = _result;\n if(_id.equals(authApiCall)){\n Log.d(Constants.APP_TAG, \"condor: onApiResult caught authApiCall \"+_result);\n clientAuthenticated = true;\n pushActivities();\n } else {\n if(hasHandler()) {\n handler.post(new Runnable() {\n @Override\n public void run() {\n callback.onApiResult(id, result);\n }\n });\n }\n }\n }\n @Override\n public void onApiError(String _id, JSONObject _result) {\n final String id = _id;\n final JSONObject result = _result;\n if(hasHandler()) {\n handler.post(new Runnable() {\n @Override\n public void run() {\n callback.onApiError(id, result);\n }\n });\n }\n }\n }\n\n public final LocalBinder binder = new LocalBinder();\n\n @Override\n public IBinder onBind(Intent intent) {\n Log.d(Constants.APP_TAG, \"Condor onBind\");\n return binder;\n }\n\n /* Location callbacks */\n public void onLocationChanged(Point point) {\n \tlastLocation = new GpsLocation(point);\n db.append(lastLocation);\n pushActivities();\n binder.onNewActivity();\n // stop trying GPS after successful non-GPS point\n if(!point.getProvider().equals(LocationManager.GPS_PROVIDER)) {\n \tlocationManager.removeUpdates(gpsReceiver);\n }\n }\n\n public String updateUsername(String username) {\n return api.accountSetUsername(username);\n }\n\n public void resetApiUrl(URI uri) {\n stopApi();\n api = new Client(uri, new ApiActions());\n if(isRecording()) {\n startApi();\n }\n }\n\n // let the Alarm thread write using the open db handle\n public Database getDb() {\n return db;\n }\n\n public GpsLocation getLastLocation() {\n \treturn lastLocation;\n }\n\n public void restoreLastLocation() {\n \tif(lastLocation == null) {\n Cursor cursor = db.activitiesLast(\"location\");\n if(cursor.getCount() > 0) {\n cursor.moveToFirst();\n try {\n\t\t\t\t\tlastLocation = new GpsLocation(db.rowToJson(cursor));\n\t\t\t\t} catch (JSONException e) {\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n } \t\t\n \t}\n }\n \n public boolean isDataActive(int networkType) {\n \tNetworkInfo netInfo = connectivityManager.getNetworkInfo(networkType);\n \treturn netInfo.isConnected();\n }\n}",
"public class Constants {\n\n public static final String APP_TAG = \"icecondor\";\n public static final int SIGNAL_NEW_ACTIVITY = 1;\n public static final String ACTION_WAKE_ALARM = \"com.icecondor.WAKE_ALARM\";\n public static final String ICECONDOR_API_URL = \"wss://api.icecondor.com/v2\";\n public static final String VERSION = \"20150402\";\n\n /* internal app settings */\n public static final String SETTING_ON_OFF = \"on_off\";\n public static final String SETTING_DEVICE_ID = \"device_id\";\n\n /* user preferences */\n public static final String PREFERENCE_AUTOSTART = \"autostart\";\n public static final String PREFERENCE_API_URL = \"api_url\";\n public static final String PREFERENCE_RECORDING_FREQUENCY_SECONDS = \"recording_frequency\";\n public static final String PREFERENCE_SOURCE_GPS = \"source_gps\";\n public static final String PREFERENCE_SOURCE_CELL = \"source_cell\";\n public static final String PREFERENCE_SOURCE_WIFI = \"source_wifi\";\n public static final String PREFERENCE_VERSION = \"version_string\";\n public static final String PREFERENCE_LOGOUT = \"logout_pref\";\n public static final String PREFERENCE_PERSISTENT_RECONNECT = \"persistent_reconnect\";\n public static final String PREFERENCE_EVENT_CONNECTING = \"event_connecting\";\n public static final String PREFERENCE_EVENT_CONNECTED = \"event_connected\";\n public static final String PREFERENCE_EVENT_DISCONNECTED = \"event_disconnected\";\n public static final String PREFERENCE_EVENT_HEARTBEAT= \"event_heartbeat\";\n\n}",
"public class Prefs {\n private final SharedPreferences prefs;\n private String KEY_CONFIGURED = \"configured\";\n\n public Prefs(Context ctx) {\n prefs = PreferenceManager.getDefaultSharedPreferences(ctx);\n finishConstruct();\n }\n\n public Prefs(SharedPreferences sPrefs) {\n prefs = sPrefs;\n finishConstruct();\n }\n\n private void finishConstruct(){\n if(prefs.getBoolean(KEY_CONFIGURED, false) == false) {\n ensureDefaults();\n }\n }\n\n public void setDeviceId(String deviceId) {\n prefs.edit().putString(Constants.SETTING_DEVICE_ID, deviceId).commit();\n }\n\n public String getDeviceId() {\n return prefs.getString(Constants.SETTING_DEVICE_ID, null);\n }\n\n public URI getApiUrl() {\n try {\n return new URI(prefs.getString(Constants.PREFERENCE_API_URL,\n Constants.ICECONDOR_API_URL));\n } catch (URISyntaxException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n return null;\n }\n }\n\n public int getRecordingFrequencyInSeconds() {\n String secondsStr = prefs.getString(Constants.PREFERENCE_RECORDING_FREQUENCY_SECONDS, \"NaN\");\n return Integer.parseInt(secondsStr);\n }\n\n public boolean isOnOff() {\n return prefs.getBoolean(Constants.SETTING_ON_OFF, true);\n }\n\n public void setOnOff(boolean b) {\n prefs.edit().putBoolean(Constants.SETTING_ON_OFF, b).commit();\n }\n\n public boolean isGpsOn() {\n return prefs.getBoolean(Constants.PREFERENCE_SOURCE_GPS, true);\n }\n\n public boolean isCellOn() {\n return prefs.getBoolean(Constants.PREFERENCE_SOURCE_CELL, true);\n }\n\n public boolean isWifiOn() {\n return prefs.getBoolean(Constants.PREFERENCE_SOURCE_WIFI, true);\n }\n\n public boolean isStartOnBoot() {\n return prefs.getBoolean(Constants.PREFERENCE_AUTOSTART, true);\n }\n\n private void ensureDefaults() {\n /* set default user preferences */\n Properties props = loadProperties();\n Editor editor = prefs.edit();\n /* Autostart: true */\n editor.putBoolean(Constants.PREFERENCE_AUTOSTART, true);\n\n /* On/Off: On */\n editor.putBoolean(Constants.SETTING_ON_OFF, true);\n\n /* Recording frequency: 3 minutes */\n editor.putString(Constants.PREFERENCE_RECORDING_FREQUENCY_SECONDS, \"180\");\n\n /* API url */\n String apiUrl;\n if(props.contains(\"api_url\")) {\n apiUrl = props.getProperty(\"api_url\");\n } else {\n apiUrl = Constants.ICECONDOR_API_URL;\n }\n editor.putString(Constants.PREFERENCE_API_URL, apiUrl);\n\n /* Location Sources */\n editor.putBoolean(Constants.PREFERENCE_SOURCE_GPS, true);\n editor.putBoolean(Constants.PREFERENCE_SOURCE_CELL, true);\n editor.putBoolean(Constants.PREFERENCE_SOURCE_WIFI, true);\n\n /* Advanced */\n editor.putBoolean(Constants.PREFERENCE_PERSISTENT_RECONNECT, false);\n editor.putBoolean(Constants.PREFERENCE_EVENT_CONNECTING, false);\n editor.putBoolean(Constants.PREFERENCE_EVENT_CONNECTED, false);\n editor.putBoolean(Constants.PREFERENCE_EVENT_DISCONNECTED, false);\n editor.putBoolean(Constants.PREFERENCE_EVENT_HEARTBEAT, true);\n\n editor.putBoolean(KEY_CONFIGURED, true);\n editor.commit();\n }\n\n\n private Properties loadProperties() {\n Properties props = new Properties();\n try {\n props.loadFromXML(new FileInputStream(new File(\"preference_defaults.xml\")));;\n } catch (InvalidPropertiesFormatException e) {\n e.printStackTrace();\n } catch (FileNotFoundException e) {\n Log.d(Constants.APP_TAG, \"preference_defaults.xml not found. ignoring.\");\n } catch (IOException e) {\n e.printStackTrace();\n }\n return props;\n }\n\n public String getAuthenticatedUserId() {\n return prefs.getString(Main.PREF_KEY_AUTHENTICATED_USER_ID, null);\n }\n\n public void setAuthenticatedUserId(String userId) {\n prefs.edit().putString(Main.PREF_KEY_AUTHENTICATED_USER_ID, userId).commit();\n }\n\n public void setAuthenticatedEmail(String email) {\n prefs.edit().putString(Main.PREF_KEY_AUTHENTICATED_EMAIL, email).commit();\n }\n\n public String getAuthenticatedEmail() {\n return prefs.getString(Main.PREF_KEY_AUTHENTICATED_EMAIL, null);\n }\n\n public void setAuthenticatedUsername(String username) {\n prefs.edit().putString(Main.PREF_KEY_AUTHENTICATED_USER_NAME, username).commit();\n }\n\n public String getAuthenticatedUsername() {\n return prefs.getString(Main.PREF_KEY_AUTHENTICATED_USER_NAME, null);\n }\n\n public void clearAuthenticatedUser() {\n prefs.edit().remove(Main.PREF_KEY_AUTHENTICATED_USER_ID).commit();\n prefs.edit().remove(Main.PREF_KEY_AUTHENTICATED_USER_NAME).commit();\n prefs.edit().remove(Main.PREF_KEY_AUTHENTICATED_EMAIL).commit();\n }\n\n public boolean isAuthenticatedUser() {\n return prefs.getString(Main.PREF_KEY_AUTHENTICATED_USER_ID, null) != null;\n }\n\n public void setUnvalidatedToken(String token) {\n prefs.edit().putString(Main.PREF_KEY_UNVERIFIED_TOKEN, token).commit();\n }\n\n public String getUnvalidatedToken() {\n return prefs.getString(Main.PREF_KEY_UNVERIFIED_TOKEN, null);\n }\n\n public void clearUnvalidatedToken() {\n prefs.edit().remove(Main.PREF_KEY_UNVERIFIED_TOKEN).commit();\n }\n\n public void setAuthenticationToken(String token) {\n prefs.edit().putString(Main.PREF_KEY_AUTHENTICATION_TOKEN, token).commit();\n }\n\n public String getAuthenticationToken() {\n return prefs.getString(Main.PREF_KEY_AUTHENTICATION_TOKEN, null);\n }\n\n public void clearAuthenticationToken() {\n prefs.edit().remove(Main.PREF_KEY_AUTHENTICATION_TOKEN).commit();\n }\n\n public boolean isPersistentReconnect() {\n return prefs.getBoolean(Constants.PREFERENCE_PERSISTENT_RECONNECT, false);\n }\n\n public void setPersistentReconnect(boolean b) {\n prefs.edit().putBoolean(Constants.PREFERENCE_PERSISTENT_RECONNECT, b).commit();\n }\n\n public boolean isEventConnecting() {\n return prefs.getBoolean(Constants.PREFERENCE_EVENT_CONNECTING, false);\n }\n\n public boolean isEventConnected() {\n return prefs.getBoolean(Constants.PREFERENCE_EVENT_CONNECTED, false);\n }\n\n public boolean isEventDisconnected() {\n return prefs.getBoolean(Constants.PREFERENCE_EVENT_DISCONNECTED, false);\n }\n\n public boolean isEventHeartbeat() {\n return prefs.getBoolean(Constants.PREFERENCE_EVENT_HEARTBEAT, false);\n }\n\n}",
"public class GpsLocation extends Activity {\n private static final String VERB = \"location\";\n private final Point point;\n\n public GpsLocation(JSONObject json) throws JSONException {\n super(json);\n Location location = new Location(json.getString(\"provider\"));\n location.setLatitude(json.getDouble(\"latitude\"));\n location.setLongitude(json.getDouble(\"longitude\"));\n location.setAccuracy((float)json.getDouble(\"longitude\"));\n Point point = new Point(location);\n this.point = point;\n }\n\n public GpsLocation(Point point) {\n super(VERB);\n this.point = point;\n try {\n json.put(\"latitude\", point.getLatitude());\n json.put(\"longitude\", point.getLongitude());\n json.put(\"accuracy\", point.getAccuracy());\n json.put(\"provider\", point.getProvider());\n } catch (JSONException e) {\n e.printStackTrace();\n }\n\n }\n\n public Point getPoint() {\n return point;\n }\n\n public String providerNameNetworkSpecial(Point point) {\n String provider = point.getProvider();\n float accuracy = point.getAccuracy();\n if(provider.equals(\"network\")) {\n if(accuracy < 200) {\n return provider+\"/wifi\";\n } else {\n return provider+\"/tower\";\n }\n } else {\n return provider;\n }\n }\n\n @Override\n public ContentValues getAttributes() {\n ContentValues cv = super.getAttributes();\n cv.put(Database.ACTIVITIES_VERB, VERB);\n cv.put(Database.ACTIVITIES_DESCRIPTION, providerNameNetworkSpecial(point)+\n \" accuracy \"+(int)point.getAccuracy()+\n \" meters\");\n cv.put(Database.ACTIVITIES_JSON, json.toString());\n return cv;\n }\n\n}",
"public class HeartBeat extends Activity {\n private static final String VERB = \"heartbeat\";\n private final String description;\n private int batteryPercentage;\n private boolean power;\n private long freeRam;\n private long totalRam;\n\n public HeartBeat(String desc) {\n super(VERB);\n description = desc;\n setMemory(Runtime.getRuntime());\n }\n\n @Override\n public ContentValues getAttributes() {\n ContentValues cv = super.getAttributes();\n cv.put(Database.ACTIVITIES_VERB, VERB);\n String desc = description + \" battery \"+batteryPercentage+\"%\";\n if(power) { desc = desc + \" charging\"; }\n cv.put(Database.ACTIVITIES_DESCRIPTION, desc);\n cv.put(Database.ACTIVITIES_JSON, json.toString());\n return cv;\n }\n\n public void setBatteryPercentage(int battPercent) {\n batteryPercentage = battPercent;\n try {\n JSONObject battery = new JSONObject();\n battery.put(\"percentage\", batteryPercentage);\n json.put(\"battery\", battery);\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n\n public void setPower(boolean power) {\n this.power = power;\n try {\n json.put(\"power\", power);\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n\n public void setMemory(Runtime runTime) {\n freeRam = runTime.freeMemory();\n totalRam = runTime.totalMemory();\n try {\n JSONObject memory = new JSONObject();\n memory.put(\"free\", freeRam);\n memory.put(\"total\", totalRam);\n json.put(\"memory\", memory);\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n\n\tpublic void setCellData(boolean dataActive) {\n\t\ttry {\n\t\t\tjson.put(\"celldata\", dataActive);\n\t\t} catch (JSONException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\tpublic void setWifiData(boolean dataActive) {\n\t\ttry {\n\t\t\tjson.put(\"wifidata\", dataActive);\n\t\t} catch (JSONException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n}"
] | import java.util.Date;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.util.Log;
import com.icecondor.nest.Condor;
import com.icecondor.nest.Constants;
import com.icecondor.nest.Prefs;
import com.icecondor.nest.db.activity.GpsLocation;
import com.icecondor.nest.db.activity.HeartBeat; | package com.icecondor.nest.service;
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// can we always assume context is Condor?
Condor condor = (Condor)context;
String action = intent.getAction();
if (action.equals(Constants.ACTION_WAKE_ALARM)) {
Log.i(Constants.APP_TAG, "AlarmReceiver onReceive "+
context.getClass().getSimpleName()+" now "+new Date());
HeartBeat heartBeat = new HeartBeat("");
heartBeat.setCellData(condor.isDataActive(ConnectivityManager.TYPE_MOBILE));
heartBeat.setWifiData(condor.isDataActive(ConnectivityManager.TYPE_WIFI));
if(condor.isBatteryValid()){
heartBeat.setBatteryPercentage(condor.getBattPercent());
heartBeat.setPower(condor.getBattAc());
} else {
Log.i(Constants.APP_TAG, "AlarmReceiver onReceive Warning Batt not valid");
}
condor.getDb().append(heartBeat);
condor.binder.onNewActivity(); | GpsLocation lastLocation = condor.getLastLocation(); | 3 |
SEMERU-WM/ChangeScribe | CommitSummarizer/CommitSummarizer.core/src/main/java/co/edu/unal/colswe/changescribe/core/textgenerator/phrase/NounPhrase.java | [
"public class Constants {\n\n\tpublic static final String RENAME = \"RENAME\";\n\tpublic static final String TREE = \"^{tree}\";\n\tpublic static final String DELETE = \"DELETE\";\n\tpublic static final String REMOVE = \"REMOVE\";\n\tpublic static final String ADD = \"ADD\";\n\tpublic static final String MODIFY = \"MODIFY\";\n\tpublic static final String HELP_RESOURCES_DIR = \"/html/help/commitstereotypes.html\";\n\tpublic static final String NEW_LINE = \"\\n\";\n\tpublic static final String SPACE = \" \";\n\tpublic static final String TAB = \"\\t\";\n\tpublic static final String JAVA_EXTENSION = \".java\";\n\tpublic static final String EMPTY_STRING = \"\";\n\tpublic static final String SLASH = \"/\";\n\tpublic static final String ANONYMOUS = \"anonymous\";\n\tpublic static final double FILTER_FACTOR_DEFAULT = 10;\n\tpublic static final String PERCENTAJE = \"%\";\n\tpublic static final int SIGNATURE_MIN_VALUE = 0;\n\tpublic static final int SIGNATURE_MAX_VALUE = 100;\n\tpublic static final int SIGNATURE_INCREMENT = 1;\n\tpublic static final String UNDERSCORE = \"_\";\n\tpublic static final String ADDS = \"ADDS\";\n\tpublic static final String MODIFIES = \"MODIFIES\";\n\tpublic static final String REMOVES = \"REMOVES\";\n\tpublic static final String EQUAL = \"=\";\n\n}",
"public class StringUtils {\n\t\n\tpublic static String clearLastCharacterInText(String text, String character) {\n\t\tif(text.endsWith(character)) {\n\t\t\ttext = text.substring(0, text.length() - 2);\n\t\t}\n\t\treturn text;\n\t}\n}",
"public class POSTagger {\n\tprivate static MaxentTagger tagger;\n\n\tpublic static void init() {\n\t\tif (POSTagger.tagger == null) {\n\t\t\t\tPOSTagger.tagger = new MaxentTagger( \"res/taggers/wsj-0-18-left3words-distsim.tagger\");\n\t\t}\n\t}\n\n\tpublic static LinkedList<TaggedTerm> tag(final String phrase) {\n\t\tinit();\n\t\tfinal LinkedList<TaggedTerm> taggedTerms = new LinkedList<TaggedTerm>();\n\t\tfinal StringBuilder completePhrase = new StringBuilder(\"you do \");\n\t\tif (phrase != null && !phrase.isEmpty()) {\n\t\t\tcompletePhrase.append(String.valueOf(phrase.charAt(0))\n\t\t\t\t\t.toLowerCase());\n\t\t\tif (phrase.length() > 2) {\n\t\t\t\tcompletePhrase.append(phrase.substring(1));\n\t\t\t}\n\t\t}\n\t\tfinal String[] taggedElements = POSTagger.tagger.tagString(\n\t\t\t\tcompletePhrase.toString()).split(\" \");\n\t\tfor (int i = 2; i < taggedElements.length; ++i) {\n\t\t\tfinal String[] element = taggedElements[i].split(\"_\");\n\t\t\tfinal TaggedTerm tt = new TaggedTerm(element[0], element[1]);\n\t\t\ttaggedTerms.add(tt);\n\t\t}\n\t\treturn taggedTerms;\n\t}\n\n\tpublic static void main(final String[] args) {\n\t\tfinal String[] identifiers = { \"setUIFont\", \"UncaughtExceptions\",\n\t\t\t\t\"ShowStatusBar\", \"CompareTo\", \"MousePressed\",\n\t\t\t\t\"ActionPerformed\", \"AfterSave\", \"ToString\", \"Length\", \"Weigth\",\n\t\t\t\t\"SaveImage\", \"SavedImage\", \"ImageSaved\", \"BrokenImage\",\n\t\t\t\t\"ImageBroken\", \"ReturnPressed\", \"IsVisible\", \"HasProblems\",\n\t\t\t\t\"DragDropEnd\", \"computesWeigth\", \"showAboutDialog\",\n\t\t\t\t\"setSelectedSong\", \"hasLeadingComment\", \"mouseMove\", \"keyDown\",\n\t\t\t\t\"drawingRequestUpdate\" };\n\t\tfor (int i = 0; i < identifiers.length; ++i) {\n\t\t\tfor (final TaggedTerm tt : tag(Tokenizer.split(identifiers[i]))) {\n\t\t\t\tSystem.out.print(tt + \" \");\n\t\t\t}\n\t\t\tSystem.out.println();\n\t\t}\n\t}\n}",
"public class TaggedTerm {\n\tprivate String term;\n\tprivate String tag;\n\n\tpublic TaggedTerm(final String term, final String tag) {\n\t\tsuper();\n\t\tthis.term = term;\n\t\tthis.tag = tag;\n\t}\n\n\tpublic String getTag() {\n\t\treturn this.tag;\n\t}\n\n\tpublic void setTag(final String tag) {\n\t\tthis.tag = tag;\n\t}\n\n\tpublic String getTerm() {\n\t\treturn this.term;\n\t}\n\n\tpublic void setTerm(final String term) {\n\t\tthis.term = term;\n\t}\n\n\tpublic String toString() {\n\t\treturn String.valueOf(this.term) + \":\" + this.tag;\n\t}\n}",
"public class Tokenizer\n{\n public static final String SEPARATOR = \" \";\n private static final Pattern MIDDLE_DIGITS;\n private static final Pattern CAMEL_CASE;\n \n static {\n MIDDLE_DIGITS = Pattern.compile(\"(\\\\D*)(\\\\d+)(\\\\D*)\");\n CAMEL_CASE = Pattern.compile(\"(\\\\s+[a-z]||[A-Z])[a-z]+\");\n }\n \n public static String split(final String identifier) {\n String result = replaceSpecialSymbols(identifier);\n result = splitMiddleDigits(result);\n result = splitCamelCase(result);\n return result;\n }\n \n private static String replaceSpecialSymbols(final String text) {\n return text.replaceAll(\"[^a-zA-Z0-9]+\", \" \").trim();\n }\n \n private static String replaceMultipleBlanks(final String text) {\n return text.replaceAll(\"\\\\s++\", \" \").trim();\n }\n \n private static String splitMiddleDigits(final String text) {\n final StringBuffer stringBuffer = new StringBuffer(text.length());\n final Matcher matcher = Tokenizer.MIDDLE_DIGITS.matcher(text);\n while (matcher.find()) {\n final String replacement = String.valueOf(matcher.group(1)) + \" \" + matcher.group(2) + \" \" + matcher.group(3);\n matcher.appendReplacement(stringBuffer, Matcher.quoteReplacement(replacement));\n }\n matcher.appendTail(stringBuffer);\n return replaceMultipleBlanks(stringBuffer.toString());\n }\n \n private static String splitCamelCase(final String text) {\n final StringBuffer stringBuffer = new StringBuffer(text.length());\n final Matcher matcher = Tokenizer.CAMEL_CASE.matcher(text);\n while (matcher.find()) {\n final String replacement = \" \" + matcher.group().toLowerCase() + \" \";\n matcher.appendReplacement(stringBuffer, Matcher.quoteReplacement(replacement));\n }\n matcher.appendTail(stringBuffer);\n return replaceMultipleBlanks(stringBuffer.toString());\n }\n}"
] | import java.util.LinkedList;
import java.util.List;
import co.edu.unal.colswe.changescribe.core.Constants;
import co.edu.unal.colswe.changescribe.core.textgenerator.phrase.util.StringUtils;
import co.edu.unal.colswe.changescribe.core.textgenerator.pos.POSTagger;
import co.edu.unal.colswe.changescribe.core.textgenerator.pos.TaggedTerm;
import co.edu.unal.colswe.changescribe.core.textgenerator.tokenizer.Tokenizer; | package co.edu.unal.colswe.changescribe.core.textgenerator.phrase;
public class NounPhrase extends Phrase {
private StringBuilder phrase;
private List<Parameter> parameters;
private String connector;
private StringBuilder complementPhrase;
public NounPhrase(String name) { | super(POSTagger.tag(Tokenizer.split(name))); | 4 |
ashqal/NightOwl | app/src/main/java/com/asha/nightowl/MainApplication.java | [
"@OwlHandle(CardView.class)\npublic class CardViewHandler extends AbsSkinHandler implements OwlCustomTable.OwlCardView {\n\n @Override\n protected void onAfterCollect(View view, Context context, AttributeSet attrs, ColorBox box) {\n Object[] objects = box.get(R.styleable.NightOwl_CardView_night_cardBackgroundColor\n , OwlCustomTable.CardViewScope);\n if ( objects != null ){\n // obtain original color\n TypedArray a = context.obtainStyledAttributes(attrs, android.support.v7.cardview.R.styleable.CardView, 0,\n android.support.v7.cardview.R.style.CardView_Light);\n if ( a != null ){\n int backgroundColor = a.getColor(android.support.v7.cardview.R.styleable.CardView_cardBackgroundColor, 0);\n objects[0] = backgroundColor;\n a.recycle();\n }\n }\n }\n\n public static class BackgroundPaint implements IOwlPaint{\n\n @Override\n public void draw(@NonNull View view, @NonNull Object value) {\n CardView cardView = (CardView) view;\n cardView.setCardBackgroundColor((Integer) value);\n }\n\n @Override\n public Object[] setup(@NonNull View view, @NonNull TypedArray a, int attr) {\n int color1 = 0;\n int color2 = a.getColor(attr,0);\n\n return new Integer[]{ color1,color2};\n }\n }\n}",
"@OwlHandle(CollapsingToolbarLayout.class)\npublic class CollapsingToolbarLayoutHandler extends AbsSkinHandler implements OwlCustomTable.OwlCollapsingToolbarLayout {\n //NightOwl_CollapsingToolbarLayout_night_contentScrim\n\n public static class ContentScrimPaint implements IOwlPaint{\n\n @Override\n public void draw(@NonNull View view, @NonNull Object value) {\n CollapsingToolbarLayout layout = (CollapsingToolbarLayout) view;\n layout.setContentScrim((Drawable) value);\n }\n\n @Override\n public Object[] setup(@NonNull View view, @NonNull TypedArray a, int attr) {\n CollapsingToolbarLayout layout = (CollapsingToolbarLayout) view;\n Drawable drawable1 = layout.getContentScrim();\n Drawable drawable2 = a.getDrawable(attr);\n return new Drawable[]{drawable1,drawable2};\n }\n }\n}",
"public class OwlCustomTable {\n\n public static final int TabLayoutScope = 10000;\n @OwlAttrScope(TabLayoutScope) public interface OwlTabLayout extends NightOwlTable.OwlView {\n @OwlStyleable\n int[] NightOwl_TabLayout = R.styleable.NightOwl_TabLayout;\n @OwlAttr(TabLayoutHandler.TextColorPaint.class) int NightOwl_TabLayout_night_textColorSelector = R.styleable.NightOwl_TabLayout_night_textColorSelector;\n @OwlAttr(TabLayoutHandler.IndicatorColorPaint.class) int NightOwl_TabLayout_night_tabIndicatorColor = R.styleable.NightOwl_TabLayout_night_tabIndicatorColor;\n }\n\n @OwlAttrScope(10100) public interface OwlToolbar extends NightOwlTable.OwlView {\n @OwlStyleable\n int[] NightOwl_Toolbar = R.styleable.NightOwl_Toolbar;\n @OwlAttr(ToolbarHandler.TitleTextColorPaint.class) int NightOwl_Toolbar_night_titleTextColor = R.styleable.NightOwl_Toolbar_night_titleTextColor;\n @OwlAttr(ToolbarHandler.PopupThemePaint.class) int NightOwl_Toolbar_night_popupTheme = R.styleable.NightOwl_Toolbar_night_popupTheme;\n }\n\n @OwlAttrScope(10200) public interface OwlCollapsingToolbarLayout {\n @OwlStyleable\n int[] NightOwl_CollapsingToolbarLayout = R.styleable.NightOwl_CollapsingToolbarLayout;\n @OwlAttr(CollapsingToolbarLayoutHandler.ContentScrimPaint.class) int NightOwl_CollapsingToolbarLayout_night_contentScrim = R.styleable.NightOwl_CollapsingToolbarLayout_night_contentScrim;\n }\n\n public static final int CardViewScope = 10300;\n @OwlAttrScope(CardViewScope) public interface OwlCardView {\n @OwlStyleable\n int[] NightOwl_CardView = R.styleable.NightOwl_CardView;\n @OwlAttr(CardViewHandler.BackgroundPaint.class) int NightOwl_CardView_night_cardBackgroundColor = R.styleable.NightOwl_CardView_night_cardBackgroundColor;\n }\n\n\n}",
"@OwlHandle(TabLayout.class)\npublic class TabLayoutHandler extends AbsSkinHandler implements OwlCustomTable.OwlTabLayout {\n\n @Override\n protected void onAfterCollect(View view, Context context, AttributeSet attrs, ColorBox box) {\n\n Object[] objects = box.get(R.styleable.NightOwl_TabLayout_night_tabIndicatorColor\n , OwlCustomTable.TabLayoutScope);\n if ( objects != null ){\n // obtain color\n TypedArray a = context.obtainStyledAttributes(attrs, android.support.design.R.styleable.TabLayout,\n 0, android.support.design.R.style.Widget_Design_TabLayout);\n if ( a != null ){\n int color = a.getColor(android.support.design.R.styleable.TabLayout_tabIndicatorColor, 0);\n objects[0] = color;\n a.recycle();\n }\n }\n }\n\n public static class TextColorPaint implements IOwlPaint {\n @Override\n public void draw(@NonNull View view, @NonNull Object value) {\n TabLayout tabLayout = (TabLayout) view;\n ColorStateList csl = (ColorStateList) value;\n tabLayout.setTabTextColors(csl);\n }\n\n @Override\n public Object[] setup(@NonNull View view, @NonNull TypedArray a, int attr) {\n TabLayout tabLayout = (TabLayout) view;\n ColorStateList csl1 = tabLayout.getTabTextColors();\n ColorStateList csl2 = a.getColorStateList(attr);\n return new ColorStateList[]{ csl1, csl2 };\n }\n }\n\n public static class IndicatorColorPaint implements IOwlPaint {\n\n @Override\n public void draw(@NonNull View view, @NonNull Object value) {\n TabLayout tabLayout = (TabLayout) view;\n int color = (int) value;\n tabLayout.setSelectedTabIndicatorColor(color);\n }\n\n @Override\n public Object[] setup(@NonNull View view, @NonNull TypedArray a, int attr) {\n // there is no method getSelectedTabIndicatorColor\n // we can insert later\n int color = 0;\n int color2 = a.getColor(attr,0);\n return new Integer[]{color,color2};\n }\n\n }\n\n}",
"@OwlHandle(Toolbar.class)\npublic class ToolbarHandler extends AbsSkinHandler implements OwlCustomTable.OwlToolbar {\n public ToolbarHandler() {\n }\n\n public static class PopupThemePaint implements IOwlPaint{\n private static Field sActionMenuViewField;\n private static Field sPresenterField;\n private static Field sContextField;\n static {\n try {\n sActionMenuViewField = Toolbar.class.getDeclaredField(\"mMenuView\");\n sActionMenuViewField.setAccessible(true);\n\n sPresenterField = ActionMenuView.class.getDeclaredField(\"mPresenter\");\n sPresenterField.setAccessible(true);\n\n sContextField = BaseMenuPresenter.class.getDeclaredField(\"mContext\");\n sContextField.setAccessible(true);\n } catch (NoSuchFieldException e) {\n e.printStackTrace();\n }\n }\n @Override\n public void draw(@NonNull View view, @NonNull Object value) {\n Toolbar toolbar = (Toolbar) view;\n int themeId = (int) value;\n try {\n ActionMenuView actionMenuView = (ActionMenuView) sActionMenuViewField.get(toolbar);\n if ( actionMenuView == null ){\n toolbar.getContext().setTheme(themeId);\n } else {\n MenuPresenter presenter = (MenuPresenter) sPresenterField.get(actionMenuView);\n Context context = (Context) sContextField.get(presenter);\n context.setTheme(themeId);\n }\n\n } catch (IllegalAccessException e) {\n e.printStackTrace();\n }\n toolbar.setPopupTheme((Integer) value);\n }\n\n @Override\n public Object[] setup(@NonNull View view, @NonNull TypedArray a, int attr) {\n Toolbar toolbar = (Toolbar) view;\n int theme1 = toolbar.getPopupTheme();\n int theme2 = a.getResourceId(attr,0);\n return new Integer[]{theme1,theme2};\n }\n }\n\n public static class TitleTextColorPaint implements IOwlPaint{\n\n @Override\n public void draw(@NonNull View view, @NonNull Object value) {\n Toolbar toolbar = (Toolbar) view;\n int color = (int) value;\n toolbar.setTitleTextColor(color);\n }\n\n @Override\n public Object[] setup(@NonNull View view, @NonNull TypedArray a, int attr) {\n Toolbar toolbar = (Toolbar) view;\n int color1 = NightOwlUtil.getFieldIntSafely(Toolbar.class, \"mTitleTextColor\", toolbar);\n int color2 = a.getColor(attr,color1);\n return new Integer[]{ color1,color2 };\n }\n }\n}",
"public class NightOwl {\n private static final String TAG = \"NightOwl\";\n private static final String WINDOW_INFLATER = \"mLayoutInflater\";\n private static final String THEME_INFLATER = \"mInflater\";\n private static NightOwl sInstance;\n static {\n NightOwlTable.init();\n }\n\n private int mMode = 0;\n private IOwlObserver mOwlObserver;\n private NightOwl(){\n }\n\n public static void owlBeforeCreate(Activity activity){\n Window window = activity.getWindow();\n LayoutInflater layoutInflater = window.getLayoutInflater();\n\n // replace the inflater in window\n LayoutInflater injectLayoutInflater1 = Factory4InjectedInflater.newInstance(layoutInflater, activity);\n injectLayoutInflater(injectLayoutInflater1\n , activity.getWindow()\n , activity.getWindow().getClass()\n , WINDOW_INFLATER);\n\n // replace the inflater in current ContextThemeWrapper\n LayoutInflater injectLayoutInflater2 = injectLayoutInflater1.cloneInContext(activity);\n injectLayoutInflater(injectLayoutInflater2\n , activity\n , ContextThemeWrapper.class\n , THEME_INFLATER);\n\n // insert owlViewContext into root view.\n View v = activity.getWindow().getDecorView();\n OwlViewContext owlObservable = new OwlViewContext();\n insertViewContext(v, owlObservable);\n\n }\n\n\n public static void owlAfterCreate(Activity activity){\n View root = activity.getWindow().getDecorView();\n OwlViewContext viewContext = obtainViewContext(root);\n checkNonNull(viewContext, \"OwlViewContext can not be null!\");\n\n // setup some observer\n viewContext.setupWithCurrentActivity(activity);\n\n // init set\n viewContext.notifyObserver(sharedInstance().mMode, activity);\n }\n\n public static void owlResume( Activity activity ){\n NightOwl nightOwl = sharedInstance();\n int targetMode = nightOwl.mMode;\n\n owlDressUp(targetMode, activity);\n }\n\n public static void owlNewDress( Activity activity ) {\n int current = owlCurrentMode() + 1;\n current %= 2;\n\n owlDressUp(current, activity);\n }\n\n public static void owlRecyclerFix(View view){\n int mode = owlCurrentMode();\n innerRefreshSkin(mode, view);\n }\n\n private static void owlDressUp( int mode, Activity activity ){\n // View tree\n NightOwl owl = sharedInstance();\n View root = activity.getWindow().getDecorView();\n OwlViewContext viewContext = obtainViewContext(root);\n checkNonNull(viewContext, \"OwlViewContext can not be null!\");\n\n if ( viewContext.needSync(mode) ){\n // refresh skin\n innerRefreshSkin(mode, root);\n\n // OwlObserver\n viewContext.notifyObserver(mode, activity);\n }\n\n owl.mMode = mode;\n if ( owl.mOwlObserver != null ) owl.mOwlObserver.onSkinChange(mode,activity);\n }\n\n /**\n * Register a custom view which created by new instance directly.\n *\n * @param view instanceof IOwlObserver & View\n * NightOwl will trigger view.onSkinChange immediately.\n */\n public static void owlRegisterCustom(IOwlObserver view){\n if ( view instanceof View ) {\n View target = (View) view;\n insertEmptyTag(target);\n view.onSkinChange(owlCurrentMode(), null);\n } else {\n throw new IllegalArgumentException(\"owlRegisterCustom param must be a instance of View\");\n }\n }\n\n public static void owlRegisterHandler(Class<? extends ISkinHandler> clz, Class paintTable){\n OwlHandlerManager.registerHandler(clz);\n OwlPaintManager.registerPaint(paintTable);\n }\n\n public static int owlCurrentMode(){\n return sharedInstance().mMode;\n }\n\n private static void innerRefreshSkin(int mode, View view ){\n // refresh current view\n if ( checkViewCollected(view) ){\n ColorBox box = obtainSkinBox(view);\n if ( box != null ) box.refreshSkin(mode, view);\n if ( view instanceof IOwlObserver ){\n ((IOwlObserver) view).onSkinChange(mode,null);\n }\n }\n // traversal view tree\n if ( view instanceof ViewGroup){\n ViewGroup vg = (ViewGroup) view;\n View sub;\n for (int i = 0; i < vg.getChildCount(); i++) {\n sub = vg.getChildAt(i);\n innerRefreshSkin(mode, sub);\n }\n }\n }\n\n private static NightOwl sharedInstance(){\n checkNonNull(sInstance,\"You must create NightOwl in Application onCreate.\");\n return sInstance;\n }\n\n public static Builder builder(){\n return new Builder();\n }\n\n public static class Builder {\n private int mode;\n private IOwlObserver owlObserver;\n public Builder defaultMode(int mode){\n this.mode = mode;\n return this;\n }\n\n /**\n * Subscribed by a owlObserver to know the skin change.\n *\n * @param owlObserver do some persistent working here\n * @return Builder\n */\n public Builder subscribedBy(IOwlObserver owlObserver){\n this.owlObserver = owlObserver;\n return this;\n }\n public NightOwl create(){\n if ( sInstance != null ) throw new RuntimeException(\"Do not create NightOwl again.\");\n sInstance = new NightOwl();\n sInstance.mMode = mode;\n sInstance.mOwlObserver = owlObserver;\n return sInstance;\n }\n }\n}",
"public interface IOwlObserver {\n\n /**\n *\n * @param mode current style mode\n * @param activity notice that: it may be null\n *\n * @see com.asha.nightowllib.inflater.InjectedInflaterBase#handleOnCreateView(View, String, AttributeSet)\n */\n void onSkinChange(int mode, Activity activity);\n}"
] | import android.app.Activity;
import android.app.Application;
import android.content.SharedPreferences;
import android.support.v4.content.SharedPreferencesCompat;
import com.asha.nightowl.custom.CardViewHandler;
import com.asha.nightowl.custom.CollapsingToolbarLayoutHandler;
import com.asha.nightowl.custom.OwlCustomTable;
import com.asha.nightowl.custom.TabLayoutHandler;
import com.asha.nightowl.custom.ToolbarHandler;
import com.asha.nightowllib.NightOwl;
import com.asha.nightowllib.observer.IOwlObserver; | package com.asha.nightowl;
/**
* Created by hzqiujiadi on 15/11/6.
* hzqiujiadi ashqalcn@gmail.com
*/
public class MainApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
SharedPreferences preferences = getSharedPreferences("NightOwlDemo",Activity.MODE_PRIVATE);
int mode = preferences.getInt("mode",0);
NightOwl.builder().subscribedBy(new SkinObserver()).defaultMode(mode).create();
NightOwl.owlRegisterHandler(TabLayoutHandler.class, OwlCustomTable.OwlTabLayout.class); | NightOwl.owlRegisterHandler(ToolbarHandler.class, OwlCustomTable.OwlToolbar.class); | 4 |
TeamCohen/SEAL | src/com/rcwang/seal/expand/IterativeSeal.java | [
"public class EvalResult {\r\n public int trialID = 0;\r\n public int numGoldEntity = 0;\r\n public int numGoldSynonym = 0;\r\n public double numCorrectSynonym = 0;\r\n public double numCorrectEntity = 0;\r\n public double numResultsAboveThreshold = 0;\r\n public double maxF1Precision = 0;\r\n public double maxF1Recall = 0;\r\n public double maxF1Threshold = 0;\r\n public double precision = 0;\r\n public double recall = 0;\r\n public double threshold = 0;\r\n public double meanAvgPrecision = 0;\r\n public File goldFile = null;\r\n public String seeds = \"\";\r\n public Feature method = null;\r\n private StringBuffer buf = new StringBuffer();\r\n public double getF1() { return Evaluator.computeF1(precision, recall); }\r\n public double getMaxF1() { return Evaluator.computeF1(maxF1Precision, maxF1Recall); }\r\n \r\n public String toString() {\r\n buf.setLength(0);\r\n buf.append(\"===================================================\\n\");\r\n if (goldFile != null && method != null)\r\n buf.append(\"Results of \\\"\" + goldFile.getName() + \"\\\" using method: \" + method + \"\\n\");\r\n if (seeds != null && seeds.trim().length() > 0)\r\n buf.append(\"Seeds: \" + seeds + \"\\n\");\r\n buf.append(\"Avg. number of results above threshold: \" + Helper.formatNumber(numResultsAboveThreshold, 3) + \"\\n\");\r\n buf.append(\"Avg. number of correct synonyms: \" + Helper.formatNumber(numCorrectSynonym, 3) + \" out of \" + numGoldSynonym + \"\\n\");\r\n buf.append(\"Avg. number of correct entities: \" + Helper.formatNumber(numCorrectEntity, 3) + \" out of \" + numGoldEntity + \"\\n\");\r\n buf.append(\"Max. Possible F1: \" + Helper.formatNumber(getMaxF1(), 3));\r\n buf.append(\" (Precision: \" + Helper.formatNumber(maxF1Precision, 3));\r\n buf.append(\", Recall: \" + Helper.formatNumber(maxF1Recall, 3) + \")\");\r\n buf.append(\" at threshold: \" + Helper.formatNumber(maxF1Threshold, 3) + \"\\n\");\r\n buf.append(\"F1: \" + Helper.formatNumber(getF1(), 3));\r\n buf.append(\" (Precision: \" + Helper.formatNumber(precision, 3));\r\n buf.append(\", Recall: \" + Helper.formatNumber(recall, 3) + \")\");\r\n buf.append(\" at threshold: \" + Helper.formatNumber(threshold, 3) + \"\\n\");\r\n buf.append(\"Mean Avg. Precision: \" + Helper.formatNumber(meanAvgPrecision, 3));\r\n return buf.toString();\r\n }\r\n \r\n public String toTabSeperated() {\r\n buf.setLength(0);\r\n buf.append(Evaluator.getDataName(goldFile)).append(\"\\t\");\r\n buf.append(method).append(\"\\t\");\r\n buf.append(getMaxF1()).append(\"\\t\");\r\n buf.append(maxF1Precision).append(\"\\t\");\r\n buf.append(maxF1Recall).append(\"\\t\");\r\n buf.append(maxF1Threshold).append(\"\\t\");\r\n buf.append(getF1()).append(\"\\t\");\r\n buf.append(precision).append(\"\\t\");\r\n buf.append(recall).append(\"\\t\");\r\n buf.append(threshold).append(\"\\t\");\r\n buf.append(meanAvgPrecision).append(\"\\n\");\r\n return buf.toString();\r\n } \r\n}",
"public class Evaluator {\r\n \r\n public static class GoldEntity {\r\n public Set<String> synonyms = new LinkedHashSet<String>();\r\n }\r\n \r\n public static Logger log = Logger.getLogger(Evaluator.class);\r\n public static final String EVAL_FILE_SUFFIX = \".xls\"; // evaluation results\r\n public static final String GOLD_FILE_SUFFIX = \".txt\"; // evaluation datasets\r\n public static final double DEFAULT_THRESHOLD = 0.8;\r\n \r\n private List<GoldEntity> goldList;\r\n private Set<String> goldSynonyms;\r\n private File goldFile;\r\n\r\n public static double computeF1(double prec, double recall) {\r\n return (prec + recall == 0) ? 0 : (2 * prec * recall) / (prec + recall);\r\n }\r\n \r\n public static String getLangID(File goldFile) {\r\n if (goldFile == null) return null;\r\n File parentFile = goldFile.getParentFile();\r\n if (parentFile == null) return null;\r\n return parentFile.getName();\r\n }\r\n \r\n public static String getDataName(File goldFile) {\r\n if (goldFile == null) return null;\r\n String name = goldFile.getName();\r\n if (name.endsWith(GOLD_FILE_SUFFIX))\r\n name = name.substring(0, name.length()-GOLD_FILE_SUFFIX.length());\r\n return name;\r\n }\r\n \r\n public static List<String> getFirstMentions(File goldFile) {\r\n List<GoldEntity> goldList = new ArrayList<GoldEntity>();\r\n Evaluator.loadGoldFile(goldFile, goldList);\r\n return getFirstMentions(goldList);\r\n }\r\n \r\n public static List<File> getGoldFiles(File dataDir) {\r\n return getGoldFiles(dataDir, null);\r\n }\r\n \r\n public static List<File> getGoldFiles(File dataDir, String langID) {\r\n File[] langDirs = dataDir.listFiles();\r\n List<File> list = new ArrayList<File>();\r\n \r\n for (File langDir : langDirs) {\r\n if (!langDir.isDirectory()) continue;\r\n if (langID != null && !langDir.getName().equals(langID)) continue;\r\n File[] files = langDir.listFiles();\r\n for (File file : files)\r\n if (file.isFile() && file.getName().endsWith(GOLD_FILE_SUFFIX))\r\n list.add(file);\r\n }\r\n return list;\r\n }\r\n \r\n public static Set<String> getGoldSynonyms(File goldFile) {\r\n Set<String> allGoldSynonyms = new HashSet<String>();\r\n List<GoldEntity> goldList = new ArrayList<GoldEntity>();\r\n loadGoldFile(goldFile, goldList);\r\n for (GoldEntity ge : goldList)\r\n allGoldSynonyms.addAll(ge.synonyms);\r\n return allGoldSynonyms;\r\n }\r\n \r\n public static void loadGoldFile(File goldFile, List<GoldEntity> goldList) {\r\n if (goldList == null) return;\r\n goldList.clear();\r\n log.info(\"Loading gold file: \" + goldFile);\r\n String content = Helper.readFile(goldFile);\r\n String[] lines = content.split(\"\\n\");\r\n\r\n for (String line : lines) {\r\n String[] synonyms = line.split(\"\\t\");\r\n GoldEntity ge = makeGoldEntity(synonyms);\r\n goldList.add(ge);\r\n }\r\n log.info(\"Number of entities in gold file: \" + goldList.size());\r\n }\r\n\r\n public static EvalResult mergeEvalResults(EvalResult[] evalResults) {\r\n int numTrials = 0;\r\n for (EvalResult evalResult : evalResults)\r\n if (evalResult != null)\r\n numTrials++;\r\n EvalResult result = new EvalResult();\r\n for (EvalResult evalResult : evalResults) {\r\n if (evalResult == null)\r\n continue;\r\n mergeEvalResults(evalResult, result, numTrials);\r\n result.seeds += evalResult.seeds;\r\n result.method = evalResult.method;\r\n result.goldFile = evalResult.goldFile;\r\n result.threshold = evalResult.threshold;\r\n result.numGoldEntity = evalResult.numGoldEntity;\r\n result.numGoldSynonym = evalResult.numGoldSynonym;\r\n }\r\n return result;\r\n }\r\n \r\n private static List<String> getFirstMentions(List<GoldEntity> goldList) {\r\n List<String> names = new ArrayList<String>();\r\n for (GoldEntity ge : goldList)\r\n names.add(ge.synonyms.iterator().next());\r\n return names;\r\n }\r\n \r\n private static GoldEntity makeGoldEntity(String[] synonyms) {\r\n GoldEntity ge = new GoldEntity();\r\n if (synonyms == null || synonyms.length == 0) return ge;\r\n \r\n for (String synonym : synonyms) {\r\n synonym = synonym.toLowerCase().replace('-', ' ').trim(); // added 04/03/2008\r\n if (synonym.length() == 0) continue;\r\n ge.synonyms.add(synonym);\r\n \r\n // remove punctuations and add to synonyms\r\n String optionalChars = WrapperFactory.OPTIONAL_CHAR_STR;\r\n if (synonym.matches(\"^.+\" + optionalChars + \".+$\")) {\r\n String s = synonym.replaceAll(optionalChars, \"\").trim();\r\n if (s.length() > 0)\r\n ge.synonyms.add(s);\r\n s = synonym.replaceAll(optionalChars, \" \").replaceAll(\"\\\\s+\", \" \").trim();\r\n if (s.length() > 0)\r\n ge.synonyms.add(s);\r\n }\r\n \r\n // if is English, do something (added 10/20/2008)\r\n if (synonym.matches(\".*[a-zA-Z].*\")) {\r\n if (synonym.endsWith(\"y\")) {\r\n ge.synonyms.add(synonym.substring(0, synonym.length()-1) + \"ies\");\r\n } else {\r\n ge.synonyms.add(synonym + \"s\");\r\n ge.synonyms.add(synonym + \"es\");\r\n ge.synonyms.add(\"the \" + synonym);\r\n// ge.synonyms.add(\"comet \" + synonym);\r\n }\r\n }\r\n }\r\n return ge;\r\n }\r\n \r\n private static EvalResult mergeEvalResults(EvalResult fromResult, EvalResult toResult, int numTrials) {\r\n toResult.numResultsAboveThreshold += fromResult.numResultsAboveThreshold / numTrials;\r\n toResult.numCorrectEntity += fromResult.numCorrectEntity / numTrials;\r\n toResult.numCorrectSynonym += fromResult.numCorrectSynonym / numTrials;\r\n toResult.maxF1Precision += fromResult.maxF1Precision / numTrials;\r\n toResult.maxF1Recall += fromResult.maxF1Recall / numTrials;\r\n toResult.maxF1Threshold += fromResult.maxF1Threshold / numTrials;\r\n toResult.precision += fromResult.precision / numTrials;\r\n toResult.recall += fromResult.recall / numTrials;\r\n toResult.meanAvgPrecision += fromResult.meanAvgPrecision / numTrials;\r\n return toResult;\r\n }\r\n \r\n public Evaluator() {\r\n goldList = new ArrayList<GoldEntity>();\r\n goldSynonyms = new HashSet<String>();\r\n }\r\n\r\n public EvalResult evaluate(EntityList entityList) {\r\n return evaluate(entityList, DEFAULT_THRESHOLD);\r\n }\r\n \r\n public EvalResult evaluate(EntityList entityList, double threshold) {\r\n EvalResult eval = new EvalResult();\r\n if (goldList.size() == 0) {\r\n log.error(\"No gold answers loaded!\");\r\n return eval;\r\n }\r\n double maxF1 = 0;\r\n double sumOfPrecisions = 0;\r\n int numResultAboveThreshold = 0;\r\n int numCorrectSynonym = 0;\r\n int numCorrectEntity = 0;\r\n boolean[] seenGold = new boolean[goldList.size()];\r\n\r\n // traverse through the entire result list\r\n for (int i = 0; i < entityList.size(); i++) {\r\n Entity entity = entityList.get(i);\r\n entity.setCorrect(0);\r\n \r\n // count the number of correct synonyms\r\n if (goldSynonyms.contains(entity.getName().toString()))\r\n numCorrectSynonym++;\r\n\r\n // get precision at current rank\r\n double precision = (double) numCorrectSynonym / (i+1);\r\n \r\n // count the number of correct entities\r\n for (int j = 0; j < goldList.size(); j++) {\r\n Set<String> goldSynonyms = goldList.get(j).synonyms;\r\n if (goldSynonyms.contains(entity.getName().toString())) {\r\n entity.setCorrect(seenGold[j] ? 2 : 1);\r\n if (seenGold[j]) continue;\r\n } else continue;\r\n \r\n // this is the first 'correct' synonym encountered for an entity\r\n sumOfPrecisions += precision;\r\n numCorrectEntity++;\r\n seenGold[j] = true;\r\n break;\r\n }\r\n // get recall and F1 at current rank\r\n double recall = (double) numCorrectEntity / goldList.size();\r\n double F1 = computeF1(precision, recall);\r\n\r\n if (F1 > maxF1) {\r\n eval.maxF1Precision = precision;\r\n eval.maxF1Recall = recall;\r\n eval.maxF1Threshold = entity.getScore();\r\n maxF1 = F1;\r\n }\r\n\r\n if (entity.getScore() >= threshold) {\r\n eval.precision = precision;\r\n eval.recall = recall;\r\n eval.numCorrectEntity = numCorrectEntity;\r\n eval.numCorrectSynonym = numCorrectSynonym;\r\n numResultAboveThreshold++;\r\n }\r\n }\r\n eval.threshold = threshold;\r\n eval.numResultsAboveThreshold = numResultAboveThreshold;\r\n eval.meanAvgPrecision = sumOfPrecisions / goldList.size();\r\n eval.numGoldEntity = goldList.size();\r\n eval.numGoldSynonym = goldSynonyms.size();\r\n eval.goldFile = goldFile;\r\n entityList.setEvalResult(eval);\r\n return eval;\r\n }\r\n \r\n public String getDataName() {\r\n return getDataName(goldFile);\r\n }\r\n \r\n public List<String> getFirstMentions() {\r\n return getFirstMentions(goldList);\r\n }\r\n \r\n public List<GoldEntity> getGoldEntityList() {\r\n return goldList;\r\n }\r\n \r\n public File getGoldFile() {\r\n return goldFile;\r\n }\r\n \r\n public Set<String> getGoldSynonyms() {\r\n return goldSynonyms;\r\n }\r\n\r\n public void loadGoldFile(File goldFile) {\r\n this.goldFile = goldFile;\r\n loadGoldFile(goldFile, goldList);\r\n goldSynonyms.clear();\r\n for (GoldEntity ge : goldList)\r\n goldSynonyms.addAll(ge.synonyms);\r\n }\r\n\r\n}\r",
"public class DocumentSet implements Iterable<Document>, Serializable {\r\n \r\n public static final double DELTA = 1e-10;\r\n public static final int DEFAULT_MAX_DOCS_IN_XML = 5;\r\n \r\n private static final long serialVersionUID = 7211782411429869181L;\r\n private Map<Document, Document> docMap;\r\n private List<Document> docList;\r\n private Set<EntityLiteral> extractions;\r\n private Set<Wrapper> wrappers;\r\n private Feature scoredByFeature;\r\n private int maxDocsInXML;\r\n \r\n public DocumentSet() {\r\n setMaxDocsInXML(DEFAULT_MAX_DOCS_IN_XML);\r\n docMap = new HashMap<Document, Document>();\r\n docList = new ArrayList<Document>();\r\n extractions = new HashSet<EntityLiteral>();\r\n wrappers = new HashSet<Wrapper>();\r\n }\r\n \r\n public DocumentSet(DocumentSet documents) {\r\n this();\r\n addAll(documents);\r\n }\r\n \r\n public void add(Document document) {\r\n if (document == null) return;\r\n Document doc = docMap.get(document);\r\n if (doc == document) return;\r\n if (doc == null) {\r\n docMap.put(document, document);\r\n docList.add(document);\r\n } else {\r\n doc.merge(document);\r\n }\r\n wrappers.addAll(document.getWrappers());\r\n extractions.addAll(document.getExtractions());\r\n }\r\n \r\n public void addAll(DocumentSet documents) {\r\n if (documents == null) return;\r\n for (Document document : documents)\r\n add(document);\r\n }\r\n \r\n public void assignScore(Feature feature) {\r\n scoredByFeature = feature;\r\n if (docList.size() == 0) return;\r\n sort();\r\n double maxScore = docList.get(0).getWeight() + DELTA;\r\n double minScore = docList.get(docList.size()-1).getWeight() - DELTA;\r\n for (Document document : docList) {\r\n double weight = (document.getWeight() - minScore) / (maxScore - minScore);\r\n document.setWeight(weight);\r\n }\r\n }\r\n \r\n public void clear() {\r\n docMap.clear();\r\n docList.clear();\r\n extractions.clear();\r\n wrappers.clear();\r\n }\r\n \r\n public void clearExtractions() {\r\n for (Document document : this)\r\n document.clearExtractions();\r\n extractions.clear();\r\n }\r\n \r\n public void clearStats() {\r\n clearWrappers();\r\n clearExtractions();\r\n }\r\n \r\n /*public double getConfidence() {\r\n double w = 0;\r\n for (Document document : this) {\r\n if (document.length() == 0) continue;\r\n int sum = 0;\r\n for (Wrapper wrapper : document.getWrappers())\r\n sum += wrapper.length() * wrapper.getNumCommonTypes();\r\n w += (double) sum / document.length();\r\n }\r\n w = w / this.size();\r\n return w;\r\n }*/\r\n \r\n public void clearWrappers() {\r\n for (Document document : this)\r\n document.clearWrappers();\r\n wrappers.clear();\r\n }\r\n \r\n public Document get(int i) {\r\n return docList.get(i);\r\n }\r\n \r\n public double getContentQuality() {\r\n int numWrappers = getNumWrappers();\r\n if (numWrappers == 0) return 0;\r\n return getSumWrapperLength() / numWrappers;\r\n }\r\n \r\n public Set<EntityLiteral> getExtractions() {\r\n return extractions;\r\n }\r\n \r\n public int getMaxDocsInXML() {\r\n return maxDocsInXML;\r\n }\r\n \r\n public int getNumExtractions() {\r\n return getExtractions().size();\r\n }\r\n \r\n public int getNumWrappers() {\r\n return getWrappers().size();\r\n }\r\n \r\n public int getSumDocLength() {\r\n int sum = 0;\r\n for (Document document : this)\r\n sum += document.length();\r\n return sum;\r\n }\r\n \r\n public double getSumWrapperLength() {\r\n double sum = 0;\r\n for (Document document : this)\r\n for (Wrapper wrapper : document.getWrappers())\r\n sum += Math.log(wrapper.getContextLength()) * wrapper.getNumCommonTypes();\r\n return sum;\r\n }\r\n \r\n public Set<Wrapper> getWrappers() {\r\n return wrappers;\r\n }\r\n\r\n public Iterator<Document> iterator() {\r\n return docList.iterator();\r\n }\r\n \r\n public void setMaxDocsInXML(int numTopDocsInXML) {\r\n this.maxDocsInXML = numTopDocsInXML;\r\n }\r\n \r\n public int size() {\r\n return docList.size();\r\n }\r\n \r\n public void sort() {\r\n Collections.sort(docList);\r\n }\r\n \r\n public DocumentSet subList(int fromIndex, int toIndex) {\r\n DocumentSet docSet = new DocumentSet();\r\n docSet.docList = docList.subList(fromIndex, toIndex);\r\n for (Document document : docList)\r\n docSet.docMap.put(document, document);\r\n return docSet;\r\n }\r\n\r\n public String toXML() {\r\n return XMLUtil.document2String(toXMLElement(null));\r\n }\r\n\r\n public Element toXMLElement(org.w3c.dom.Document document) {\r\n XMLUtil xml = new XMLUtil(document);\r\n Element documentsNode = xml.createElement(\"documents\", null);\r\n xml.createAttrsFor(documentsNode, new Object[]{\r\n \"numDocuments\", docList.size(),\r\n \"scoredBy\", scoredByFeature,\r\n });\r\n\r\n for (int i = 0; i < Math.min(docList.size(), maxDocsInXML); i++) {\r\n Document doc = docList.get(i);\r\n if (doc.getWeight() == 0) continue;\r\n Element documentNode = xml.createElementBelow(documentsNode, \"document\", null);\r\n xml.createAttrsFor(documentNode, new Object[]{\r\n \"rank\", i+1,\r\n \"weight\", doc.getWeight(),\r\n });\r\n String title = doc.getSnippet().getTitle().toString();\r\n String urlStr = doc.getSnippet().getPageURL().toString();\r\n xml.createElementBelow(documentNode, \"title\", title);\r\n xml.createElementBelow(documentNode, \"url\", urlStr);\r\n }\r\n return documentsNode;\r\n }\r\n\r\n protected Feature getScoredByFeature() {\r\n return scoredByFeature;\r\n }\r\n}",
"public static enum Feature { ETF, EDF, EWF, WLW, BSW, PRW, GWW}\r",
"public class GlobalVar {\r\n \r\n public static final String PROP_ENV_NAME = \"SEAL_PROP\";\r\n public static final String PROP_FILE_PATH = \"seal.properties\";\r\n public static final String COMMA_REGEXP = \"\\\\s*,\\\\s*\";\r\n public static final String CLUEWEB_TMP_DIR=\"clueweb.tmpdir\";\r\n public static final String CLUEWEB_HEADER_TIMEOUT_MS = \"clueweb.headerTimeout\";\r\n public static final String CLUEWEB_TIMEOUT_NUMTRIALS = \"clueweb.numtrials\";\r\n public static final String CLUEWEB_TIMEOUT_REPORTING_MS = \"clueweb.timeoutReporting\";\r\n public static Logger log = Logger.getLogger(GlobalVar.class);\r\n \r\n private static GlobalVar gv = null;\r\n private static Properties prop = null;\r\n \r\n // Basic parameters\r\n private static String langID;\r\n private static Feature feature;\r\n private static boolean hasNoisySeeds;\r\n private static int useEngine;\r\n private static String yahooAPIKey;\r\n private static String yahooBossKey;\r\n private static long googleHitGapInMS;\r\n private static File resultDir;\r\n private static int minSeedsBracketed;\r\n private static String bingAPIKey;\r\n private static String googleCustomAPIKey;\r\n private static String setExpander;\r\n\r\n // Fetching parameters\r\n private static int numResults;\r\n private static int numSubSeeds;\r\n \r\n // OfflineSeal and WrapperSavingAsia parameters\r\n private static boolean isFetchFromWeb; //wwc - keeps WebManager from getting stuff from web\r\n private static File localDir; //wwc - files that will be searched by the OfflineSearcher\r\n private static File indexDir; //wwc - index of files in localDir\r\n private static File localRoot; //wwc - set if files are indexed relative to some root directory\r\n private static File savedWrapperDir; //wwc - stores wrappers generated by OfflineSeal or WrapperSavingAsia\r\n private static int wrapperSaving; //wwc - policy on wrapper saving, 2 means save to savedWrapperDir\r\n\r\n // Optimization parameters\r\n private static int wrapperLevel;\r\n private static int minContextLength;\r\n private static int maxDocSizeInKB;\r\n private static int timeOutInMS;\r\n private static File cacheDir;\r\n private static File urlBlackList;\r\n private static File stopwordsList;\r\n \r\n // Iterative expansion parameters\r\n private static SeedingPolicy policy;\r\n private static int numExpansions;\r\n private static int numTrueSeeds;\r\n private static int numPossibleSeeds;\r\n \r\n // Bilingual\r\n private static String langID2;\r\n \r\n // Experiments parameters\r\n private static List<Feature> expFeatures;\r\n private static List<String> expDatasets;\r\n private static File evalDir;\r\n private static File dataDir;\r\n private static int numTrials;\r\n\r\n // Question Answering parameters\r\n private static int topSystem;\r\n private static boolean useGoogleSets;\r\n private static double ephyraThreshold;\r\n private static double sealThreshold;\r\n private static double interThreshold;\r\n private static double unionThreshold;\r\n private static double method1Threshold;\r\n \r\n\r\n private static boolean explicitRelations;\r\n private static boolean storeContentWeights;\r\n \r\n // ClueWeb parameters\r\n private static boolean cluewebKeepResponseFile;\r\n private static boolean cluewebKeepQueryFile;\r\n private static boolean cluewebMemoryManagement;\r\n private static boolean multiquery;\r\n /**\r\n * Looks for a GlobalVar in the following order:\r\n * 1) System environment: PROP_ENV_NAME\r\n * 2) Fixed location: PROP_FILE_PATH\r\n * @return\r\n */\r\n public static GlobalVar getGlobalVar() {\r\n if (gv != null) return gv;\r\n gv = new GlobalVar();\r\n String propFilePath = System.getenv(PROP_ENV_NAME);\r\n if (propFilePath == null) {\r\n propFilePath = System.getProperty(PROP_FILE_PATH,PROP_FILE_PATH);\r\n }\r\n gv.load(propFilePath);\r\n return gv;\r\n }\r\n\r\n public void load(String propFilePath) {\r\n File propFile = new File(propFilePath);\r\n log.debug(\"Loading seal.properties from \"+propFilePath);\r\n prop = Helper.loadPropertiesFile(propFile);\r\n if (prop == null) {\r\n log.fatal(\"Missing \\\"\" + PROP_FILE_PATH + \"\\\" in your classpath!\");\r\n System.exit(1);\r\n }\r\n //merge any command-line overrides\r\n Properties sysprop = System.getProperties();\r\n prop.putAll(sysprop); // this is messy(noisy) but easy\r\n \r\n gv.load(prop);\r\n }\r\n\r\n\r\n\r\n\r\n \r\n /**\r\n * Merges the input properties with the previously loaded properties.\r\n * Input property names overwrite the loaded property names.\r\n * @param in the input properties\r\n */\r\n public void merge(Properties in) {\r\n if (prop != null)\r\n prop.putAll(in);\r\n else prop = in;\r\n load(prop);\r\n }\r\n \r\n private static String getProperty(String key, String defaultValue) {\r\n if (prop == null) {\r\n log.warn(\"Properties file not found! Using default: \\\"\" + defaultValue + \r\n \"\\\" for the property name: \\\"\" + key + \"\\\"\");\r\n return defaultValue;\r\n }\r\n String value = prop.getProperty(key);\r\n if (value == null || value.trim().length() == 0) {\r\n log.warn(\"Missing or invalid property name: \\\"\" + key + \"\\\", using default: \\\"\" + defaultValue + \"\\\"\");\r\n value = defaultValue;\r\n }\r\n return value;\r\n }\r\n \r\n private static void setProperties(Properties prop) {\r\n GlobalVar.prop = prop;\r\n }\r\n \r\n private static List<Feature> toFeatures(String in) {\r\n if (in == null) return null;\r\n String[] array = in.split(COMMA_REGEXP);\r\n List<Feature> list = new ArrayList<Feature>();\r\n for (String s : array) {\r\n Feature feature = Feature.valueOf(s.trim());\r\n if (feature != null)\r\n list.add(feature);\r\n }\r\n return list;\r\n }\r\n \r\n private static List<String> toStrings(String in) {\r\n if (in == null) return null;\r\n String[] array = in.split(COMMA_REGEXP);\r\n List<String> list = new ArrayList<String>();\r\n for (String s : array) {\r\n s = s.toLowerCase().trim();\r\n if (s.length() > 0)\r\n list.add(s);\r\n }\r\n return list;\r\n }\r\n \r\n private static File toFile(String in) {\r\n return in == null ? null : new File(in);\r\n }\r\n \r\n public void load(Properties prop) {\r\n setProperties(prop);\r\n \r\n // expansion parameters\r\n wrapperLevel = Integer.parseInt(getProperty(\"wrapperLevel\", \"0\"));\r\n minSeedsBracketed = Integer.parseInt(getProperty(\"minSeedsBracketed\", \"0\"));\r\n minContextLength = Integer.parseInt(getProperty(\"minContextLength\", \"1\"));\r\n maxDocSizeInKB = Integer.parseInt(getProperty(\"maxDocSizeInKB\", \"512\"));\r\n \r\n langID = getProperty(\"langID\", \"un\");\r\n langID2 = getProperty(\"langID2\", \"un\");\r\n yahooAPIKey = getProperty(\"yahooAPIKey\", \"\");\r\n yahooBossKey = getProperty(\"yahooBossKey\", \"\");\r\n bingAPIKey = getProperty(\"bingAPIKey\",\"\");\r\n googleCustomAPIKey = getProperty(\"googleCustomAPIKey\",\"\");\r\n numResults = Integer.parseInt(getProperty(\"numResults\", \"100\"));\r\n numSubSeeds = Integer.parseInt(getProperty(\"numSubSeeds\", \"0\"));\r\n timeOutInMS = Integer.parseInt(getProperty(\"timeOutInMS\", \"10000\")); // 10 sec.\r\n isFetchFromWeb = Boolean.parseBoolean(getProperty(\"isFetchFromWeb\", \"true\")); // wwc\r\n hasNoisySeeds = Boolean.parseBoolean(getProperty(\"hasNoisySeeds\", \"false\"));\r\n useGoogleSets = Boolean.parseBoolean(getProperty(\"useGoogleSets\", \"false\"));\r\n setExpander = getProperty(\"setExpander\",\r\n useGoogleSets ?\r\n \"com.rcwang.seal.expand.GoogleSets\" : \r\n \"com.rcwang.seal.expand.Seal\");\r\n useEngine = Integer.parseInt(getProperty(\"useEngine\", \"6\"));\r\n cacheDir = toFile(getProperty(\"cacheDir\", \"cache\"));\r\n localDir = toFile(getProperty(\"localDir\", \"local\"));\r\n indexDir = toFile(getProperty(\"indexDir\", \"index\")); // wwc\r\n localRoot = toFile(getProperty(\"localRoot\", null)); // wwc\r\n savedWrapperDir = toFile(getProperty(\"savedWrapperDir\", \"wrapper\")); // wwc\r\n wrapperSaving = Integer.parseInt(getProperty(\"wrapperSaving\", \"0\")); // wwc\r\n resultDir = toFile(getProperty(\"resultDir\", null));\r\n feature = Feature.valueOf(getProperty(\"feature\", \"WLW\"));\r\n policy = SeedingPolicy.valueOf(getProperty(\"policy\", \"ISS_UNSUPERVISED\"));\r\n numTrueSeeds = Integer.parseInt(getProperty(\"numTrueSeeds\", \"2\"));\r\n numPossibleSeeds = Integer.parseInt(getProperty(\"numPossibleSeeds\", \"0\"));\r\n // every hit to Google must be at least x milliseconds in between\r\n googleHitGapInMS = Long.parseLong(getProperty(\"googleHitGapInMS\", \"5000\"));\r\n expFeatures = toFeatures(getProperty(\"expFeatures\", null));\r\n expDatasets = toStrings(getProperty(\"expDatasets\", null));\r\n urlBlackList = toFile(getProperty(\"urlBlackList\", null));\r\n stopwordsList = toFile(getProperty(\"stopwordsList\", null));\r\n \r\n // evaluation parameters\r\n evalDir = new File(getProperty(\"evalDir\", \"eval\"));\r\n dataDir = new File(getProperty(\"dataDir\", \"data\"));\r\n numTrials = Integer.parseInt(getProperty(\"numTrials\", \"0\"));\r\n numExpansions = Integer.parseInt(getProperty(\"numExpansions\", \"0\"));\r\n \r\n // qa\r\n topSystem = Integer.parseInt(getProperty(\"topSystem\", \"0\"));\r\n ephyraThreshold = Double.parseDouble(getProperty(\"ephyraThreshold\", \"0\"));\r\n sealThreshold = Double.parseDouble(getProperty(\"sealThreshold\", \"0\"));\r\n interThreshold = Double.parseDouble(getProperty(\"interThreshold\", \"0\"));\r\n unionThreshold = Double.parseDouble(getProperty(\"unionThreshold\", \"0\"));\r\n method1Threshold = Double.parseDouble(getProperty(\"method1Threshold\", \"0\"));\r\n \r\n // are all relations created using Entity(String,String) constructor?\r\n explicitRelations = Boolean.parseBoolean(getProperty(\"explicitRelations\",\"false\"));\r\n \r\n // should individual content weights be stored in addition to aggregated weights?\r\n // (for NELL scoring)\r\n storeContentWeights = Boolean.parseBoolean(getProperty(\"storeContentWeights\",\"false\"));\r\n \r\n // clueweb\r\n cluewebKeepQueryFile = Boolean.parseBoolean(getProperty(\"cluewebKeepQueryFile\",\"false\"));\r\n cluewebKeepResponseFile = Boolean.parseBoolean(getProperty(\"cluewebKeepResponseFile\",\"false\"));\r\n cluewebMemoryManagement = Boolean.parseBoolean(getProperty(\"cluewebMemoryManagement\",\"true\"));\r\n multiquery = Boolean.parseBoolean(getProperty(\"multiquery\",\"false\"));\r\n }\r\n \r\n public Properties getProperties() { return prop; }\r\n \r\n public File getCacheDir() { return cacheDir; }\r\n public void setCacheDir(File cacheDir) { GlobalVar.cacheDir = cacheDir; }\r\n \r\n public File getIndexDir() { return indexDir; } //wwc\r\n public void setIndexDir(File indexDir) { GlobalVar.indexDir = indexDir; } //wwc\r\n\r\n public File getLocalDir() { return localDir; } //wwc\r\n public void setLocalDir(File localDir) { GlobalVar.localDir = localDir; } //wwc\r\n\r\n public File getLocalRoot() { return localRoot; } //wwc\r\n public void setRootOfIndexedFiles(File localRoot) { GlobalVar.localRoot = localRoot; } //wwc\r\n\r\n public File getSavedWrapperDir() { return savedWrapperDir; } //wwc\r\n public void setSavedWrapperDir(File savedWrapperDir) { GlobalVar.savedWrapperDir = savedWrapperDir; } //wwc\r\n\r\n public int getWrapperSaving() { return wrapperSaving; } //wwc\r\n public void setWrapperSaving(int wrapperSaving) { GlobalVar.wrapperSaving = wrapperSaving; } //wwc\r\n\r\n public File getDataDir() { return dataDir; }\r\n public void setDataDir(File dataDir) { GlobalVar.dataDir = dataDir; }\r\n \r\n public File getEvalDir() { return evalDir; }\r\n public void setEvalDir(File evalDir) { GlobalVar.evalDir = evalDir; }\r\n \r\n public String getLangID() { return langID; }\r\n public void setLangID(String langID) { GlobalVar.langID = langID; }\r\n \r\n public int getMaxDocSizeInKB() { return maxDocSizeInKB; }\r\n public void setMaxDocSizeInKB(int maxDocSizeInKB) { GlobalVar.maxDocSizeInKB = maxDocSizeInKB; }\r\n \r\n public int getMinContextLength() { return minContextLength; }\r\n public void setMinContextLength(int minContextLength) { GlobalVar.minContextLength = minContextLength; }\r\n \r\n public int getMinSeedsBracketed() { return minSeedsBracketed; }\r\n public void setMinSeedsBracketed(int minSeedsBracketed) { GlobalVar.minSeedsBracketed = minSeedsBracketed; }\r\n \r\n public int getNumExpansions() { return numExpansions; }\r\n public void setNumExpansions(int numExpansions) { GlobalVar.numExpansions = numExpansions; }\r\n \r\n public int getNumResults() { return numResults; }\r\n public void setNumResults(int numResults) { GlobalVar.numResults = numResults; }\r\n \r\n public int getNumSubSeeds() { return numSubSeeds; }\r\n public void setNumSubSeeds(int numSubSeeds) { GlobalVar.numSubSeeds = numSubSeeds; }\r\n \r\n public int getNumTrials() { return numTrials; }\r\n public void setNumTrials(int numTrials) { GlobalVar.numTrials = numTrials; }\r\n\r\n public File getResultDir() { return resultDir; }\r\n public void setResultDir(File resultDir) { GlobalVar.resultDir = resultDir; }\r\n \r\n public File getStopwordsList() { return stopwordsList; }\r\n public void setStopwordsList(File stopwordsList) { GlobalVar.stopwordsList = stopwordsList; }\r\n \r\n public int getTimeOutInMS() { return timeOutInMS; }\r\n public void setTimeOutInMS(int timeOutInMS) { GlobalVar.timeOutInMS = timeOutInMS; }\r\n \r\n public File getUrlBlackList() { return urlBlackList; }\r\n public void setUrlBlackList(File urlBlackList) { GlobalVar.urlBlackList = urlBlackList; }\r\n \r\n public String getYahooAPIKey() { return yahooAPIKey; }\r\n public void setYahooAPIKey(String yahooAPIKey) { GlobalVar.yahooAPIKey = yahooAPIKey; }\r\n \r\n public boolean getIsFetchFromWeb() { return isFetchFromWeb; } //wwc\r\n public void setIsFetchFromWeb(boolean isFetchFromWeb) { GlobalVar.isFetchFromWeb = isFetchFromWeb; } //wwc\r\n\r\n public boolean hasNoisySeeds() { return hasNoisySeeds; }\r\n public void setHasNoisySeeds(boolean hasNoisySeeds) { GlobalVar.hasNoisySeeds = hasNoisySeeds; }\r\n\r\n public Feature getFeature() { return feature; }\r\n public void setFeature(Feature feature) { GlobalVar.feature = feature; }\r\n \r\n public SeedingPolicy getPolicy() { return policy; }\r\n public void setPolicy(SeedingPolicy policy) { GlobalVar.policy = policy; }\r\n\r\n public int getNumPossibleSeeds() { return numPossibleSeeds; }\r\n public void setNumPossibleSeeds(int numPossibleSeeds) { GlobalVar.numPossibleSeeds = numPossibleSeeds; }\r\n\r\n public int getNumTrueSeeds() { return numTrueSeeds; }\r\n public void setNumTrueSeeds(int numTrueSeeds) { GlobalVar.numTrueSeeds = numTrueSeeds; }\r\n\r\n public List<Feature> getExpFeatures() { return expFeatures; }\r\n public void setExpFeatures(List<Feature> expFeatures) { GlobalVar.expFeatures = expFeatures; }\r\n\r\n public List<String> getExpDatasets() { return expDatasets; }\r\n public void setExpDatasets(List<String> expDatasets) { GlobalVar.expDatasets = expDatasets; }\r\n\r\n public long getGoogleHitGapInMS() { return googleHitGapInMS; }\r\n public void setGoogleHitGapInMS(long googleHitGap) { GlobalVar.googleHitGapInMS = googleHitGap; }\r\n\r\n public int getTopSystem() { return topSystem; }\r\n public void setTopSystem(int topSystem) { GlobalVar.topSystem = topSystem; }\r\n\r\n public double getEphyraThreshold() { return ephyraThreshold; }\r\n public void setEphyraThreshold(double ephyraThreshold) { GlobalVar.ephyraThreshold = ephyraThreshold; }\r\n\r\n public double getSealThreshold() { return sealThreshold; }\r\n public void setSealThreshold(double sealThreshold) { GlobalVar.sealThreshold = sealThreshold; }\r\n\r\n public double getInterThreshold() { return interThreshold; }\r\n public void setInterThreshold(double interThreshold) { GlobalVar.interThreshold = interThreshold; }\r\n\r\n public double getUnionThreshold() { return unionThreshold; }\r\n public void setUnionThreshold(double unionThreshold) { GlobalVar.unionThreshold = unionThreshold; }\r\n\r\n public double getMethod1Threshold() { return method1Threshold; }\r\n public void setMethod1Threshold(double method1Threshold) { GlobalVar.method1Threshold = method1Threshold; }\r\n\r\n public boolean isUseGoogleSets() { return useGoogleSets; }\r\n public void setUseGoogleSets(boolean useGoogleSets) {GlobalVar.useGoogleSets = useGoogleSets; }\r\n\r\n public String getLangID2() { return langID2; }\r\n public void setLangID2(String langID2) { GlobalVar.langID2 = langID2; }\r\n\r\n public int getUseEngine() { return useEngine; }\r\n public void setUseEngine(int useEngine) { GlobalVar.useEngine = useEngine; }\r\n\r\n public int getWrapperLevel() { return wrapperLevel; }\r\n public void setWrapperLevel(int wrapperLevel) { GlobalVar.wrapperLevel = wrapperLevel; }\r\n\r\n public String getYahooBossKey() { return yahooBossKey; }\r\n public void setYahooBossKey(String yahooBossKey) { GlobalVar.yahooBossKey = yahooBossKey; }\r\n\r\n public boolean getExplicitRelations() { return explicitRelations; }\r\n public boolean isStoreContentWeights() { return storeContentWeights; }\r\n\r\n public String getBingAPIKey() { return bingAPIKey; }\r\n public void setBingAPIKey(String k) { GlobalVar.bingAPIKey = k; }\r\n\r\n public String getGoogleCustomAPIKey() { return googleCustomAPIKey; }\r\n public void setGoogleCustomAPIKey(String k) { GlobalVar.googleCustomAPIKey = k; }\r\n \r\n public boolean getClueWebMemoryManagement() { return cluewebMemoryManagement; }\r\n public void setClueWebMemoryManagement(boolean b) { cluewebMemoryManagement = b; }\r\n \r\n public boolean getClueWebKeepResponseFile() { return cluewebKeepResponseFile; }\r\n public void setClueWebKeepResponseFile(boolean b) { cluewebKeepResponseFile = b; }\r\n \r\n public boolean getClueWebKeepQueryFile() { return cluewebKeepQueryFile; }\r\n public void setClueWebKeepQueryFile(boolean b) { cluewebKeepQueryFile = b; }\r\n \r\n public boolean isMultiquery() { return multiquery; }\r\n public void setMultiquery(boolean b) { multiquery = b; }\r\n\r\n\r\n\r\n\r\n public String getSetExpander() { return setExpander; }\r\n\r\n\r\n\r\n\r\n }\r",
"public class Helper {\r\n \r\n public static Logger log = Logger.getLogger(Helper.class);\r\n \r\n public static final String UNICODE = \"UTF-8\";\r\n public static final String COMMON_ENCODING = \"ISO-8859-1\";\r\n public static final String DATE_FORMAT = \"yyyy-MM-dd\"; // must match below\r\n public static final String DATE_PATTERN = \"\\\\d+{4}-\\\\d+{2}-\\\\d+{2}\"; // must match above\r\n public static final String TIME_FORMAT = \"h:mm:ss aa\";\r\n public static final String DATE_TIME_FORMAT = DATE_FORMAT + \" \" + TIME_FORMAT;\r\n public static final NumberFormat NUM_FORMAT = NumberFormat.getInstance();\r\n \r\n public static String repeat(char c, int n) {\r\n StringBuffer buf = new StringBuffer();\r\n for (; n > 0; n--)\r\n buf.append(c);\r\n return buf.toString();\r\n }\r\n \r\n public static String center(String s, char filler, int width) {\r\n if (s.length() >= width) return s;\r\n int numFillers = (width - s.length()) / 2;\r\n return repeat(filler, numFillers) + s + repeat(filler, numFillers);\r\n }\r\n \r\n public static String addQuote(String s) {\r\n s = s.trim();\r\n if (!s.startsWith(\"\\\"\"))\r\n s = \"\\\"\" + s;\r\n if (!s.endsWith(\"\\\"\"))\r\n s += \"\\\"\";\r\n return s;\r\n }\r\n \r\n public static double getPDF(double x, double avg, double std) {\r\n double diff = x - avg;\r\n double exp = Math.exp(-0.5 * Math.pow(diff / std, 2));\r\n return exp / (std * Math.sqrt(2 * Math.PI));\r\n }\r\n \r\n public static String addQuote(String[] ss) {\r\n StringBuffer buf = new StringBuffer();\r\n for (String s : ss)\r\n buf.append(buf.length() > 0 ? \" \" : \"\").append(addQuote(s));\r\n return buf.toString();\r\n }\r\n \r\n public static File createDir(File dir) {\r\n if (dir != null && !dir.isDirectory()) {\r\n log.info(\"Creating directory: \" + dir.getAbsolutePath());\r\n if (!dir.mkdirs())\r\n log.error(\"Could not create requested directories for \"+dir.getAbsolutePath());\r\n }\r\n return dir;\r\n }\r\n \r\n public static File createTempFile (String content) {\r\n File temp = null;\r\n try {\r\n temp = File.createTempFile(\"tmp\", null);\r\n } catch (IOException ioe) {\r\n log.error(\"Error creating temp file: \" + ioe);\r\n return null;\r\n }\r\n temp.deleteOnExit();\r\n writeToFile(temp, content, \"UTF-8\", false);\r\n return temp;\r\n }\r\n \r\n public static String decodeURLString(String s) {\r\n if (s == null) return null;\r\n try {\r\n return URLDecoder.decode(s, UNICODE);\r\n } catch (UnsupportedEncodingException e) {\r\n log.error(e.toString());\r\n return null;\r\n }\r\n }\r\n \r\n public static void die(String s) {\r\n System.err.println(\"[FATAL] \" + s);\r\n System.exit(1);\r\n }\r\n \r\n public static boolean empty(EntityList entityList) {\r\n return entityList == null || entityList.isEmpty();\r\n }\r\n \r\n public static boolean empty(String s) {\r\n return s == null || s.trim().length() == 0;\r\n }\r\n \r\n // encode the query and formulate the query URL\r\n public static String encodeURLString(String s) {\r\n if (s == null) return null;\r\n try {\r\n return URLEncoder.encode(s, UNICODE);\r\n } catch (UnsupportedEncodingException e) {\r\n log.error(e.toString());\r\n return null;\r\n }\r\n }\r\n \r\n /**\r\n * Returns the String bounded by \"left\" and \"after\" in String s\r\n * @param s\r\n * @param left\r\n * @param right\r\n * @return the bounded String\r\n */\r\n public static String extract(String s, String left, String right) {\r\n int leftOffset, rightOffset;\r\n if (left == null) {\r\n leftOffset = 0;\r\n left = \"\";\r\n } else {\r\n leftOffset = s.indexOf(left);\r\n if (leftOffset == -1)\r\n return null;\r\n }\r\n if (right == null) {\r\n rightOffset = s.length();\r\n } else {\r\n rightOffset = s.indexOf(right, leftOffset + left.length());\r\n if (rightOffset == -1)\r\n return null;\r\n }\r\n return s.substring(leftOffset + left.length(), rightOffset);\r\n }\r\n\r\n public static String formatNumber(double number, int decimal) {\r\n NUM_FORMAT.setMaximumFractionDigits(decimal);\r\n NUM_FORMAT.setMinimumFractionDigits(decimal);\r\n return NUM_FORMAT.format(number).replace(\",\", \"\");\r\n }\r\n \r\n public static int getStringSize(String s) {\r\n int docSize = -1;\r\n try {\r\n docSize = s.getBytes(\"US-ASCII\").length;\r\n } catch (UnsupportedEncodingException e) {\r\n e.printStackTrace();\r\n }\r\n return docSize;\r\n }\r\n \r\n /***\r\n * Creates a unique ID based on the current date and time\r\n * @return a unique ID\r\n */\r\n public static String getUniqueID () {\r\n Calendar cal = Calendar.getInstance(TimeZone.getDefault());\r\n SimpleDateFormat sdf = new SimpleDateFormat(\"MMdd-HHmmss\");\r\n sdf.setTimeZone(TimeZone.getDefault());\r\n return sdf.format(cal.getTime());\r\n }\r\n \r\n public static Properties loadPropertiesFile(File propFile) {\r\n if (propFile == null)\r\n return null;\r\n Properties props = new Properties();\r\n InputStream in;\r\n try {\r\n in = readFileToStream(propFile);\r\n if (in != null) {\r\n props.load(in);\r\n in.close();\r\n }\r\n } catch (FileNotFoundException e) {\r\n log.error(\"Properties file not found: \" + e);\r\n return null;\r\n } catch (IOException e) {\r\n log.error(\"Read properties file error: \" + e);\r\n return null;\r\n }\r\n return props;\r\n }\r\n \r\n public static <T> T loadSerialized(File file, Class<? extends T> c) {\r\n log.info(\"Loading serialized object from: \" + file);\r\n FileInputStream fis = null;\r\n ObjectInputStream in = null;\r\n T object = null;\r\n try {\r\n fis = new FileInputStream(file);\r\n in = new ObjectInputStream(fis);\r\n object = c.cast(in.readObject());\r\n in.close();\r\n } catch(IOException ex) {\r\n ex.printStackTrace();\r\n } catch(ClassNotFoundException ex) {\r\n ex.printStackTrace();\r\n }\r\n return object;\r\n }\r\n\r\n public static double log2(double d) {\r\n return Math.log(d) / Math.log(2);\r\n }\r\n \r\n public static String merge(String[] strList, String delimiter) {\r\n StringBuffer buf = new StringBuffer();\r\n for (String s : strList) {\r\n if (buf.length() > 0)\r\n buf.append(delimiter);\r\n buf.append(s);\r\n }\r\n return buf.toString();\r\n }\r\n \r\n public static void printElapsedTime(long startTime) {\r\n log.info(\"Elapsed time: \" + (System.currentTimeMillis() - startTime) / 1000.0 + \" seconds\");\r\n }\r\n \r\n public static void printDebugInfo() {\r\n log.info(\"Originator Size: \" + Originator.size() + \" (\" + Originator.getNumStrings() + \")\");\r\n log.info(\"String Size: \" + StringFactory.getStrSize());\r\n log.info(\"String ID Size: \" + StringFactory.getIDSize());\r\n Helper.printMemoryUsed();\r\n }\r\n \r\n public static void printMemoryUsed() {\r\n for (int i = 0; i < 3; i++) System.gc();\r\n long memSize = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();\r\n String memSizeStr = Helper.formatNumber((double) memSize / 1024 / 1024, 2);\r\n log.info(\" Memory used: \" + memSizeStr + \"MB\");\r\n }\r\n \r\n public static String readFile(File f) {\r\n return readFile(f, \"UTF-8\", false);\r\n }\r\n\r\n /**\r\n * Reads in a file, if not found, search on the class path\r\n * @param file the input file\r\n * @param charset the character set\r\n * @param binary is the file binary or text (non-binary)?\r\n * @return the content of the file\r\n */\r\n public static String readFile(File file, String charset, boolean binary) {\r\n if (file == null || charset == null)\r\n return null;\r\n InputStream in = readFileToStream(file);\r\n if (in == null)\r\n return null;\r\n StringBuffer buf = new StringBuffer();\r\n try {\r\n BufferedReader bReader = new BufferedReader(new InputStreamReader(in, charset));\r\n if (!binary) {\r\n String line;\r\n while ((line = bReader.readLine()) != null)\r\n buf.append(line).append(\"\\n\");\r\n } else {\r\n char[] c = new char[(int) file.length()];\r\n bReader.read(c);\r\n buf.append(c);\r\n }\r\n bReader.close();\r\n } catch (Exception e) {\r\n log.error(\"Could not read \\\"\" + file + \"\\\": \" + e);\r\n return null;\r\n }\r\n String result = buf.toString();\r\n // get rid of BOM (byte order marker) from UTF-8 file\r\n if (result.length() > 0 && result.charAt(0) == 65279)\r\n result = result.substring(1);\r\n return result;\r\n }\r\n \r\n public static InputStream readFileToStream(File in) {\r\n if (in == null) return null;\r\n InputStream s = null;\r\n try {\r\n if (in.exists()) // if file exist locally\r\n s = new FileInputStream(in);\r\n if (s == null) // if file exist somewhere on the class path\r\n s = ClassLoader.getSystemResourceAsStream(in.getPath());\r\n if (s == null) { // if file still could not be found\r\n log.error(\"Could not find \\\"\" + in + \"\\\" locally (\"+in.getAbsolutePath()+\") or on classpath\");\r\n return null;\r\n }\r\n } catch (Exception e) {\r\n log.error(\"Could not read \\\"\" + in + \"\\\": \" + e);\r\n return null;\r\n }\r\n return s;\r\n }\r\n \r\n public static void recursivelyRemove(File f) {\r\n if (f == null || !f.exists()) return;\r\n if (f.isDirectory()) {\r\n File[] files = f.listFiles();\r\n for (File file : files)\r\n recursivelyRemove(file);\r\n }\r\n String type = f.isDirectory() ? \"directory\" : \"file\";\r\n boolean deleted = f.delete();\r\n if (!deleted)\r\n log.error(\"Cannot delete the \" + type + \": \" + f);\r\n else log.debug(\"Successfully deleted the \" + type + \": \" + f);\r\n }\r\n \r\n public static String removeQuote(String s) {\r\n if (s == null) return null;\r\n s = s.trim();\r\n if (s.startsWith(\"\\\"\") && s.endsWith(\"\\\"\"))\r\n s = s.substring(1, s.length()-1);\r\n return s;\r\n }\r\n \r\n public static void saveSerialized(Object object, File file, boolean overwrite) {\r\n if (!overwrite && file.exists()) {\r\n log.info(\"Serialized file \" + file + \" already exists! Skip saving...\");\r\n return;\r\n }\r\n log.info(\"Saving serialized object to: \" + file);\r\n if (file.getParentFile() != null)\r\n Helper.createDir(file.getParentFile());\r\n FileOutputStream fos = null;\r\n ObjectOutputStream out = null;\r\n try {\r\n fos = new FileOutputStream(file);\r\n out = new ObjectOutputStream(fos);\r\n out.writeObject(object);\r\n out.close();\r\n } catch(IOException ex) {\r\n ex.printStackTrace();\r\n }\r\n }\r\n\r\n public static void sortByLength(List<String> list, final boolean ascending) {\r\n Comparator<String> c = new Comparator<String>() {\r\n public int compare(String e1, String e2) {\r\n int length1 = e1.length();\r\n int length2 = e2.length();\r\n if (ascending)\r\n return Double.compare(length1, length2);\r\n else return Double.compare(length2, length1);\r\n }\r\n };\r\n Collections.sort(list, c);\r\n }\r\n \r\n /**\r\n * Converts an integer to a binary array with a specified max size\r\n * input: 11, output: [1011]\r\n * @param integer\r\n * @param size\r\n * @return\r\n */\r\n public static boolean[] toBinaryArray(int integer, int size) {\r\n boolean[] b = new boolean[size];\r\n String s = Integer.toBinaryString(integer);\r\n if (s.length() > b.length)\r\n s = s.substring(s.length()-b.length);\r\n // algorithm bug fixed kmr jan 2012\r\n // the 1s place is at the end of the string, so start there\r\n for (int i = s.length()-1; i >=0; i--)\r\n // the 1s element is at b[0] so start there\r\n b[s.length()-1-i] = (s.charAt(i) == '1');\r\n return b;\r\n }\r\n\r\n public static String toFileName(String s) {\r\n return s.replaceAll(\"[\\\\/:\\\\*?\\\"<>|\\\\s]+\", \"_\");\r\n }\r\n\r\n public static File toFileOrDie(String filename) {\r\n if (filename == null)\r\n die(\"Could not find the file: \" + filename);\r\n File file = new File(filename);\r\n if (!file.exists())\r\n die(\"Could not find the file: \" + filename);\r\n return file;\r\n }\r\n\r\n public static String toReadableString(Collection<String> list) {\r\n Set<String> seeds = new TreeSet<String>();\r\n if (list != null)\r\n seeds.addAll(list);\r\n StringBuffer buf = new StringBuffer();\r\n buf.append(\"{\");\r\n for (String seed : seeds) {\r\n if (buf.length() > 1)\r\n buf.append(\", \");\r\n buf.append(seed);\r\n }\r\n buf.append(\"}\");\r\n return buf.toString();\r\n }\r\n\r\n public static String toReadableDouble(Collection<Double> doubles) {\r\n StringBuffer buf = new StringBuffer();\r\n buf.append(\"{\");\r\n for (Double d : doubles) {\r\n if (buf.length() > 1)\r\n buf.append(\", \");\r\n buf.append(Helper.formatNumber(d, 5));\r\n }\r\n buf.append(\"}\");\r\n return buf.toString();\r\n }\r\n \r\n public static String toReadableTime(Long timestamp, String format) {\r\n SimpleDateFormat sdf = new SimpleDateFormat(format);\r\n sdf.setTimeZone(TimeZone.getDefault());\r\n if (timestamp == null)\r\n timestamp = System.currentTimeMillis();\r\n return sdf.format(new Date(timestamp));\r\n }\r\n\r\n public static String toSeedsFileName(Collection<String> seedList) {\r\n Set<String> seeds = new TreeSet<String>();\r\n if (seedList != null)\r\n seeds.addAll(seedList);\r\n StringBuffer buf = new StringBuffer();\r\n for (String seed : seeds) {\r\n if (buf.length() > 0)\r\n buf.append(\"+\");\r\n buf.append(seed);\r\n }\r\n return toFileName(buf.toString());\r\n }\r\n \r\n /**\r\n * Converts a String array to a Collection of Unicode\r\n * @param strs\r\n * @return\r\n */\r\n public static Set<String> toUnicode(Collection<String> strs) {\r\n Set<String> set = new HashSet<String>();\r\n if (strs == null) return set;\r\n for (String s : strs) {\r\n s = toUnicode(s);\r\n if (!empty(s))\r\n set.add(s.toLowerCase()); // added 04/21/2008\r\n }\r\n return set;\r\n }\r\n\r\n /**\r\n * Converts a string to unicode\r\n * @param s\r\n * @return\r\n */\r\n public static String toUnicode(String s) {\r\n if (s == null) return null;\r\n try {\r\n s = new String(s.getBytes(COMMON_ENCODING), UNICODE);\r\n } catch (UnsupportedEncodingException e) {\r\n log.error(e);\r\n }\r\n return s.trim();\r\n }\r\n\r\n public static URL toURL(String s) {\r\n try {\r\n return new URL(s);\r\n } catch (MalformedURLException e) {\r\n return null;\r\n }\r\n }\r\n\r\n public static void writeToFile(File out, String content) {\r\n writeToFile(out, content, UNICODE, false);\r\n }\r\n\r\n public static void writeToFile(File out, String content, boolean append) {\r\n writeToFile(out, content, UNICODE, append);\r\n }\r\n \r\n public static void writeToFile(File out, String content, String charset, boolean append) {\r\n if (out == null || content == null) return;\r\n try {\r\n BufferedWriter bWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(out, append), charset));\r\n bWriter.write(content);\r\n bWriter.close();\r\n } catch (IOException e) {\r\n log.error(\"Writing to \" + out + \": \" + e);\r\n }\r\n }\r\n\r\npublic static Object toReadableString(Set<EntityLiteral> contents) {\r\n Set<EntityLiteral> seeds = new TreeSet<EntityLiteral>();\r\n if (contents != null)\r\n seeds.addAll(contents);\r\n StringBuffer buf = new StringBuffer();\r\n buf.append(\"{\");\r\n for (EntityLiteral seed : seeds) {\r\n if (buf.length() > 1)\r\n buf.append(\", \");\r\n buf.append(seed.toString());\r\n }\r\n buf.append(\"}\");\r\n return buf.toString();\r\n }\r\n}\r"
] | import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.log4j.Logger;
import com.rcwang.seal.eval.EvalResult;
import com.rcwang.seal.eval.Evaluator;
import com.rcwang.seal.fetch.DocumentSet;
import com.rcwang.seal.rank.Ranker.Feature;
import com.rcwang.seal.util.GlobalVar;
import com.rcwang.seal.util.Helper;
| /**************************************************************************
* Developed by Language Technologies Institute, Carnegie Mellon University
* Written by Richard Wang (rcwang#cs,cmu,edu)
**************************************************************************/
package com.rcwang.seal.expand;
public class IterativeSeal {
public static Logger log = Logger.getLogger(IterativeSeal.class);
| public static GlobalVar gv = GlobalVar.getGlobalVar();
| 4 |
nimble-platform/identity-service | identity-service/src/test/java/eu/nimble/core/infrastructure/identity/config/DefaultTestConfiguration.java | [
"@Service\r\n@SuppressWarnings(\"Duplicates\")\r\npublic class EmailService {\r\n\r\n private static final Logger logger = LoggerFactory.getLogger(EmailService.class);\r\n\r\n @Autowired\r\n private JavaMailSender emailSender;\r\n\r\n @Autowired\r\n private UblUtils ublUtils;\r\n\r\n @Autowired\r\n private MessageSource messageSource;\r\n\r\n @Autowired\r\n private TemplateEngine textMailTemplateEngine;\r\n\r\n @Value(\"${spring.mail.defaultFrom}\")\r\n private String defaultFrom;\r\n\r\n @Value(\"${spring.mail.debug:false}\")\r\n private Boolean debug;\r\n\r\n @Value(\"${nimble.frontend.url}\")\r\n private String frontendUrl;\r\n\r\n @Value(\"${nimble.supportEmail}\")\r\n private String supportEmail;\r\n\r\n @Value(\"${nimble.platformName}\")\r\n private String platformVersion;\r\n\r\n @Value(\"${spring.mail.platformName}\")\r\n private String platformName;\r\n\r\n @Value(\"${nimble.frontend.registration.url}\")\r\n private String frontendRegistrationUrl;\r\n\r\n @Value(\"${nimble.frontend.company-details.url}\")\r\n private String companyDetailsUrl;\r\n\r\n @Value(\"${spring.mail.languages}\")\r\n private String mailTemplateLanguages;\r\n\r\n @Value(\"${nimble.companyDataUpdateEmail}\")\r\n private String companyDataUpdateEmail;\r\n\r\n public void sendResetCredentialsLink(String toEmail, String credentials, String language) throws UnsupportedEncodingException{\r\n String resetCredentialsURL = frontendUrl + \"/#/user-mgmt/forgot/?key=\" + URLEncoder.encode(credentials, \"UTF-8\");\r\n Context context = new Context();\r\n context.setVariable(\"resetPasswordURL\", resetCredentialsURL);\r\n context.setVariable(\"platformName\",platformName);\r\n\r\n String version = Strings.isNullOrEmpty(platformVersion) ? \"\": String.format(\" (%s)\",platformVersion);\r\n String subject = getMailSubject(NimbleMessageCode.MAIL_SUBJECT_RESET_CREDENTIALS_LINK,language,Arrays.asList(platformName,version));\r\n\r\n this.send(new String[]{toEmail}, subject, getTemplateName(\"password-reset\",language), context);\r\n }\r\n\r\n public void sendInvite(String toEmail, String senderName, String companyName, Collection<String> roles, String language) throws UnsupportedEncodingException {\r\n String invitationUrl = String.format(\"%s/%s/?email=%s\",frontendUrl,frontendRegistrationUrl,URLEncoder.encode(toEmail, \"UTF-8\"));\r\n\r\n Context context = new Context();\r\n context.setVariable(\"senderName\", senderName);\r\n context.setVariable(\"companyName\", companyName);\r\n context.setVariable(\"invitationUrl\", invitationUrl);\r\n context.setVariable(\"roles\", roles);\r\n context.setVariable(\"platformName\",platformName);\r\n\r\n String version = Strings.isNullOrEmpty(platformVersion) ? \"\": String.format(\" (%s)\",platformVersion);\r\n String subject = getMailSubject(NimbleMessageCode.MAIL_SUBJECT_INVITATION,language,Arrays.asList(platformName,version));\r\n\r\n this.send(new String[]{toEmail}, subject, getTemplateName(\"invitation\",language), context);\r\n }\r\n\r\n public void sendSubscriptionSummary(List<String> toEmail, List<SubscriptionSummary> subscriptionSummaryList, String language) throws UnsupportedEncodingException {\r\n Context context = new Context();\r\n\r\n // keeps the list of SubscriptionMailModel which corresponds to the 'subscriptions' variable in mail template\r\n List<SubscriptionMailModel> subscriptionMailModels = new ArrayList<>();\r\n // populate subscriptionMailModels array\r\n for (SubscriptionSummary subscriptionSummary : subscriptionSummaryList) {\r\n // retrieve the urls for product details\r\n List<String> productDetailsUrls = new ArrayList<>();\r\n for (int i = 0; i < subscriptionSummary.getCatalogueIds().size(); i++) {\r\n productDetailsUrls.add(String.format(\"%s/#/product-details?catalogueId=%s&id=%s\",frontendUrl,URLEncoder.encode(subscriptionSummary.getCatalogueIds().get(i), \"UTF-8\"),\r\n URLEncoder.encode(subscriptionSummary.getProductIds().get(i), \"UTF-8\")));\r\n }\r\n // set title of subscription\r\n String title;\r\n // company\r\n if(subscriptionSummary.getCompanyName() != null){\r\n title = String.format(\"The following products are published/updated by %s\",subscriptionSummary.getCompanyName());\r\n }\r\n // category\r\n else{\r\n title = String.format(\"The following products are published/updated on category: %s\",subscriptionSummary.getCategoryName());\r\n }\r\n // create the subscription mail model\r\n SubscriptionMailModel subscriptionMailModel = new SubscriptionMailModel();\r\n subscriptionMailModel.setTitle(title);\r\n subscriptionMailModel.setProductUrls(productDetailsUrls);\r\n\r\n subscriptionMailModels.add(subscriptionMailModel);\r\n }\r\n // set context variables\r\n context.setVariable(\"subscriptions\", subscriptionMailModels);\r\n context.setVariable(\"platformName\",platformName);\r\n // set mail subject\r\n String version = Strings.isNullOrEmpty(platformVersion) ? \"\": String.format(\" (%s)\",platformVersion);\r\n String subject = getMailSubject(NimbleMessageCode.MAIL_SUBJECT_SUBSCRIPTION,language,Arrays.asList(platformName,version));\r\n\r\n this.send(toEmail.toArray(new String[0]), subject, getTemplateName(\"subscription\",language), context);\r\n }\r\n\r\n public void informInviteExistingCompany(String toEmail, String senderName, String companyName, Collection<String> roles, String language) {\r\n Context context = new Context();\r\n context.setVariable(\"senderName\", senderName);\r\n context.setVariable(\"companyName\", companyName);\r\n context.setVariable(\"nimbleUrl\", frontendUrl);\r\n context.setVariable(\"roles\", roles);\r\n context.setVariable(\"platformName\",platformName);\r\n\r\n String version = Strings.isNullOrEmpty(platformVersion) ? \"\": String.format(\" (%s)\",platformVersion);\r\n String subject = getMailSubject(NimbleMessageCode.MAIL_SUBJECT_INVITATION_EXISTING_COMPANY, language, Arrays.asList(companyName,platformName,version));\r\n\r\n this.send(new String[]{toEmail}, subject, getTemplateName(\"invitation_existing_company\",language), context);\r\n }\r\n\r\n public void notifyPlatformManagersCompanyDataUpdates(List<String> emails, PersonType user, PartyType company, CompanyDetailsUpdates companyDetailsUpdates, String language){\r\n Context context = new Context();\r\n\r\n // collect info of user\r\n String username = user.getFirstName() + \" \" + user.getFamilyName();\r\n context.setVariable(\"username\", username);\r\n\r\n // collect info of company and platform\r\n context.setVariable(\"companyName\", ublUtils.getName(company));\r\n context.setVariable(\"platformName\",platformName);\r\n // company updates\r\n context.setVariable(\"companyUpdates\",getMailContentForCompanyDetailsUpdates(companyDetailsUpdates,language));\r\n // link to the company details\r\n context.setVariable(\"companyDetailsUrl\", String.format(\"%s/%s?id=%s&viewMode=mgmt\",frontendUrl,companyDetailsUrl,company.getPartyIdentification().get(0).getID()));\r\n\r\n String version = Strings.isNullOrEmpty(platformVersion) ? \"\": String.format(\" (%s)\",platformVersion);\r\n String subject = getMailSubject(NimbleMessageCode.MAIL_SUBJECT_COMPANY_DATA_UPDATED, language, Arrays.asList(platformName,version));\r\n\r\n // if the specific email address is defined for the company data updates, use it to send the email\r\n // otherwise, send the email to all platform managers\r\n if(!Strings.isNullOrEmpty(this.companyDataUpdateEmail)){\r\n emails = Arrays.asList(this.companyDataUpdateEmail);\r\n }\r\n\r\n this.send(emails.toArray(new String[]{}), subject, getTemplateName(\"company_data_updated\",language), context);\r\n }\r\n\r\n public void notifyPlatformManagersNewCompany(List<String> emails, PersonType representative, PartyType company, String language) {\r\n\r\n Context context = new Context();\r\n\r\n // collect info of user\r\n String username = representative.getFirstName() + \" \" + representative.getFamilyName();\r\n context.setVariable(\"username\", username);\r\n\r\n String userEmail = null;\r\n if (representative.getContact() != null)\r\n userEmail = representative.getContact().getElectronicMail();\r\n context.setVariable(\"userEmail\", userEmail);\r\n\r\n // collect info of user\r\n context.setVariable(\"companyName\", ublUtils.getName(company));\r\n context.setVariable(\"companyID\", company.getHjid());\r\n context.setVariable(\"platformName\",platformName);\r\n\r\n // collect info of company\r\n if (company.getPostalAddress() != null) {\r\n AddressType address = company.getPostalAddress();\r\n String countryName = address.getCountry() != null && address.getCountry().getIdentificationCode() != null? CountryUtil.getCountryNameByISOCode(address.getCountry().getIdentificationCode().getValue()) : null;\r\n context.setVariable(\"companyCountry\", countryName);\r\n context.setVariable(\"companyStreet\", address.getStreetName());\r\n context.setVariable(\"companyBuildingNumber\", address.getBuildingNumber());\r\n context.setVariable(\"companyCity\", address.getCityName());\r\n context.setVariable(\"companypostalCode\", address.getPostalZone());\r\n }\r\n\r\n String version = Strings.isNullOrEmpty(platformVersion) ? \"\": String.format(\" (%s)\",platformVersion);\r\n String subject = getMailSubject(NimbleMessageCode.MAIL_SUBJECT_COMPANY_REGISTERED, language, Arrays.asList(platformName,version));\r\n\r\n this.send(emails.toArray(new String[]{}), subject, getTemplateName(\"new_company\",language), context);\r\n }\r\n\r\n public void notifyVerifiedCompany(String email, PersonType legalRepresentative, PartyType company, String language) {\r\n\r\n Context context = new Context();\r\n context.setVariable(\"firstName\", legalRepresentative.getFirstName());\r\n context.setVariable(\"familyName\", legalRepresentative.getFamilyName());\r\n context.setVariable(\"companyName\", ublUtils.getName(company));\r\n context.setVariable(\"supportEmail\", supportEmail);\r\n context.setVariable(\"nimbleUrl\", frontendUrl);\r\n context.setVariable(\"platformName\",platformName);\r\n\r\n String version = Strings.isNullOrEmpty(platformVersion) ? \"\": String.format(\" (%s)\",platformVersion);\r\n String subject = getMailSubject(NimbleMessageCode.MAIL_SUBJECT_COMPANY_VERIFIED,language,Arrays.asList(platformName,version));\r\n\r\n this.send(new String[]{email}, subject, getTemplateName(\"company_verified\",language), context);\r\n }\r\n\r\n public void notifyDeletedCompany(List<PersonType> legalRepresentatives, PartyType company, String language) {\r\n\r\n String companyName = ublUtils.getName(company);\r\n for (PersonType legalRepresentative : legalRepresentatives) {\r\n Context context = new Context();\r\n context.setVariable(\"firstName\", legalRepresentative.getFirstName());\r\n context.setVariable(\"familyName\", legalRepresentative.getFamilyName());\r\n context.setVariable(\"companyName\", companyName);\r\n context.setVariable(\"platformName\",platformName);\r\n\r\n String version = Strings.isNullOrEmpty(platformVersion) ? \"\": String.format(\" (%s)\",platformVersion);\r\n String subject = getMailSubject(NimbleMessageCode.MAIL_SUBJECT_COMPANY_DELETED,language,Arrays.asList(platformName,version));\r\n\r\n try {\r\n this.send(new String[]{legalRepresentative.getContact().getElectronicMail()}, subject, getTemplateName(\"company_deleted\",language), context);\r\n }catch (Exception e){\r\n logger.error(\"Failed to send email:\",e);\r\n }\r\n }\r\n }\r\n\r\n private void send(String[] to, String subject, String template, Context context) {\r\n\r\n SimpleMailMessage mailMessage = new SimpleMailMessage();\r\n String message = this.textMailTemplateEngine.process(template, context);\r\n\r\n if (debug) {\r\n logger.info(message);\r\n return;\r\n }\r\n\r\n mailMessage.setFrom(this.defaultFrom);\r\n mailMessage.setTo(to);\r\n mailMessage.setSubject(subject);\r\n mailMessage.setText(message);\r\n\r\n this.emailSender.send(mailMessage);\r\n }\r\n\r\n private String getTemplateName(String templateName,String language){\r\n List<String> languages = Arrays.asList(mailTemplateLanguages.split(\",\"));\r\n if(languages.contains(language)){\r\n return String.format(\"%s_%s\",templateName,language);\r\n }\r\n return String.format(\"%s_%s\",templateName,languages.get(0));\r\n }\r\n\r\n private String getMailSubject(NimbleMessageCode messageCode, String language, List<String> parameters){\r\n return this.messageSource.getMessage(messageCode.toString(), parameters.toArray(), getLocale(language));\r\n }\r\n\r\n /**\r\n * Returns the {{@link Locale}} for the given language\r\n * */\r\n private Locale getLocale(String language){\r\n List<String> languages = Arrays.asList(mailTemplateLanguages.split(\",\"));\r\n String mailSubjectLanguage = languages.contains(language) ? language :languages.get(0) ;\r\n return new Locale(mailSubjectLanguage);\r\n }\r\n\r\n /**\r\n * Returns the mail content for company details updates\r\n * @param companyDetailsUpdates the updated fields of company details\r\n * @param language the language id to be used to put proper translations of company fields\r\n * @return the mail content for company details updates as string\r\n * */\r\n private String getMailContentForCompanyDetailsUpdates(CompanyDetailsUpdates companyDetailsUpdates,String language){\r\n Locale locale = getLocale(language);\r\n\r\n StringBuilder content = new StringBuilder();\r\n // company name\r\n if(companyDetailsUpdates.getLegalName() != null){\r\n content.append(this.messageSource.getMessage(NimbleMessageCode.COMPANY_NAME.toString(),null,locale)).append(\":\\n\");\r\n content.append(stringifyLanguageMap(companyDetailsUpdates.getLegalName())).append(\"\\n\");\r\n }\r\n // brand name\r\n if(companyDetailsUpdates.getBrandName() != null){\r\n content.append(this.messageSource.getMessage(NimbleMessageCode.BRAND_NAME.toString(),null,locale)).append(\":\\n\");\r\n content.append(stringifyLanguageMap(companyDetailsUpdates.getBrandName())).append(\"\\n\");\r\n }\r\n // vat number\r\n if(companyDetailsUpdates.getVatNumber() != null){\r\n content.append(this.messageSource.getMessage(NimbleMessageCode.VAT_NUMBER.toString(),null,locale)).append(\":\\n\");\r\n content.append(companyDetailsUpdates.getVatNumber()).append(\"\\n\\n\");\r\n }\r\n // verification info\r\n if(companyDetailsUpdates.getVerificationInformation() != null){\r\n content.append(this.messageSource.getMessage(NimbleMessageCode.VERIFICATION_INFO.toString(),null,locale)).append(\":\\n\");\r\n content.append(companyDetailsUpdates.getVerificationInformation()).append(\"\\n\\n\");\r\n }\r\n // business type\r\n if(companyDetailsUpdates.getBusinessType() != null){\r\n String businessTypeKey = companyDetailsUpdates.getBusinessType().replace(\" \",\"_\").toUpperCase();\r\n content.append(this.messageSource.getMessage(NimbleMessageCode.BUSINESS_TYPE.toString(),null,locale)).append(\":\\n\");\r\n content.append(this.messageSource.getMessage(businessTypeKey,null,locale)).append(\"\\n\\n\");\r\n }\r\n // activity sectors\r\n if(companyDetailsUpdates.getIndustrySectors() != null){\r\n content.append(this.messageSource.getMessage(NimbleMessageCode.ACTIVITY_SECTORS.toString(),null,locale)).append(\":\\n\");\r\n content.append(stringifyLanguageMap(companyDetailsUpdates.getIndustrySectors())).append(\"\\n\");\r\n }\r\n // business keywords\r\n if(companyDetailsUpdates.getBusinessKeywords() != null){\r\n content.append(this.messageSource.getMessage(NimbleMessageCode.BUSINESS_KEYWORDS.toString(),null,locale)).append(\":\\n\");\r\n content.append(stringifyLanguageMap(companyDetailsUpdates.getBusinessKeywords())).append(\"\\n\");\r\n }\r\n // year of foundation\r\n if(companyDetailsUpdates.getYearOfCompanyRegistration() != null){\r\n content.append(this.messageSource.getMessage(NimbleMessageCode.YEAR_FOUNDATION.toString(),null,locale)).append(\":\\n\");\r\n content.append(companyDetailsUpdates.getYearOfCompanyRegistration()).append(\"\\n\\n\");\r\n }\r\n // address\r\n if(companyDetailsUpdates.getAddress() != null){\r\n // street\r\n content.append(this.messageSource.getMessage(NimbleMessageCode.STREET.toString(),null,locale)).append(\":\\n\");\r\n content.append(companyDetailsUpdates.getAddress().getStreetName()).append(\"\\n\\n\");\r\n // building number\r\n content.append(this.messageSource.getMessage(NimbleMessageCode.BUILDING_NUMBER.toString(),null,locale)).append(\":\\n\");\r\n content.append(companyDetailsUpdates.getAddress().getBuildingNumber()).append(\"\\n\\n\");\r\n // city/town\r\n content.append(this.messageSource.getMessage(NimbleMessageCode.CITY_TOWN.toString(),null,locale)).append(\":\\n\");\r\n content.append(companyDetailsUpdates.getAddress().getCityName()).append(\"\\n\\n\");\r\n // state/province\r\n content.append(this.messageSource.getMessage(NimbleMessageCode.STATE_PROVINCE.toString(),null,locale)).append(\":\\n\");\r\n content.append(companyDetailsUpdates.getAddress().getRegion()).append(\"\\n\\n\");\r\n // postal code\r\n content.append(this.messageSource.getMessage(NimbleMessageCode.POSTAL_CODE.toString(),null,locale)).append(\":\\n\");\r\n content.append(companyDetailsUpdates.getAddress().getPostalCode()).append(\"\\n\\n\");\r\n // country\r\n content.append(this.messageSource.getMessage(NimbleMessageCode.COUNTRY.toString(),null,locale)).append(\":\\n\");\r\n content.append(companyDetailsUpdates.getAddress().getCountry()).append(\"\\n\");\r\n }\r\n return content.toString();\r\n }\r\n\r\n /**\r\n * Stringifies the given language map\r\n * @param languageMap the language id - value map\r\n * @return language id - value pairs separeted by new line\r\n * */\r\n private String stringifyLanguageMap(Map<NimbleConfigurationProperties.LanguageID, String> languageMap){\r\n String newLineChar = \"\\n\";\r\n StringBuilder stringBuilder = new StringBuilder();\r\n languageMap.forEach((languageID, value) -> {\r\n List<String> values = Arrays.asList(value.split(newLineChar).clone());\r\n values.forEach(v -> stringBuilder.append(v).append(\"(\").append(languageID).append(\")\\n\"));\r\n });\r\n return stringBuilder.toString();\r\n }\r\n}\r",
"@Service\npublic class IdentityService {\n\n private static final Logger logger = LoggerFactory.getLogger(IdentityService.class);\n\n @Autowired\n private UaaUserRepository uaaUserRepository;\n\n @Autowired\n private PartyRepository partyRepository;\n\n @Autowired\n private KeycloakAdmin keycloakAdmin;\n\n public UaaUser getUserfromBearer(String bearer) throws IOException {\n OpenIdConnectUserDetails userDetails = getUserDetails(bearer);\n return uaaUserRepository.findByExternalID(userDetails.getUserId());\n }\n\n public OpenIdConnectUserDetails getUserDetails(String bearer) throws IOException {\n return OpenIdConnectUserDetails.fromBearer(bearer);\n }\n\n /**\n * Checks if the bearer contains at least one of the given roles.\n *\n * @param bearer Token containing roles\n * @param roles Roles to check\n * @return True if at least one matching role was found.\n * @throws IOException if roles could not be extracted from token\n */\n public boolean hasAnyRole(String bearer, OAuthClient.Role... roles) throws IOException {\n OpenIdConnectUserDetails details = getUserDetails(bearer);\n return Arrays.stream(roles).anyMatch(r -> details.hasRole(r.toString()));\n }\n\n public Optional<PartyType> getCompanyOfUser(UaaUser uaaUser) {\n if (uaaUser == null)\n return Optional.empty();\n return partyRepository.findByPerson(uaaUser.getUBLPerson()).stream().findFirst();\n }\n\n @SuppressWarnings(\"SimplifiableIfStatement\")\n public boolean inSameCompany(UaaUser userOne, UaaUser userTwo) {\n\n if (userOne == null || userTwo == null)\n return false;\n\n Optional<PartyType> requestingCompany = getCompanyOfUser(userOne);\n Optional<PartyType> targetCompany = getCompanyOfUser(userTwo);\n if ((requestingCompany.isPresent() && targetCompany.isPresent()) == false) // check if companies exist\n return false;\n\n return requestingCompany.get().getHjid().equals(targetCompany.get().getHjid());\n }\n\n public Set<String> fetchRoles(PersonType personType) {\n try {\n UaaUser uaaUser = uaaUserRepository.findByUblPerson(personType).stream().findFirst().orElseThrow(NotFoundException::new);\n return fetchRoles(uaaUser);\n } catch (Exception exception) {\n logger.error(\"Error while fetching roles for person\", exception);\n }\n return Collections.emptySet();\n }\n\n public Set<String> fetchRoles(UaaUser user) {\n\n Set<String> roles = new HashSet<>();\n try {\n // collect roles\n logger.debug(\"Fetching roles of user {}\", user.getUsername());\n roles = keycloakAdmin.getUserRoles(user.getExternalID(), KeycloakAdmin.NON_NIMBLE_ROLES);\n } catch (Exception ex) {\n logger.error(\"Error while fetch roles of user\", ex);\n }\n\n return roles;\n }\n\n public void enrichWithRoles(PersonType person) {\n Set<String> roles = fetchRoles(person);\n person.getRole().clear();\n person.getRole().addAll(roles);\n }\n\n public void enrichWithRoles(PartyType party) {\n party.getPerson().forEach(this::enrichWithRoles);\n }\n\n public static Double computeDetailsCompleteness(CompanyDetails companyDetails) {\n\n List<Double> completenessWeights = new ArrayList<>();\n completenessWeights.add(companyDetails.getLegalName().isEmpty() == false ? 1.0 : 0.0);\n completenessWeights.add(StringUtils.isNotEmpty(companyDetails.getVatNumber()) ? 1.0 : 0.0);\n completenessWeights.add(StringUtils.isNotEmpty(companyDetails.getBusinessType()) ? 1.0 : 0.0);\n completenessWeights.add(companyDetails.getIndustrySectors() != null && companyDetails.getIndustrySectors().size() > 0 ? 1.0 : 0.0);\n\n Address address = companyDetails.getAddress();\n if (address != null) {\n completenessWeights.add(StringUtils.isNotEmpty(address.getStreetName()) ? 1.0 : 0.0);\n completenessWeights.add(StringUtils.isNotEmpty(address.getCityName()) ? 1.0 : 0.0);\n completenessWeights.add(StringUtils.isNotEmpty(address.getPostalCode()) ? 1.0 : 0.0);\n completenessWeights.add(StringUtils.isNotEmpty(address.getCountry()) ? 1.0 : 0.0);\n }\n return completenessWeights.stream().mapToDouble(d -> d).average().orElse(0.0);\n }\n\n public static Double computeDescriptionCompleteness(CompanyDescription companyDescription) {\n List<Double> completenessWeights = new ArrayList<>();\n completenessWeights.add(!companyDescription.getCompanyStatement().isEmpty() ? 1.0 : 0.0);\n completenessWeights.add(StringUtils.isNotEmpty(companyDescription.getWebsite()) ? 1.0 : 0.0);\n completenessWeights.add(companyDescription.getLogoImageId() != null ? 1.0 : 0.0);\n completenessWeights.add(companyDescription.getSocialMediaList() != null && companyDescription.getSocialMediaList().size() > 0 ? 1.0 : 0.0);\n return completenessWeights.stream().mapToDouble(d -> d).average().orElse(0.0);\n }\n\n public static Double computeDeliveryAddressCompleteness(PartyType party) {\n List<Double> completenessWeights = new ArrayList<>();\n TradingPreferences tradingPreferences = party.getPurchaseTerms();\n if (tradingPreferences.getDeliveryTerms().size() == 0 || null == tradingPreferences.getDeliveryTerms().get(0).getDeliveryLocation()) {\n return 0.0;\n } else {\n LocationType locationType = tradingPreferences.getDeliveryTerms().get(0).getDeliveryLocation();\n completenessWeights.add(locationType.getAddress().getStreetName() != null ? 1.0 : 0.0);\n completenessWeights.add(locationType.getAddress().getBuildingNumber() != null ? 1.0 : 0.0);\n completenessWeights.add(locationType.getAddress().getCityName() != null ? 1.0 : 0.0);\n completenessWeights.add(locationType.getAddress().getRegion() != null ? 1.0 : 0.0);\n completenessWeights.add(locationType.getAddress().getPostalZone() != null ? 1.0 : 0.0);\n completenessWeights.add(locationType.getAddress().getCountry() != null ? 1.0 : 0.0);\n return completenessWeights.stream().mapToDouble(d -> d).average().orElse(0.0);\n }\n }\n\n public static Double computeCertificateCompleteness(PartyType party) {\n List<Double> completenessWeights = new ArrayList<>();\n completenessWeights.add(party.getCertificate() != null && party.getCertificate().size() > 0 ? 1.0 : 0.0);\n return completenessWeights.stream().mapToDouble(d -> d).average().orElse(0.0);\n }\n\n public static Double computeTradeCompleteness(NegotiationSettings negotiationSettings) {\n List<Double> completenessWeights = new ArrayList<>();\n try {\n completenessWeights.add(negotiationSettings.getPaymentMeans() != null && negotiationSettings.getPaymentMeans().size() > 0 ? 1.0 : 0.0);\n completenessWeights.add(negotiationSettings.getPaymentTerms() != null && negotiationSettings.getPaymentTerms().size() > 0 ? 1.0 : 0.0);\n completenessWeights.add(negotiationSettings.getIncoterms() != null && negotiationSettings.getIncoterms().size() > 0 ? 1.0 : 0.0);\n }catch (Exception e){\n logger.error(\"Exception occurred while computing the tradCompletenessSocre\", e);\n }\n return completenessWeights.stream().mapToDouble(d -> d).average().orElse(0.0);\n }\n\n public static Double computeAdditionalDataCompleteness(PartyType party, CompanyTradeDetails tradeDetails, CompanyDescription companyDescription) {\n List<Double> completenessWeights = new ArrayList<>();\n completenessWeights.add(companyDescription.getEvents() != null && companyDescription.getEvents().size() > 0 ? 1.0 : 0.0);\n completenessWeights.add(companyDescription.getCompanyPhotoList() != null && companyDescription.getCompanyPhotoList().size() > 0 ? 1.0 : 0.0);\n completenessWeights.add(companyDescription.getExternalResources() != null && companyDescription.getExternalResources().size() > 0 ? 1.0 : 0.0);\n return completenessWeights.stream().mapToDouble(d -> d).average().orElse(0.0);\n }\n}",
"@Entity\npublic class UaaUser implements Serializable {\n\n @Id\n @Column(nullable = false, unique = true)\n private String externalID;\n\n private String username;\n\n @OneToOne\n private PersonType ublPerson;\n\n @ColumnDefault(\"false\")\n private Boolean showWelcomeInfo = false;\n\n public UaaUser() {\n }\n\n public UaaUser(String username, PersonType ublPerson, String externalID) {\n this.username = username;\n this.ublPerson = ublPerson;\n this.externalID = externalID;\n this.showWelcomeInfo = true;\n }\n\n public String getUsername() {\n return username;\n }\n\n public String getExternalID() {\n return externalID;\n }\n\n public PersonType getUBLPerson() {\n return this.ublPerson;\n }\n\n public Boolean getShowWelcomeInfo() {\n return showWelcomeInfo;\n }\n\n public void setShowWelcomeInfo(Boolean showWelcomeInfo) {\n this.showWelcomeInfo = showWelcomeInfo;\n }\n}",
"@SuppressWarnings(\"Convert2MethodRef\")\n@Service\npublic class KeycloakAdmin {\n\n private static final Logger logger = LoggerFactory.getLogger(KeycloakAdmin.class);\n\n public static final String NIMBLE_USER_ROLE = \"nimble_user\";\n public static final String INITIAL_REPRESENTATIVE_ROLE = \"initial_representative\";\n public static final String LEGAL_REPRESENTATIVE_ROLE = \"legal_representative\";\n public static final String PLATFORM_MANAGER_ROLE = \"platform_manager\";\n public static final String NIMBLE_DELETED_USER = \"nimble_deleted_user\";\n\n public static final String PLATFORM_MANAGER_GROUP = \"Platform Manager\";\n\n public static final List<String> NON_ASSIGNABLE_ROLES = Arrays.asList(\"platform_manager\", \"uma_authorization\",\n \"offline_access\", \"admin\", \"create-realm\",\n \"create-realm\", \"nimble_user\", \"initial_representative\");\n\n public static final List<String> NON_NIMBLE_ROLES = Arrays.asList(\"uma_authorization\", \"offline_access\", \"admin\", \"create-realm\", \"create-realm\");\n\n @Value(\"${nimble.oauth.identityProvider.eFactory}\")\n private String eFactoryIdentityProvider;\n\n @Autowired\n private KeycloakConfig keycloakConfig;\n\n @Autowired\n private OAuthClient oAuthClient;\n\n @Autowired\n private OAuthClientConfig oAuthClientConfig;\n\n private Keycloak keycloak;\n\n private static long oneHourInMilliSeconds = 3600000;\n\n @PostConstruct\n @SuppressWarnings(\"unused\")\n public void init() {\n ResteasyClient client = new ResteasyClientBuilder().connectionPoolSize(10).build();\n this.keycloak = KeycloakBuilder.builder()\n .serverUrl(keycloakConfig.getServerUrl())\n .realm(keycloakConfig.getRealm())\n .grantType(OAuth2Constants.PASSWORD)\n .username(keycloakConfig.getAdmin().getUsername())\n .password(keycloakConfig.getAdmin().getPassword())\n .clientId(keycloakConfig.getAdmin().getCliendId())\n .clientSecret(keycloakConfig.getAdmin().getCliendSecret())\n .resteasyClient(client)\n .build();\n }\n\n public String initiatePasswordRecoveryProcess(String email) {\n RealmResource realmResource = this.keycloak.realm(keycloakConfig.getRealm());\n UsersResource userResource = realmResource.users();\n\n List<UserRepresentation> userList = userResource.search(email);\n if (userList.size() != 0) {\n UserRepresentation user = userList.get(0);\n return JWT.create()\n .withJWTId(user.getId())\n .withClaim(GlobalConstants.JWT_TYPE_ATTRIBUTE_STRING, \"reset-credentials\")\n .withSubject(user.getId())\n .withExpiresAt(new Date(System.currentTimeMillis() + oneHourInMilliSeconds))\n .sign(HMAC512(keycloakConfig.getAdmin().getCliendSecret().getBytes()));\n }else {\n throw new ResourceNotFoundException(\"Resource not found for the user name\");\n }\n }\n\n public void resetPasswordViaRecoveryProcess(String token, String newPassword) {\n\n try {\n JWTVerifier verifier = JWT.require(HMAC512(keycloakConfig.getAdmin().getCliendSecret().getBytes())).build();\n verifier.verify(token);\n } catch (SignatureVerificationException e) {\n logger.warn(\"Invalid token received for password reset\");\n throw new BadRequestException(\"Invalid Token\");\n }\n\n long exp = JWT.decode(token).getClaim(GlobalConstants.JWT_EXPIRY_ATTRIBUTE_STRING).asLong();\n if (System.currentTimeMillis() > exp) {\n String sub = JWT.decode(token).getClaim(GlobalConstants.JWT_SUBJECT_ATTRIBUTE_STRING).asString();\n RealmResource realmResource = this.keycloak.realm(keycloakConfig.getRealm());\n UserResource use = realmResource.users().get(sub);\n CredentialRepresentation passwordCredential = createPasswordCredentials(newPassword);\n passwordCredential.setTemporary(false);\n this.keycloak.realm(keycloakConfig.getRealm()).users().get(sub).resetPassword(passwordCredential);\n }else {\n throw new NotAuthorizedException(\"URL expired\");\n }\n }\n\n /**\n * Verify the jwt token provided by the Keycloak\n * TODO: Implement verification by using the certs\n * https://stackoverflow.com/questions/39890232/how-to-decode-keys-from-keycloak-openid-connect-cert-api\n * @param jwtToken\n * @return\n */\n public boolean verify(String jwtToken) throws ServerException {\n\n String uri = keycloakConfig.getServerUrl() + \"/realms/master\";\n\n HttpHeaders headers = new HttpHeaders();\n headers.setContentType(MediaType.APPLICATION_JSON);\n HttpEntity<String> entity = new HttpEntity<String>(headers);\n RestTemplate rs = new RestTemplate();\n\n try {\n ResponseEntity<String> response = rs.exchange(uri, HttpMethod.GET, entity, String.class);\n ObjectMapper mapper = new ObjectMapper();\n mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);\n\n RealmConfigs realmConfigs = mapper.readValue(response.getBody(), RealmConfigs.class);\n JwtHelper.decodeAndVerify(jwtToken, new RsaVerifier(getRSAPublicKey(realmConfigs.getPublic_key())));\n } catch (IOException e) {\n logger.error(\"Error in extracting the data from Keycloak realm response{}\", e);\n throw new ServerException(\"Keycloak server error\", e);\n } catch (Exception e) {\n logger.error(\"Error in verifying token{}\", e);\n return false;\n }\n return true;\n }\n\n\n /**\n * Generates the RSA Public key from Keycloak public key\n * @param publicKey\n * @return\n * @throws Exception\n */\n private RSAPublicKey getRSAPublicKey(String publicKey) throws Exception {\n if( StringUtils.isBlank(publicKey)) return null;\n try {\n KeyFactory keyFactory = java.security.KeyFactory.getInstance(\"RSA\");\n X509EncodedKeySpec keySpec = new X509EncodedKeySpec(java.util.Base64.getDecoder().decode(publicKey));\n return (RSAPublicKey) keyFactory.generatePublic(keySpec);\n } catch (InvalidKeySpecException | NoSuchAlgorithmException e) {\n logger.error(\"Error forming RSA key {}\", e);\n throw new Exception(e);\n }\n }\n\n /**\n * throws javax.ws.rs.WebApplicationException with corrensponding response for error\n **/\n public String registerUser(String firstName, String lastName, String password, String email) {\n\n RealmResource realmResource = this.keycloak.realm(keycloakConfig.getRealm());\n UsersResource userResource = realmResource.users();\n\n // create proper credentials\n CredentialRepresentation passwordCredentials = createPasswordCredentials(password);\n\n // create user\n UserRepresentation user = new UserRepresentation();\n user.setUsername(email);\n user.setCredentials(Collections.singletonList(passwordCredentials));\n user.setFirstName(firstName);\n user.setLastName(lastName);\n user.setEmail(email);\n user.setRequiredActions(Collections.emptyList());\n user.setEnabled(true);\n user.setEmailVerified(false);\n\n // extract identifier of user\n Response response = userResource.create(user);\n String userId = extractCreatedId(response);\n UserResource createdUser = fetchUserResource(userId);\n\n // ToDo: throw exception if user already exists\n\n // set password\n createdUser.resetPassword(passwordCredentials);\n\n// // send verification mail\n// createdUser.executeActionsEmail(oAuthClientConfig.getCliendId(), \"http://localhost:102\", Collections.singletonList(\"VERIFY_EMAIL\"));\n// createdUser.sendVerifyEmail(oAuthClientConfig.getCliendId());\n\n addRole(userId, NIMBLE_USER_ROLE);\n\n return createdUser.toRepresentation().getId();\n }\n\n public void deleteUser(String externalId) {\n RealmResource realmResource = this.keycloak.realm(keycloakConfig.getRealm());\n UsersResource userResource = realmResource.users();\n\n // delete user\n userResource.delete(externalId);\n }\n\n public void deleteUserByUsername(String username) {\n RealmResource realmResource = this.keycloak.realm(keycloakConfig.getRealm());\n UsersResource userResource = realmResource.users();\n\n List<UserRepresentation> userRepresentations = userResource.search(username);\n userRepresentations.forEach(userRepresentation -> userResource.delete(userRepresentation.getId()));\n }\n\n public Map<String, String> getAssignableRoles() {\n RealmResource realmResource = this.keycloak.realm(keycloakConfig.getRealm());\n\n return realmResource.roles().list().stream()\n .filter(r -> NON_ASSIGNABLE_ROLES.contains(r.getName()) == false)\n .collect(Collectors.toMap(r -> r.getId(), r -> r.getName()));\n }\n\n public Set<String> getUserRoles(String userId) {\n return getUserRoles(userId, new ArrayList<>());\n }\n\n public Set<String> getUserRoles(String userId, List<String> excludeRoles) {\n\n List<String> finalExcludeRoles = (excludeRoles == null) ? new ArrayList<>() : excludeRoles;\n UserResource userResource = fetchUserResource(userId);\n return userResource.roles().realmLevel().listAll().stream()\n .map(r -> r.getName())\n .filter(role -> finalExcludeRoles.contains(role) == false)\n .collect(Collectors.toSet());\n }\n\n public UserResource getUserResource(String userId) {\n return fetchUserResource(userId);\n }\n\n public String getEFactoryUserId(UserResource userResource){\n for (FederatedIdentityRepresentation federatedIdentityRepresentation : userResource.getFederatedIdentity()) {\n if(federatedIdentityRepresentation.getIdentityProvider().contentEquals(eFactoryIdentityProvider)){\n return federatedIdentityRepresentation.getUserId();\n }\n }\n return null;\n }\n public void addRole(String userId, String role) {\n UserResource userResource = fetchUserResource(userId);\n\n RealmResource realmResource = this.keycloak.realm(keycloakConfig.getRealm());\n RoleRepresentation roleRepresentation = realmResource.roles().get(role).toRepresentation();\n userResource.roles().realmLevel().add(Collections.singletonList(roleRepresentation));\n }\n\n public void removeRole(String userId, String role) {\n UserResource userResource = fetchUserResource(userId);\n\n RealmResource realmResource = this.keycloak.realm(keycloakConfig.getRealm());\n RoleRepresentation roleRepresentation = realmResource.roles().get(role).toRepresentation();\n userResource.roles().realmLevel().remove(Collections.singletonList(roleRepresentation));\n }\n\n public List<UserRepresentation> getPlatformManagers() {\n\n RealmResource realmResource = this.keycloak.realm(keycloakConfig.getRealm());\n List<GroupRepresentation> groups = realmResource.groups().groups();\n\n Optional<GroupRepresentation> platformManagerGroup = groups.stream().filter(g -> \"Platform Manager\".equals(g.getName())).findFirst();\n if (platformManagerGroup.isPresent() == false) {\n logger.warn(\"No platform managers found!\");\n return new ArrayList<>(); // empty list as fallback\n }\n return realmResource.groups().group(platformManagerGroup.get().getId()).members();\n }\n\n private UserResource fetchUserResource(String userId) {\n RealmResource realmResource = this.keycloak.realm(keycloakConfig.getRealm());\n return realmResource.users().get(userId);\n }\n\n public boolean resetPassword(UaaUser user, String oldPassword, String newPassword) {\n\n try {\n // verify existing password\n OAuth2AccessToken accessToken = oAuthClient.getToken(user.getUsername(), oldPassword);\n if (accessToken == null)\n return false;\n\n // set new password\n CredentialRepresentation passwordCredential = createPasswordCredentials(newPassword);\n this.keycloak.realm(keycloakConfig.getRealm()).users().get(user.getExternalID()).resetPassword(passwordCredential);\n } catch (OAuth2AccessDeniedException ex) {\n logger.info(\"Authentication error while setting new password\");\n return false;\n }\n\n return true;\n }\n\n private String extractCreatedId(Response response) {\n URI location = response.getLocation();\n if (!response.getStatusInfo().equals(Response.Status.CREATED)) {\n Response.StatusType statusInfo = response.getStatusInfo();\n throw new WebApplicationException(\"Create method returned status \" +\n statusInfo.getReasonPhrase() + \" (Code: \" + statusInfo.getStatusCode() + \"); expected status: Created (201)\",\n statusInfo.getStatusCode());\n }\n if (location == null) {\n return null;\n }\n String path = location.getPath();\n return path.substring(path.lastIndexOf('/') + 1);\n }\n\n public int applyRoles(String userID, Set<String> rolesToApply) {\n // setting proper set of roles\n Set<String> currentRoles = getUserRoles(userID, NON_ASSIGNABLE_ROLES);\n Set<String> rolesToRemove = Sets.difference(currentRoles, rolesToApply);\n Set<String> rolesToAdd = Sets.difference(rolesToApply, currentRoles);\n logger.info(\"Applying new roles to user {}: add: {}, remove: {}\", userID, rolesToAdd, rolesToRemove);\n for (String role : rolesToRemove)\n removeRole(userID, role);\n for (String role : rolesToAdd)\n addRole(userID, role);\n return rolesToAdd.size() + rolesToRemove.size();\n }\n\n public static List<String> prettfiyRoleIDs(List<String> roleIDs) {\n return roleIDs.stream().map(r -> WordUtils.capitalize(r.replace(\"_\", \" \"))).collect(Collectors.toList());\n }\n\n private static CredentialRepresentation createPasswordCredentials(String password) {\n CredentialRepresentation passwordCredentials = new CredentialRepresentation();\n passwordCredentials.setTemporary(false);\n passwordCredentials.setType(CredentialRepresentation.PASSWORD);\n passwordCredentials.setValue(password);\n return passwordCredentials;\n }\n}",
"@Service\npublic class OAuthClient {\n\n @Autowired\n private OAuthClientConfig config;\n\n @Autowired\n private OAuth2ClientContext oauth2Context;\n\n @Bean\n public TokenStore tokenStore() {\n return new InMemoryTokenStore();\n }\n\n public OAuth2AccessToken getToken(String username, String password) {\n\n // build resources\n ResourceOwnerPasswordResourceDetails resourceDetails = new ResourceOwnerPasswordResourceDetails();\n resourceDetails.setClientId(config.getCliendId());\n resourceDetails.setClientSecret(config.getCliendSecret());\n resourceDetails.setAccessTokenUri(config.getAccessTokenUri());\n resourceDetails.setUsername(username);\n resourceDetails.setPassword(password);\n\n // build provider\n ResourceOwnerPasswordAccessTokenProvider accessTokenProvider = new ResourceOwnerPasswordAccessTokenProvider();\n AccessTokenRequest accessTokenRequest = oauth2Context.getAccessTokenRequest();\n\n // fetch token\n OAuth2AccessToken accessToken = accessTokenProvider.obtainAccessToken(resourceDetails, accessTokenRequest);\n return accessToken;\n }\n\n public OAuth2AccessToken refreshToken(String refreshToken) {\n\n // build resources\n ResourceOwnerPasswordResourceDetails resourceDetails = new ResourceOwnerPasswordResourceDetails();\n resourceDetails.setClientId(config.getCliendId());\n resourceDetails.setClientSecret(config.getCliendSecret());\n resourceDetails.setAccessTokenUri(config.getAccessTokenUri());\n\n // build provider\n AccessTokenRequest accessTokenRequest = oauth2Context.getAccessTokenRequest();\n ResourceOwnerPasswordAccessTokenProvider accessTokenProvider = new ResourceOwnerPasswordAccessTokenProvider();\n\n // perform refresh\n OAuth2AccessToken newAccessToken = accessTokenProvider.refreshAccessToken(resourceDetails, () -> refreshToken, accessTokenRequest);\n return newAccessToken;\n }\n\n public enum Role {\n NIMBLE_USER(\"nimble_user\"),\n INITIAL_REPRESENTATIVE(\"initial_representative\"),\n LEGAL_REPRESENTATIVE(\"legal_representative\"),\n PLATFORM_MANAGER(\"platform_manager\"),\n COMPANY_ADMIN(\"company_admin\"),\n PUBLISHER(\"publisher\"),\n NIMBLE_DELETED_USER(\"nimble_deleted_user\"),\n EXTERNAL_REPRESENTATIVE(\"external_representative\"),\n MONITOR(\"monitor\"),\n EFACTORY_USER(\"eFactoryUser\");\n\n private final String role;\n\n Role(final String role) {\n this.role = role;\n }\n\n @Override\n public String toString() {\n return role;\n }\n }\n}",
"public static final String REFRESH_TOKEN_SESSION_KEY = \"refresh_token\";"
] | import eu.nimble.core.infrastructure.identity.mail.EmailService;
import eu.nimble.core.infrastructure.identity.service.IdentityService;
import eu.nimble.core.infrastructure.identity.entity.UaaUser;
import eu.nimble.core.infrastructure.identity.uaa.KeycloakAdmin;
import eu.nimble.core.infrastructure.identity.uaa.OAuthClient;
import eu.nimble.service.model.ubl.commonaggregatecomponents.PartyType;
import eu.nimble.utility.persistence.initalizer.CustomDbInitializer;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Profile;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Optional;
import java.util.Random;
import static eu.nimble.core.infrastructure.identity.system.IdentityController.REFRESH_TOKEN_SESSION_KEY;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.when; | package eu.nimble.core.infrastructure.identity.config;
/**
* Created by Johannes Innerbichler on 09.08.18.
*/
@Profile("test")
@TestConfiguration
public class DefaultTestConfiguration {
@Bean
@Primary
public IdentityService identityResolver() throws IOException {
IdentityService identityServiceMock = Mockito.mock(IdentityService.class);
// mock user query
when(identityServiceMock.getUserfromBearer(anyString())).thenReturn(new UaaUser());
// mock company query
when(identityServiceMock.getCompanyOfUser(anyObject())).then((Answer<Optional<PartyType>>) invocationOnMock -> {
PartyType mockParty = new PartyType();
return Optional.of(mockParty);
});
// mock verification of roles
when(identityServiceMock.hasAnyRole(any(), anyVararg())).thenReturn(true);
return identityServiceMock;
}
@Bean
@Primary
public KeycloakAdmin keycloakAdmin() {
return Mockito.mock(KeycloakAdmin.class);
}
@Bean
@Primary
public EmailService emailService() {
return Mockito.mock(EmailService.class);
}
@Bean
@Primary | public OAuthClient oAuthClient() { | 4 |
noctarius/castmapr | src/main/java/com/noctarius/castmapr/core/operation/IListMapReduceOperation.java | [
"public class CollectorImpl<Key, Value>\n implements Collector<Key, Value>\n{\n\n public final Map<Key, List<Value>> emitted = new HashMap<Key, List<Value>>();\n\n @Override\n public void emit( Key key, Value value )\n {\n List<Value> values = emitted.get( key );\n if ( values == null )\n {\n values = new LinkedList<Value>();\n emitted.put( key, values );\n }\n values.add( value );\n }\n}",
"public interface IListAware<Value>\n{\n\n /**\n * This method is called after deserializing but before executing {@link Mapper#map(Object, Object, Collector)} or\n * {@link Reducer#reduce(Object, java.util.Iterator)}.\n * \n * @param list The list the implementing instance is executed against.\n */\n void setMultiMap( IList<Value> list );\n\n}",
"public abstract class Mapper<KeyIn, ValueIn, KeyOut, ValueOut>\n implements Serializable\n{\n\n /**\n * This method is called before the {@link #map(Object, Object, Collector)} method is executed for every value and\n * can be used to initialize the internal state of the mapper or to emit a special value.\n * \n * @param collector The {@link Collector} to be used for emitting values.\n */\n public void initialize( Collector<KeyOut, ValueOut> collector )\n {\n }\n\n /**\n * The map method is called for every single key-value pair in the bound {@link IMap} instance on this cluster node\n * and partition.<br>\n * Due to it's nature of a DataGrid Hazelcast distributes values all over the cluster and so this method is executed\n * on multiple servers at the same time.<br>\n * If you want to know more about the implementation of MapReduce algorithms read the {@see <a\n * href=\"http://research.google.com/archive/mapreduce-osdi04.pdf\">Google Whitepaper on MapReduce</a>}.\n * \n * @param key\n * @param value\n * @param collector\n */\n public abstract void map( KeyIn key, ValueIn value, Collector<KeyOut, ValueOut> collector );\n\n /**\n * This method is called after the {@link #map(Object, Object, Collector)} method is executed for every value and\n * can be used to finalize the internal state of the mapper or to emit a special value.\n * \n * @param collector The {@link Collector} to be used for emitting values.\n */\n public void finalized( Collector<KeyOut, ValueOut> collector )\n {\n }\n\n}",
"public interface PartitionIdAware\n{\n\n /**\n * This method is called after deserializing but before executing {@link Mapper#map(Object, Object, Collector)} or\n * {@link Reducer#reduce(Object, java.util.Iterator)}.\n * \n * @param partitionId The current partitionId\n */\n void setPartitionId( int partitionId );\n\n}",
"public interface Reducer<Key, Value>\n extends Serializable\n{\n\n /**\n * The reduce method is called either locally after of intermediate results are retrieved from mapping algorithms or\n * (if the Reducer implementation is distributable - see {@link Distributable} or {@link DistributableReducer}) on\n * the different cluster nodes.<br>\n * <b>Caution: For distributable {@link Reducer}s you need to pay attention that the reducer is executed multiple\n * times and only with intermediate results of one cluster node! This is totally ok for example for sum-algorithms\n * but can be a problem for other kinds!</b><br>\n * {@link Reducer} implementations are never distributed by default - they need to explicitly be marked using the\n * {@link Distributable} annotation or by implementing the {@link DistributableReducer} interface.\n * \n * @param key The reduced key\n * @param values The values corresponding to the reduced key\n * @return The reduced value\n */\n Value reduce( Key key, Iterator<Value> values );\n\n}"
] | import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import com.hazelcast.collection.CollectionContainer;
import com.hazelcast.collection.CollectionProxyId;
import com.hazelcast.collection.CollectionProxyType;
import com.hazelcast.collection.CollectionRecord;
import com.hazelcast.collection.CollectionService;
import com.hazelcast.collection.CollectionWrapper;
import com.hazelcast.collection.list.ObjectListProxy;
import com.hazelcast.core.IList;
import com.hazelcast.nio.serialization.Data;
import com.hazelcast.spi.ProxyService;
import com.hazelcast.spi.impl.NodeEngineImpl;
import com.noctarius.castmapr.core.CollectorImpl;
import com.noctarius.castmapr.spi.IListAware;
import com.noctarius.castmapr.spi.Mapper;
import com.noctarius.castmapr.spi.PartitionIdAware;
import com.noctarius.castmapr.spi.Reducer; | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.noctarius.castmapr.core.operation;
public class IListMapReduceOperation<KeyIn, ValueIn, KeyOut, ValueOut>
extends AbstractMapReduceOperation<KeyIn, ValueIn, KeyOut, ValueOut>
{
public IListMapReduceOperation()
{
}
public IListMapReduceOperation( String name, Mapper<KeyIn, ValueIn, KeyOut, ValueOut> mapper, | Reducer<KeyOut, ValueOut> reducer ) | 4 |
christ66/cobertura | cobertura/src/main/java/net/sourceforge/cobertura/instrument/CoberturaInstrumenter.java | [
"@CoverageIgnore\npublic class ProjectData extends CoverageDataContainer {\n\tprivate static final Logger logger = Logger.getLogger(ProjectData.class\n\t\t\t.getCanonicalName());\n\tprivate static final long serialVersionUID = 6;\n\n\tprivate static ProjectData globalProjectData = null;\n\n\tprivate static Thread shutdownHook;\n\tprivate static final transient Lock globalProjectDataLock = new ReentrantLock();\n\n\t/**\n\t * This collection is used for quicker access to the list of classes.\n\t */\n\tprivate Map classes = new HashMap();\n\n\tpublic void addClassData(ClassData classData) {\n\t\tlock.lock();\n\t\ttry {\n\t\t\tString packageName = classData.getPackageName();\n\t\t\tPackageData packageData = (PackageData) children.get(packageName);\n\t\t\tif (packageData == null) {\n\t\t\t\tpackageData = new PackageData(packageName);\n\t\t\t\t// Each key is a package name, stored as an String object.\n\t\t\t\t// Each value is information about the package, stored as a PackageData object.\n\t\t\t\tthis.children.put(packageName, packageData);\n\t\t\t}\n\t\t\tpackageData.addClassData(classData);\n\t\t\tthis.classes.put(classData.getName(), classData);\n\t\t} finally {\n\t\t\tlock.unlock();\n\t\t}\n\t}\n\n\tpublic ClassData getClassData(String name) {\n\t\treturn (ClassData) this.classes.get(name);\n\t}\n\n\t/**\n\t * This is called by instrumented bytecode.\n\t */\n\tpublic ClassData getOrCreateClassData(String name) {\n\t\tlock.lock();\n\t\ttry {\n\t\t\tClassData classData = (ClassData) this.classes.get(name);\n\t\t\tif (classData == null) {\n\t\t\t\tclassData = new ClassData(name);\n\t\t\t\taddClassData(classData);\n\t\t\t}\n\t\t\treturn classData;\n\t\t} finally {\n\t\t\tlock.unlock();\n\t\t}\n\t}\n\n\tpublic Collection getClasses() {\n\t\tlock.lock();\n\t\ttry {\n\t\t\treturn this.classes.values();\n\t\t} finally {\n\t\t\tlock.unlock();\n\t\t}\n\t}\n\n\tpublic int getNumberOfClasses() {\n\t\tlock.lock();\n\t\ttry {\n\t\t\treturn this.classes.size();\n\t\t} finally {\n\t\t\tlock.unlock();\n\t\t}\n\t}\n\n\tpublic int getNumberOfSourceFiles() {\n\t\treturn getSourceFiles().size();\n\t}\n\n\tpublic SortedSet getPackages() {\n\t\tlock.lock();\n\t\ttry {\n\t\t\treturn new TreeSet(this.children.values());\n\t\t} finally {\n\t\t\tlock.unlock();\n\t\t}\n\t}\n\n\tpublic Collection getSourceFiles() {\n\t\tSortedSet sourceFileDatas = new TreeSet();\n\t\tlock.lock();\n\t\ttry {\n\t\t\tIterator iter = this.children.values().iterator();\n\t\t\twhile (iter.hasNext()) {\n\t\t\t\tPackageData packageData = (PackageData) iter.next();\n\t\t\t\tsourceFileDatas.addAll(packageData.getSourceFiles());\n\t\t\t}\n\t\t} finally {\n\t\t\tlock.unlock();\n\t\t}\n\t\treturn sourceFileDatas;\n\t}\n\n\t/**\n\t * Get all subpackages of the given package. Includes also specified package if\n\t * it exists.\n\t *\n\t * @param packageName The package name to find subpackages for.\n\t * For example, \"com.example\"\n\t *\n\t * @return A collection containing PackageData objects. Each one\n\t * has a name beginning with the given packageName. For\n\t * example: \"com.example.io\", \"com.example.io.internal\"\n\t */\n\tpublic SortedSet getSubPackages(String packageName) {\n\t\tSortedSet subPackages = new TreeSet();\n\t\tlock.lock();\n\t\ttry {\n\t\t\tIterator iter = this.children.values().iterator();\n\t\t\twhile (iter.hasNext()) {\n\t\t\t\tPackageData packageData = (PackageData) iter.next();\n\t\t\t\tif (packageData.getName().startsWith(packageName + \".\")\n\t\t\t\t\t\t|| packageData.getName().equals(packageName)\n\t\t\t\t\t\t|| (packageName.length() == 0)) {\n\t\t\t\t\tsubPackages.add(packageData);\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tlock.unlock();\n\t\t}\n\t\treturn subPackages;\n\t}\n\n\tpublic void merge(CoverageData coverageData) {\n\t\tif (coverageData == null) {\n\t\t\treturn;\n\t\t}\n\t\tProjectData projectData = (ProjectData) coverageData;\n\t\tgetBothLocks(projectData);\n\t\ttry {\n\t\t\tsuper.merge(coverageData);\n\n\t\t\tfor (Iterator iter = projectData.classes.keySet().iterator(); iter\n\t\t\t\t\t.hasNext();) {\n\t\t\t\tObject key = iter.next();\n\t\t\t\tif (!this.classes.containsKey(key)) {\n\t\t\t\t\tthis.classes.put(key, projectData.classes.get(key));\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tlock.unlock();\n\t\t\tprojectData.lock.unlock();\n\t\t}\n\t}\n\n\t/**\n\t * Get a reference to a ProjectData object in order to increase the\n\t * coverage count for a specific line.\n\t * <p/>\n\t * This method is only called by code that has been instrumented. It\n\t * is not called by any of the Cobertura code or ant tasks.\n\t */\n\tpublic static ProjectData getGlobalProjectData() {\n\t\tglobalProjectDataLock.lock();\n\t\ttry {\n\t\t\tif (globalProjectData != null)\n\t\t\t\treturn globalProjectData;\n\n\t\t\tglobalProjectData = new ProjectData();\n\t\t\tinitialize();\n\t\t\treturn globalProjectData;\n\t\t} finally {\n\t\t\tglobalProjectDataLock.unlock();\n\t\t}\n\t}\n\n\t// TODO: Is it possible to do this as a static initializer?\n\tprivate static void initialize() {\n\t\t// Hack for Tomcat - by saving project data right now we force loading\n\t\t// of classes involved in this process (like ObjectOutputStream)\n\t\t// so that it won't be necessary to load them on JVM shutdown\n\t\tif (System.getProperty(\"catalina.home\") != null) {\n\t\t\tsaveGlobalProjectData();\n\n\t\t\t// Force the class loader to load some classes that are\n\t\t\t// required by our JVM shutdown hook.\n\t\t\t// TODO: Use ClassLoader.loadClass(\"whatever\"); instead\n\t\t\tClassData.class.toString();\n\t\t\tCoverageData.class.toString();\n\t\t\tCoverageDataContainer.class.toString();\n\t\t\tFileLocker.class.toString();\n\t\t\tLineData.class.toString();\n\t\t\tPackageData.class.toString();\n\t\t\tSourceFileData.class.toString();\n\t\t}\n\n\t\t// Add a hook to save the data when the JVM exits\n\t\tshutdownHook = new Thread(new SaveTimer());\n\t\tRuntime.getRuntime().addShutdownHook(shutdownHook);\n\t\t// Possibly also save the coverage data every x seconds?\n\t\t//Timer timer = new Timer(true);\n\t\t//timer.schedule(saveTimer, 100);\n\t}\n\n\tpublic static void saveGlobalProjectData() {\n\t\tProjectData projectDataToSave = null;\n\n\t\tglobalProjectDataLock.lock();\n\t\ttry {\n\t\t\tprojectDataToSave = getGlobalProjectData();\n\n\t\t\t/*\n\t\t\t * The next statement is not necessary at the moment, because this method is only called\n\t\t\t * either at the very beginning or at the very end of a test. If the code is changed\n\t\t\t * to save more frequently, then this will become important.\n\t\t\t */\n\t\t\tglobalProjectData = new ProjectData();\n\t\t} finally {\n\t\t\tglobalProjectDataLock.unlock();\n\t\t}\n\n\t\t/*\n\t\t * Now sleep a bit in case there is a thread still holding a reference to the \"old\"\n\t\t * globalProjectData (now referenced with projectDataToSave). \n\t\t * We want it to finish its updates. I assume 1 second is plenty of time.\n\t\t */\n\t\ttry {\n\t\t\tThread.sleep(1000);\n\t\t} catch (InterruptedException e) {\n\t\t}\n\n\t\tTouchCollector.applyTouchesOnProjectData(projectDataToSave);\n\n\t\t// Get a file lock\n\t\tFile dataFile = CoverageDataFileHandler.getDefaultDataFile();\n\t\t/*\n\t\t * A note about the next synchronized block: Cobertura uses static fields to\n\t\t * hold the data. When there are multiple classloaders, each classloader\n\t\t * will keep track of the line counts for the classes that it loads. \n\t\t * \n\t\t * The static initializers for the Cobertura classes are also called for\n\t\t * each classloader. So, there is one shutdown hook for each classloader.\n\t\t * So, when the JVM exits, each shutdown hook will try to write the\n\t\t * data it has kept to the datafile. They will do this at the same\n\t\t * time. Before Java 6, this seemed to work fine, but with Java 6, there\n\t\t * seems to have been a change with how file locks are implemented. So,\n\t\t * care has to be taken to make sure only one thread locks a file at a time.\n\t\t * \n\t\t * So, we will synchronize on the string that represents the path to the\n\t\t * dataFile. Apparently, there will be only one of these in the JVM\n\t\t * even if there are multiple classloaders. I assume that is because\n\t\t * the String class is loaded by the JVM's root classloader. \n\t\t */\n\t\tsynchronized (dataFile.getPath().intern()) {\n\t\t\tFileLocker fileLocker = new FileLocker(dataFile);\n\n\t\t\ttry {\n\t\t\t\t// Read the old data, merge our current data into it, then\n\t\t\t\t// write a new ser file.\n\t\t\t\tif (fileLocker.lock()) {\n\t\t\t\t\tProjectData datafileProjectData = loadCoverageDataFromDatafile(dataFile);\n\t\t\t\t\tif (datafileProjectData == null) {\n\t\t\t\t\t\tdatafileProjectData = projectDataToSave;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tdatafileProjectData.merge(projectDataToSave);\n\t\t\t\t\t}\n\t\t\t\t\tCoverageDataFileHandler.saveCoverageData(\n\t\t\t\t\t\t\tdatafileProjectData, dataFile);\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\t// Release the file lock\n\t\t\t\tfileLocker.release();\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static void turnOffAutoSave() {\n\t\tif (shutdownHook != null) {\n\t\t\tRuntime.getRuntime().removeShutdownHook(shutdownHook);\n\t\t}\n\t}\n\n\tprivate static ProjectData loadCoverageDataFromDatafile(File dataFile) {\n\t\tProjectData projectData = null;\n\n\t\t// Read projectData from the serialized file.\n\t\tif (dataFile.isFile()) {\n\t\t\tprojectData = CoverageDataFileHandler.loadCoverageData(dataFile);\n\t\t}\n\n\t\tif (projectData == null) {\n\t\t\t// We could not read from the serialized file, so use a new object.\n\t\t\tlogger\n\t\t\t\t\t.info(\"Cobertura: Coverage data file \"\n\t\t\t\t\t\t\t+ dataFile.getAbsolutePath()\n\t\t\t\t\t\t\t+ \" either does not exist or is not readable. Creating a new data file.\");\n\t\t}\n\n\t\treturn projectData;\n\t}\n\n}",
"public class DetectDuplicatedCodeClassVisitor extends ClassVisitor {\n\n\t/**\n\t * map of (line number -> (duplicated lineId -> origin lineId))\n\t */\n\tprivate Map<Integer, Map<Integer, Integer>> duplicatedLinesCollector = new HashMap<Integer, Map<Integer, Integer>>();\n\n\t/**\n\t * Name (internal asm) of currently processed class\n\t */\n\tprivate String className;\n\n\t/**\n\t * Every LINENUMBER instruction will have generated it's lineId.\n\t * <p/>\n\t * The generated ids must be the same as those generated by\n\t * ( {@link AbstractFindTouchPointsClassInstrumenter#lineIdGenerator} )\n\t */\n\tprivate final AtomicInteger lineIdGenerator = new AtomicInteger(0);\n\n\tpublic DetectDuplicatedCodeClassVisitor(ClassVisitor cv) {\n\t\tsuper(Opcodes.ASM4, new CheckClassAdapter(cv, false));\n\t}\n\n\t@Override\n\tpublic void visit(int version, int access, String name, String signature,\n\t\t\tString superName, String[] interfaces) {\n\t\tsuper.visit(version, access, name, signature, superName, interfaces);\n\t\tthis.className = name;\n\t}\n\n\t@Override\n\tpublic MethodVisitor visitMethod(int access, String methodName,\n\t\t\tString description, String signature, String[] exceptions) {\n\t\tMethodVisitor nestedVisitor = super.visitMethod(access, methodName,\n\t\t\t\tdescription, signature, exceptions);\n\t\treturn new DetectDuplicatedCodeMethodVisitor(nestedVisitor,\n\t\t\t\tduplicatedLinesCollector, className, methodName, description,\n\t\t\t\tlineIdGenerator);\n\t}\n\n\t/**\n\t * Returns map of (line number -> (duplicated lineId -> origin lineId))\n\t */\n\tpublic Map<Integer, Map<Integer, Integer>> getDuplicatesLinesCollector() {\n\t\treturn duplicatedLinesCollector;\n\t}\n}",
"public class BuildClassMapClassVisitor\n\t\textends\n\t\t\tAbstractFindTouchPointsClassInstrumenter {\n\t/**\n\t * {@link ClassMap} for the currently analyzed class.\n\t */\n\tprivate final ClassMap classMap = new ClassMap();\n\n\t/**\n\t * Information about important 'events' (instructions) are sent into the listener that is internally\n\t * responsible for modifying the {@link #classMap} content.\n\t */\n\tprivate final BuildClassMapTouchPointListener touchPointListener = new BuildClassMapTouchPointListener(\n\t\t\tclassMap);\n\n\t/**\n\t * It's flag that signals if the class should be instrumented by cobertura.\n\t * After analyzing the class you can check the field using {@link #shouldBeInstrumented()}.\n\t */\n\tprivate boolean toInstrument = true;\n\n\tprivate final Set<String> ignoredMethods;\n\n\t/**\n\t * @param cv - a listener for code-instrumentation events\n\t * @param ignoreRegexp - list of patters of method calls that should be ignored from line-coverage-measurement\n\t * @param duplicatedLinesMap - map of found duplicates in the class. You should use {@link DetectDuplicatedCodeClassVisitor} to find the duplicated lines.\n\t */\n\tpublic BuildClassMapClassVisitor(ClassVisitor cv,\n\t\t\tCollection<Pattern> ignoreRegexes,\n\t\t\tMap<Integer, Map<Integer, Integer>> duplicatedLinesMap,\n\t\t\tSet<String> ignoredMethods) {\n\t\tsuper(cv, ignoreRegexes, duplicatedLinesMap);\n\t\tthis.ignoredMethods = ignoredMethods;\n\t}\n\n\t@Override\n\tpublic AnnotationVisitor visitAnnotation(String name, boolean arg1) {\n\t\tif (Type.getDescriptor(CoverageIgnore.class).equals(name)) {\n\t\t\ttoInstrument = false;\n\t\t}\n\t\treturn super.visitAnnotation(name, arg1);\n\t}\n\n\t/**\n\t * Stores in {@link #classMap} information of className and if the class should be instrumented ({@link #shouldBeInstrumented()})\n\t */\n\t@Override\n\tpublic void visit(int version, int access, String name, String signature,\n\t\t\tString parent, String[] interfaces) {\n\t\tclassMap.setClassName(name);\n\n\t\tif ((access & Opcodes.ACC_INTERFACE) != 0) {\n\t\t\ttoInstrument = false;\n\t\t}\n\t\tsuper.visit(version, access, name, signature, parent, interfaces);\n\t}\n\n\t/**\n\t * Stores in {@link #classMap} information of source filename\n\t */\n\t@Override\n\tpublic void visitSource(String file, String debug) {\n\t\tclassMap.setSource(file);\n\t\tsuper.visitSource(file, debug);\n\t}\n\n\t/**\n\t * Analyzes given method and stores information about all found important places into {@link #classMap}\n\t */\n\t@Override\n\tpublic MethodVisitor visitMethod(int access, String name, String desc,\n\t\t\tString signature, String[] exceptions) {\n\t\tif (((access & Opcodes.ACC_STATIC) != 0)\n\t\t\t\t&& CodeProvider.COBERTURA_INIT_METHOD_NAME.equals(name)) {\n\t\t\ttoInstrument = false; // The class has bean already instrumented.\n\t\t}\n\n\t\tMethodVisitor mv = super.visitMethod(access, name, desc, signature,\n\t\t\t\texceptions);\n\t\tif (ignoredMethods.contains(name + desc)) {\n\t\t\treturn mv;\n\t\t}\n\t\tFindTouchPointsMethodAdapter instrumenter = new FindTouchPointsMethodAdapter(\n\t\t\t\tnew HistoryMethodAdapter(mv, 4), classMap.getClassName(), name,\n\t\t\t\tdesc, eventIdGenerator, duplicatedLinesMap, lineIdGenerator);\n\t\tinstrumenter.setTouchPointListener(touchPointListener);\n\t\tinstrumenter.setIgnoreRegexp(getIgnoreRegexp());\n\t\treturn instrumenter;\n\t}\n\n\t/**\n\t * Returns classMap build for the analyzed map. The classmap is filled after running the analyzer ({@link ClassReader#accept(ClassVisitor, int)}).\n\t *\n\t * @return the classmap.\n\t */\n\tpublic ClassMap getClassMap() {\n\t\treturn classMap;\n\t}\n\n\t/**\n\t * It's flag that signals if the class should be instrumented by Cobertura.\n\t */\n\tpublic boolean shouldBeInstrumented() {\n\t\treturn toInstrument;\n\t}\n}",
"public class InjectCodeClassInstrumenter\n\t\textends\n\t\t\tAbstractFindTouchPointsClassInstrumenter {\n\t/**\n\t * This class is responsible for injecting code inside 'interesting places' of methods inside instrumented class\n\t */\n\tprivate final InjectCodeTouchPointListener touchPointListener;\n\n\t/**\n\t * {@link ClassMap} generated in previous instrumentation pass by {@link BuildClassMapClassVisitor}\n\t */\n\tprivate final ClassMap classMap;\n\n\t/**\n\t * {@link CodeProvider} used to generate pieces of asm code that is injected into instrumented class.\n\t * <p/>\n\t * We are strictly recommending here using {@link FastArrayCodeProvider} instead of {@link AtomicArrayCodeProvider} because\n\t * of performance.\n\t */\n\tprivate final CodeProvider codeProvider;\n\n\t/**\n\t * When we processing the class we want to now if we processed 'static initialization block' (clinit method).\n\t * <p/>\n\t * <p>If there is no such a method in the instrumented class - we will need to generate it at the end</p>\n\t */\n\tprivate boolean wasStaticInitMethodVisited = false;\n\n\tprivate final Set<String> ignoredMethods;\n\n\t/**\n\t * @param cv - a listener for code-instrumentation events\n\t * @param ignoreRegexes - list of patters of method calls that should be ignored from line-coverage-measurement\n\t * @param classMap - map of all interesting places in the class. You should acquire it by {@link BuildClassMapClassVisitor} and remember to\n\t * prepare it using {@link ClassMap#assignCounterIds()} before using it with {@link InjectCodeClassInstrumenter}\n\t * @param duplicatedLinesMap - map of found duplicates in the class. You should use {@link DetectDuplicatedCodeClassVisitor} to find the duplicated lines.\n\t */\n\tpublic InjectCodeClassInstrumenter(ClassVisitor cv,\n\t\t\tCollection<Pattern> ignoreRegexes, boolean threadsafeRigorous,\n\t\t\tboolean individualTest,\n\t\t\tClassMap classMap,\n\t\t\tMap<Integer, Map<Integer, Integer>> duplicatedLinesMap,\n\t\t\tSet<String> ignoredMethods) {\n\t\tsuper(cv, ignoreRegexes, duplicatedLinesMap);\n\t\tthis.classMap = classMap;\n\t\tthis.ignoredMethods = ignoredMethods;\n\t\t// If we are doing individual test unit items, then\n\t\t// let's use our own test unit provider, otherwise use the others.\n\t\t// Please note that the TestUnitCodeProvider is going to provide \n\t\t// stronger thread safety by using the ConcurrentHashMap API.\n\t\tif (individualTest) {\n\t\t\tcodeProvider = new TestUnitCodeProvider();\n\t\t} else {\n\t\t\tcodeProvider = threadsafeRigorous\n\t\t\t\t\t? new AtomicArrayCodeProvider()\n\t\t\t\t\t: new FastArrayCodeProvider();\n\t\t}\n\t\ttouchPointListener = new InjectCodeTouchPointListener(classMap,\n\t\t\t\tcodeProvider);\n\t}\n\n\t/**\n\t * <p>Marks the class 'already instrumented' and injects code connected to the fields that are keeping counters.</p>\n\t */\n\t@Override\n\tpublic void visit(int version, int access, String name, String signature,\n\t\t\tString supertype, String[] interfaces) {\n\n\t\tsuper.visit(version, access, name, signature, supertype, interfaces);\n\t\tcodeProvider.generateCountersField(cv);\n\t}\n\n\t/**\n\t * <p>Instrumenting a code in a single method. Special conditions for processing 'static initialization block'.</p>\n\t * <p/>\n\t * <p>This method also uses {@link ShiftVariableMethodAdapter} that is used firstly to calculate the index of internal\n\t * variable injected to store information about last 'processed' jump or switch in runtime ( {@link ShiftVariableMethodAdapter#calculateFirstStackVariable(int, String)} ),\n\t * and then is used to inject code responsible for keeping the variable and shifting (+1) all previously seen variables.\n\t */\n\t@Override\n\tpublic MethodVisitor visitMethod(int access, String name, String desc,\n\t\t\tString signature, String[] exceptions) {\n\t\tMethodVisitor mv = super.visitMethod(access, name, desc, signature,\n\t\t\t\texceptions);\n\t\tif (ignoredMethods.contains(name + desc)) {\n\t\t\treturn mv;\n\t\t}\n\t\tif ((access & Opcodes.ACC_STATIC) != 0) {\n\t\t\tmv = new GenerateCallCoberturaInitMethodVisitor(mv, classMap\n\t\t\t\t\t.getClassName());\n\t\t\tif (\"<clinit>\".equals(name)) {\n\t\t\t\twasStaticInitMethodVisited = true;\n\t\t\t}\n\t\t}\n\t\tFindTouchPointsMethodAdapter instrumenter = new FindTouchPointsMethodAdapter(\n\t\t\t\tmv, classMap.getClassName(), name, desc, eventIdGenerator,\n\t\t\t\tduplicatedLinesMap, lineIdGenerator);\n\t\tinstrumenter.setTouchPointListener(touchPointListener);\n\t\tinstrumenter.setIgnoreRegexp(getIgnoreRegexp());\n\t\tLocalVariablesSorter sorter = new LocalVariablesSorter(access, desc,\n\t\t\t\tinstrumenter);\n\t\tint variable = sorter.newLocal(Type.INT_TYPE);\n\t\ttouchPointListener.setLastJumpIdVariableIndex(variable);\n\t\treturn sorter;\n\t\t//return new ShiftVariableMethodAdapter(instrumenter, access, desc, 1);\n\t}\n\n\t/**\n\t * Method instrumenter that injects {@link CodeProvider#generateCINITmethod(MethodVisitor, String, int)} code, and\n\t * then forwards the whole previous content of the method.\n\t *\n\t * @author piotr.tabor@gmail.com\n\t */\n\tprivate class GenerateCallCoberturaInitMethodVisitor extends MethodVisitor {\n\t\tprivate String className;\n\t\tpublic GenerateCallCoberturaInitMethodVisitor(MethodVisitor arg0,\n\t\t\t\tString className) {\n\t\t\tsuper(Opcodes.ASM4, arg0);\n\t\t\tthis.className = className;\n\t\t}\n\n\t\t@Override\n\t\tpublic void visitCode() {\n\t\t\tcodeProvider.generateCallCoberturaInitMethod(mv, className);\n\t\t\tsuper.visitCode();\n\t\t}\n\t}\n\n\t/**\n\t * <p>If there was no 'static initialization block' in the class, the method is responsible for generating the method.<br/>\n\t * It is also responsible for generating method that keeps mapping of counterIds into source places connected to them</p>\n\t */\n\t@Override\n\tpublic void visitEnd() {\n\t\tif (!wasStaticInitMethodVisited) {\n\t\t\t//We need to generate new method\n\t\t\tMethodVisitor mv = super.visitMethod(Opcodes.ACC_STATIC,\n\t\t\t\t\t\"<clinit>\", \"()V\", null, null);\n\t\t\tmv.visitCode();\n\t\t\tcodeProvider.generateCallCoberturaInitMethod(mv, classMap\n\t\t\t\t\t.getClassName());\n\t\t\tmv.visitInsn(Opcodes.RETURN);\n\t\t\tmv.visitMaxs(/*stack*/3,/*local*/0);\n\t\t\tmv.visitEnd();\n\t\t\twasStaticInitMethodVisited = true;\n\t\t}\n\n\t\tcodeProvider.generateCoberturaInitMethod(cv, classMap.getClassName(),\n\t\t\t\tclassMap.getMaxCounterId() + 1);\n\t\tcodeProvider.generateCoberturaClassMapMethod(cv, classMap);\n\t\tcodeProvider.generateCoberturaGetAndResetCountersMethod(cv, classMap\n\t\t\t\t.getClassName());\n\n\t\tsuper.visitEnd();\n\t}\n\n}",
"public abstract class IOUtil {\n\n\t/**\n\t * Copies bytes from input stream into the output stream. Stops\n\t * when the input stream read method returns -1. Does not close\n\t * the streams.\n\t *\n\t * @throws IOException If either passed stream will throw IOException.\n\t * @throws NullPointerException If either passed stream is null.\n\t */\n\tpublic static void copyStream(InputStream in, OutputStream out)\n\t\t\tthrows IOException {\n\t\t// NullPointerException is explicity thrown to guarantee expected behaviour\n\t\tif (in == null || out == null)\n\t\t\tthrow new NullPointerException();\n\n\t\tint el;\n\t\tbyte[] buffer = new byte[1 << 15];\n\t\twhile ((el = in.read(buffer)) != -1) {\n\t\t\tout.write(buffer, 0, el);\n\t\t}\n\t}\n\n\t/**\n\t * Returns an array that contains values read from the\n\t * given input stream.\n\t *\n\t * @throws NullPointerException If null stream is passed.\n\t */\n\tpublic static byte[] createByteArrayFromInputStream(InputStream in)\n\t\t\tthrows IOException {\n\t\tByteArrayOutputStream byteArray = new ByteArrayOutputStream();\n\t\tcopyStream(in, byteArray);\n\t\treturn byteArray.toByteArray();\n\t}\n\n\t/**\n\t * Moves a file from one location to other.\n\t *\n\t * @throws IOException If IO exception occur during moving.\n\t * @throws NullPointerException If either passed file is null.\n\t */\n\tpublic static void moveFile(File sourceFile, File destinationFile)\n\t\t\tthrows IOException {\n\t\tif (destinationFile.exists()) {\n\t\t\tdestinationFile.delete();\n\t\t}\n\n\t\t// Move file using File method if possible\n\t\tboolean succesfulMove = sourceFile.renameTo(destinationFile);\n\t\tif (succesfulMove)\n\t\t\treturn;\n\n\t\t// Copy file from source to destination\n\t\tInputStream in = null;\n\t\tOutputStream out = null;\n\t\ttry {\n\t\t\tin = new FileInputStream(sourceFile);\n\t\t\tout = new FileOutputStream(destinationFile);\n\t\t\tcopyStream(in, out);\n\t\t} finally {\n\t\t\tin = closeInputStream(in);\n\t\t\tout = closeOutputStream(out);\n\t\t}\n\n\t\t// Remove source file\n\t\tsourceFile.delete();\n\t}\n\n\t/**\n\t * Closes an input stream.\n\t *\n\t * @param in The stream to close.\n\t *\n\t * @return null unless an exception was thrown while closing, else\n\t * returns the stream\n\t */\n\tpublic static InputStream closeInputStream(InputStream in) {\n\t\tif (in != null) {\n\t\t\ttry {\n\t\t\t\tin.close();\n\t\t\t\tin = null;\n\t\t\t} catch (IOException e) {\n\t\t\t\tSystem.err.println(\"Cobertura: Error closing input stream.\");\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\treturn in;\n\t}\n\n\t/**\n\t * Closes an output stream.\n\t *\n\t * @param out The stream to close.\n\t *\n\t * @return null unless an exception was thrown while closing, else\n\t * returns the stream.\n\t */\n\tpublic static OutputStream closeOutputStream(OutputStream out) {\n\t\tif (out != null) {\n\t\t\ttry {\n\t\t\t\tout.close();\n\t\t\t\tout = null;\n\t\t\t} catch (IOException e) {\n\t\t\t\tSystem.err.println(\"Cobertura: Error closing output stream.\");\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\treturn out;\n\t}\n\n\tpublic static PrintWriter getPrintWriter(File file)\n\t\t\tthrows UnsupportedEncodingException, FileNotFoundException {\n\t\tWriter osWriter = new BufferedWriter(new OutputStreamWriter(\n\t\t\t\tnew FileOutputStream(file), \"UTF-8\"), 16384);\n\t\tPrintWriter pw = new PrintWriter(osWriter, false);\n\t\treturn pw;\n\t}\n\n}"
] | import net.sourceforge.cobertura.util.IOUtil;
import org.apache.log4j.Logger;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.util.CheckClassAdapter;
import java.io.*;
import java.util.*;
import java.util.regex.Pattern;
import net.sourceforge.cobertura.coveragedata.ProjectData;
import net.sourceforge.cobertura.instrument.pass1.DetectDuplicatedCodeClassVisitor;
import net.sourceforge.cobertura.instrument.pass1.DetectIgnoredCodeClassVisitor;
import net.sourceforge.cobertura.instrument.pass2.BuildClassMapClassVisitor;
import net.sourceforge.cobertura.instrument.pass3.InjectCodeClassInstrumenter; | /*
* Cobertura - http://cobertura.sourceforge.net/
*
* Copyright (C) 2011 Piotr Tabor
*
* Note: This file is dual licensed under the GPL and the Apache
* Source License (so that it can be used from both the main
* Cobertura classes and the ant tasks).
*
* Cobertura is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation; either version 2 of the License,
* or (at your option) any later version.
*
* Cobertura is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Cobertura; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*/
package net.sourceforge.cobertura.instrument;
/**
* Class that is responsible for the whole process of instrumentation of a single class.
* <p/>
* The class is instrumented in tree passes:
* <ol>
* <li>Read only: {@link DetectDuplicatedCodeClassVisitor} - we look for the same ASM code snippets
* rendered in different places of destination code</li>
* <li>Read only: {@link BuildClassMapClassVisitor} - finds all touch-points and other interesting
* information that are in the class and store it in {@link ClassMap}.
* <li>Real instrumentation: {@link InjectCodeClassInstrumenter}. Uses {#link ClassMap} to inject
* code into the class</li>
* </ol>
*
* @author piotr.tabor@gmail.com
*/
public class CoberturaInstrumenter {
private static final Logger logger = Logger
.getLogger(CoberturaInstrumenter.class);
/**
* During the instrumentation process we are feeling {@link ProjectData}, to generate from
* it the *.ser file.
* <p/>
* We now (1.10+) don't need to generate the file (it is not necessery for reporting), but we still
* do it for backward compatibility (for example maven-cobertura-plugin expects it). We should avoid
* this some day.
*/
private ProjectData projectData;
/**
* The root directory for instrumented classes. If it is null, the instrumented classes are overwritten.
*/
private File destinationDirectory;
/**
* List of patterns to know that we don't want trace lines that are calls to some methods
*/
private Collection<Pattern> ignoreRegexes = new Vector<Pattern>();
/**
* Methods annotated by this annotations will be ignored during coverage measurement
*/
private Set<String> ignoreMethodAnnotations = new HashSet<String>();
/**
* If true: Getters, Setters and simple initialization will be ignored by coverage measurement
*/
private boolean ignoreTrivial;
/**
* If true: The process is interrupted when first error occurred.
*/
private boolean failOnError;
/**
* If true: We make sure to keep track of test unit that execute which individual line.
*/
private boolean individualTest;
/**
* Setting to true causes cobertura to use more strict threadsafe model that is significantly
* slower, but guarantees that number of hits counted for each line will be precise in multithread-environment.
* <p/>
* The option does not change measured coverage.
* <p/>
* In implementation it means that AtomicIntegerArray will be used instead of int[].
*/
private boolean threadsafeRigorous;
/**
* Used for storing all the test unit locations.
*/
private List<File> testUnitFilePath;
/**
* Analyzes and instruments class given by path.
* <p/>
* <p>Also the {@link #projectData} structure is filled with information about the found touch-points</p>
*
* @param file - path to class that should be instrumented
*
* @return instrumentation result structure or null in case of problems
*/
public InstrumentationResult instrumentClass(File file) {
InputStream inputStream = null;
try {
logger.debug("Working on file:" + file.getAbsolutePath());
inputStream = new FileInputStream(file);
return instrumentClass(inputStream);
} catch (Throwable t) {
logger.warn("Unable to instrument file " + file.getAbsolutePath(),
t);
if (failOnError) {
throw new RuntimeException(
"Warning detected and failOnError is true", t);
} else {
return null;
}
} finally {
IOUtil.closeInputStream(inputStream);
}
}
/**
* Analyzes and instruments class given by inputStream
* <p/>
* <p>Also the {@link #projectData} structure is filled with information about the found touch-points</p>
*
* @param inputStream - source of class to instrument
*
*
* @return instrumentation result structure or null in case of problems
*/
public InstrumentationResult instrumentClass(InputStream inputStream)
throws IOException {
if (testUnitFilePath != null &&
testUnitFilePath.size() > 0 &&
individualTest) {
new TestUnitInstrumenter(testUnitFilePath);
}
ClassReader cr0 = new ClassReader(inputStream);
ClassWriter cw0 = new ClassWriter(0);
DetectIgnoredCodeClassVisitor detectIgnoredCv = new DetectIgnoredCodeClassVisitor(
cw0, ignoreTrivial, ignoreMethodAnnotations);
DetectDuplicatedCodeClassVisitor cv0 = new DetectDuplicatedCodeClassVisitor(
detectIgnoredCv);
cr0.accept(cv0, 0);
ClassReader cr = new ClassReader(cw0.toByteArray());
ClassWriter cw = new ClassWriter(0);
BuildClassMapClassVisitor cv = new BuildClassMapClassVisitor(cw,
ignoreRegexes, cv0.getDuplicatesLinesCollector(),
detectIgnoredCv.getIgnoredMethodNamesAndSignatures());
cr.accept(cv, ClassReader.EXPAND_FRAMES);
if (logger.isDebugEnabled()) {
logger
.debug("=============== Detected duplicated code =============");
Map<Integer, Map<Integer, Integer>> l = cv0
.getDuplicatesLinesCollector();
for (Map.Entry<Integer, Map<Integer, Integer>> m : l.entrySet()) {
if (m.getValue() != null) {
for (Map.Entry<Integer, Integer> pair : m.getValue()
.entrySet()) {
logger.debug(cv.getClassMap().getClassName() + ":"
+ m.getKey() + " " + pair.getKey() + "->"
+ pair.getValue());
}
}
}
logger
.debug("=============== End of detected duplicated code ======");
}
//TODO(ptab): Don't like the idea, but we have to be compatible (hope to remove the line in future release)
logger
.debug("Migrating classmap in projectData to store in *.ser file: "
+ cv.getClassMap().getClassName());
cv.getClassMap().applyOnProjectData(projectData,
cv.shouldBeInstrumented());
if (cv.shouldBeInstrumented()) {
/*
* BuildClassMapClassInstrumenter and DetectDuplicatedCodeClassVisitor has not modificated bytecode,
* so we can use any bytecode representation of that class.
*/
ClassReader cr2 = new ClassReader(cw0.toByteArray());
ClassWriter cw2 = new CoberturaClassWriter(
ClassWriter.COMPUTE_FRAMES);
cv.getClassMap().assignCounterIds();
logger.debug("Assigned " + cv.getClassMap().getMaxCounterId()
+ " counters for class:" + cv.getClassMap().getClassName()); | InjectCodeClassInstrumenter cv2 = new InjectCodeClassInstrumenter( | 3 |
Atmosphere/wasync | wasync/src/main/java/org/atmosphere/wasync/serial/SerialSocketRuntime.java | [
"public class FunctionWrapper {\n\n private final String functionName;\n private final Function<?> function;\n\n public FunctionWrapper(String functionName, Function<?> function) {\n this.functionName = functionName;\n this.function = function;\n }\n\n public Function<?> function(){\n return function;\n }\n\n public String functionName() {\n return functionName;\n }\n}",
"public interface Future extends java.util.concurrent.Future<Socket> {\n /**\n * Send data to the remote Server.\n * @param message the message to fire\n * @return a {@link Future}\n * @throws java.io.IOException\n */\n Future fire(Object message) throws IOException;\n /**\n * Mark the future done. If an exception occurred, this method will throw it.\n * @return a {@link Future}\n */\n Future finishOrThrowException() throws IOException;\n\n /**\n * If an exception occurs, the {@link Transport} will set it using this method. An application can also\n * use that method to interrupt a blocking {@link Socket#open(Request)} operation. This operation\n * must unlock the current blocked thread.\n * @param t a {@link IOException}\n * @return a {@link Future}\n */\n Future ioException(IOException t);\n\n /**\n * Mark this instance as done.\n */\n void done();\n\n /**\n * Close the underlying {@link Socket}\n */\n void close();\n}",
"public interface Options {\n /**\n * The used {@link Transport}\n *\n * @return {@link Transport}\n */\n public Transport transport();\n\n /**\n * Reconnect after a network failure or when the server close the connection.\n *\n * @return reconnect\n */\n public boolean reconnect();\n\n /**\n * The delay, in milliseconds, before reconnecting.\n *\n * @return The delay, in milliseconds, before reconnecting.\n */\n public int reconnectTimeoutInMilliseconds();\n\n /**\n * Maximum reconnection attempts that will run in the interval defined by {@link #reconnectTimeoutInMilliseconds}\n *\n * @return the number of maximum reconnection attempts\n */\n public int reconnectAttempts();\n\n /**\n * When using long-polling and the {@link Request}, the delay before considering the long-polling connection has been fully processed by the server. If you use\n * the {@link org.atmosphere.wasync.impl.AtmosphereClient}, the server will send some handshake so this value is not needed.\n *\n * @return the delay before considering the long-polling connection has been fully processed\n */\n public long waitBeforeUnlocking();\n\n /**\n * The {@link AsyncHttpClient} used to communicate with server.\n *\n * @return {@link AsyncHttpClient} used to communicate with server.\n */\n public AsyncHttpClient runtime();\n\n /**\n * Set the {@link AsyncHttpClient}.\n *\n * @param client the {@link AsyncHttpClient}\n */\n public void runtime(AsyncHttpClient client);\n\n /**\n * Return true is the {@link AsyncHttpClient} is shared between {@link Socket}. Default is false. You need to invoke {@link #runtime(com.ning.http.client.AsyncHttpClient)} to make\n * it shared.\n *\n * @return true is the {@link AsyncHttpClient}\n */\n public boolean runtimeShared();\n\n /**\n * The time, in seconds to wait before closing the connection.\n *\n * @return The time, in seconds to wait before closing the connection.\n */\n public int requestTimeoutInSeconds();\n\n /**\n * Return true if binary data, instead of String/Text message, are sent back by the server. Default is false.\n *\n * @return true if binary data,\n */\n boolean binary();\n\n}",
"public interface Request {\n\n public enum METHOD {GET, POST, TRACE, PUT, DELETE, OPTIONS}\n public enum TRANSPORT {WEBSOCKET, SSE, STREAMING, LONG_POLLING}\n\n /**\n * The list of transports to try\n * @return a {@link TRANSPORT}\n */\n List<TRANSPORT> transport();\n\n /**\n * The method\n * @return a {@link METHOD}\n */\n METHOD method();\n\n /**\n * Return the list of headers\n * @return a Map of headers\n */\n HttpHeaders headers();\n\n /**\n * Return the list of query params\n * @return a Map of headers\n */\n Map<String, List<String>> queryString();\n\n /**\n * The list of {@link Encoder} to use before the request is sent.\n * @return The list of {@link Encoder}\n */\n List<Encoder<?,?>> encoders();\n\n /**\n * The list of {@link Decoder} to use before the request is sent.\n * @return The list of {@link Decoder}\n */\n List<Decoder<?,?>> decoders();\n\n /**\n * The targetted URI\n * @return the targetted URI\n */\n String uri();\n\n /**\n * The {@link FunctionResolver} associated with that request.\n * @return The {@link FunctionResolver}\n */\n FunctionResolver functionResolver();\n\n}",
"public interface Transport {\n\n /**\n * The transport name\n *\n * @return transport name\n */\n Request.TRANSPORT name();\n\n /**\n * Register a new {@link FunctionResolver}\n *\n * @param function {@link FunctionResolver}\n * @return this;\n */\n Transport registerF(FunctionWrapper function);\n\n /**\n * Called when an unexpected exception ocurred.\n *\n * @param t a {@link Throwable}\n */\n void onThrowable(Throwable t);\n\n /**\n * Close the underlying transport}\n */\n void close();\n\n /**\n * Return the current {@link org.atmosphere.wasync.Socket.STATUS}\n */\n Socket.STATUS status();\n\n /**\n * Error handled by a {@link Function}\n */\n boolean errorHandled();\n\n /**\n * Set a {@link Throwable}\n *\n * @param e {@link Throwable}\n */\n void error(Throwable e);\n\n /**\n * Set the {@link Future}, which can be used to clone the connection.\n *\n * @param f {@link Future}\n */\n void future(Future f);\n\n /**\n * Set the {@link Future}, which will unlock the {@link Socket#fire} method once the connection has been fully established.\n * @param f {@link Future}\n */\n void connectedFuture(Future f);\n}",
"public class DefaultFuture implements Future {\n\n private final DefaultSocket socket;\n private CountDownLatch latch = new CountDownLatch(1);\n private final AtomicBoolean done = new AtomicBoolean(false);\n private long time = -1;\n private TimeUnit tu;\n private TimeoutException te = null;\n private IOException ioException;\n\n public DefaultFuture(DefaultSocket socket) {\n this.socket = socket;\n }\n\n public long time(){\n return time;\n }\n\n public TimeUnit timeUnit(){\n return tu;\n }\n\n public DefaultFuture timeoutException(TimeoutException te) {\n this.te = te;\n return this;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public boolean cancel(boolean mayInterruptIfRunning) {\n latch.countDown();\n return true;\n }\n\n\n /**\n * {@inheritDoc}\n */\n @Override\n public boolean isCancelled() {\n return latch.getCount() == 0;\n }\n\n\n /**\n * {@inheritDoc}\n */\n @Override\n public boolean isDone() {\n return done.get();\n }\n\n public void done(){\n done.set(true);\n latch.countDown();\n }\n\n @Override\n public void close() {\n if (socket != null) {\n socket.close();\n }\n }\n\n // TODO: Not public\n /**\n * {@inheritDoc}\n */\n @Override\n public Future finishOrThrowException() throws IOException {\n done();\n try {\n if (ioException != null) {\n throw ioException;\n }\n } finally {\n ioException = null;\n }\n return this;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public Future ioException(IOException t) {\n ioException = t;\n done();\n return this;\n }\n\n protected void reset(){\n done.set(false);\n latch = new CountDownLatch(1);\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public Socket get() throws InterruptedException, ExecutionException {\n latch.await();\n return socket;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public Socket get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {\n time = timeout;\n tu = unit;\n try {\n if (!latch.await(timeout, unit) || te != null) {\n throw te == null ? new TimeoutException() : te;\n }\n } finally {\n te = null;\n }\n return socket;\n }\n\n protected Socket socket() {\n return socket;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public Future fire(Object data) throws IOException {\n reset();\n socket.internalSocket().write(socket.request(), data);\n return this;\n }\n}",
"public class SocketRuntime {\n\n private final static Logger logger = LoggerFactory.getLogger(SocketRuntime.class);\n\n protected Transport transport;\n protected final Options options;\n protected final DefaultFuture rootFuture;\n protected final List<FunctionWrapper> functions;\n\n public SocketRuntime(Transport transport, Options options, DefaultFuture rootFuture, List<FunctionWrapper> functions) {\n this.transport = transport;\n this.options = options;\n this.rootFuture = rootFuture;\n this.functions = functions;\n }\n\n public DefaultFuture future() {\n return rootFuture;\n }\n\n protected Object invokeEncoder(List<Encoder<? extends Object, ?>> encoders, Object instanceType) {\n for (Encoder e : encoders) {\n Class<?>[] typeArguments = TypeResolver.resolveArguments(e.getClass(), Encoder.class);\n\n if (typeArguments.length > 0 && typeArguments[0].isAssignableFrom(instanceType.getClass())) {\n instanceType = e.encode(instanceType);\n }\n }\n return instanceType;\n }\n\n public Future write(Request request, Object data) throws IOException {\n // Execute encoder\n Object object = invokeEncoder(request.encoders(), data);\n\n boolean webSocket = transport.name().equals(Request.TRANSPORT.WEBSOCKET);\n if (webSocket\n && (transport.status().equals(Socket.STATUS.CLOSE)\n || transport.status().equals(Socket.STATUS.ERROR))) {\n transport.error(new IOException(\"Invalid Socket Status \" + transport.status().name()));\n } else {\n if (webSocket) {\n webSocketWrite(request, object, data);\n } else {\n try {\n Response r = httpWrite(request, object, data).get(rootFuture.time(), rootFuture.timeUnit());\n String m = r.getResponseBody();\n if (m.length() > 0) {\n TransportsUtil.invokeFunction(request.decoders(), functions, String.class, m, MESSAGE.name(), request.functionResolver());\n }\n } catch (TimeoutException t) {\n logger.trace(\"AHC Timeout\", t);\n rootFuture.timeoutException(t);\n } catch (Throwable t) {\n logger.error(\"\", t);\n }\n }\n }\n\n return rootFuture.finishOrThrowException();\n }\n\n public void webSocketWrite(Request request, Object object, Object data) throws IOException {\n WebSocketTransport webSocketTransport = WebSocketTransport.class.cast(transport);\n if (InputStream.class.isAssignableFrom(object.getClass())) {\n InputStream is = (InputStream) object;\n ByteArrayOutputStream bs = new ByteArrayOutputStream();\n //TODO: We need to stream directly, in AHC!\n byte[] buffer = new byte[8192];\n int n = 0;\n while (-1 != (n = is.read(buffer))) {\n bs.write(buffer, 0, n);\n }\n webSocketTransport.sendMessage(bs.toByteArray());\n } else if (Reader.class.isAssignableFrom(object.getClass())) {\n Reader is = (Reader) object;\n StringWriter bs = new StringWriter();\n //TODO: We need to stream directly, in AHC!\n char[] chars = new char[8192];\n int n = 0;\n while (-1 != (n = is.read(chars))) {\n bs.write(chars, 0, n);\n }\n webSocketTransport.sendMessage(bs.getBuffer().toString());\n } else if (String.class.isAssignableFrom(object.getClass())) {\n webSocketTransport.sendMessage(object.toString());\n } else if (byte[].class.isAssignableFrom(object.getClass())) {\n webSocketTransport.sendMessage((byte[]) object);\n } else {\n throw new IllegalStateException(\"No Encoder for \" + data);\n }\n }\n\n public ListenableFuture<Response> httpWrite(Request request, Object object, Object data) throws IOException {\n\n BoundRequestBuilder b = configureAHC(request);\n\n if (InputStream.class.isAssignableFrom(object.getClass())) {\n //TODO: Allow reading the response.\n return b.setBody((InputStream) object).execute();\n } else if (Reader.class.isAssignableFrom(object.getClass())) {\n return b.setBody(new ReaderInputStream((Reader) object)).execute();\n } else if (String.class.isAssignableFrom(object.getClass())) {\n return b.setBody((String) object).execute();\n } else if (byte[].class.isAssignableFrom(object.getClass())) {\n return b.setBody((byte[]) object).execute();\n } else {\n throw new IllegalStateException(\"No Encoder for \" + data);\n }\n }\n\n protected BoundRequestBuilder configureAHC(Request request) {\n FluentStringsMap m = DefaultSocket.decodeQueryString(request);\n\n return options.runtime().preparePost(request.uri())\n .setHeaders(request.headers())\n .setQueryParams(m)\n .setMethod(Request.METHOD.POST.name());\n }\n\n}",
"public class WebSocketTransport extends WebSocketUpgradeHandler implements Transport {\n\n\tprivate final Logger logger = LoggerFactory.getLogger(WebSocketTransport.class);\n\tprivate NettyWebSocket webSocket;\n\n\tprivate final AtomicBoolean ok = new AtomicBoolean(false);\n\tprivate final AtomicInteger reconnectAttempt = new AtomicInteger();\n\tprivate final AtomicBoolean reconnecting = new AtomicBoolean(false);\n\n\tprivate final List<FunctionWrapper> functions;\n\tprivate final List<Decoder<?, ?>> decoders;\n\tprivate final FunctionResolver resolver;\n\tprivate final Options options;\n\tprivate final RequestBuilder requestBuilder;\n\tprivate final AtomicBoolean closed = new AtomicBoolean(false);\n\tprivate STATUS status = Socket.STATUS.INIT;\n\tprivate final AtomicBoolean errorHandled = new AtomicBoolean();\n\tprivate Future underlyingFuture;\n\tprivate Future connectOperationFuture;\n\tprotected final boolean protocolEnabled;\n\tprotected boolean supportBinary = false;\n\tprotected final ScheduledExecutorService timer;\n\tprotected boolean protocolReceived = false;\n\n\tpublic WebSocketTransport(RequestBuilder requestBuilder, Options options, Request request,\n\t\t\tList<FunctionWrapper> functions) {\n\t\tsuper(Collections.emptyList());\n\t\tthis.decoders = request.decoders();\n\n\t\tif (decoders.size() == 0) {\n\t\t\tdecoders.add(new Decoder<String, Object>() {\n\t\t\t\t@Override\n\t\t\t\tpublic Object decode(Event e, String s) {\n\t\t\t\t\treturn s;\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t\tthis.functions = functions;\n\t\tthis.resolver = request.functionResolver();\n\t\tthis.options = options;\n\t\tthis.requestBuilder = requestBuilder;\n\t\tthis.supportBinary = options.binary() ||\n\t\t// Backward compatibility.\n\t\t\t\t(request.headers().get(\"Content-Type\") != null\n\t\t\t\t\t\t? request.headers().get(\"Content-Type\").contains(\"application/octet-stream\")\n\t\t\t\t\t\t: false);\n\n\t\tprotocolEnabled = request.queryString().get(\"X-atmo-protocol\") != null;\n\t\ttimer = Executors.newSingleThreadScheduledExecutor();\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t */\n\t@Override\n\tpublic void onThrowable0(Throwable t) {\n\t\tlogger.debug(\"\", t);\n\t\tstatus = Socket.STATUS.ERROR;\n\t\tonFailure(t);\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t */\n\t@Override\n\tpublic void close() {\n\t\tstatus = Socket.STATUS.CLOSE;\n\t\tif (closed.getAndSet(true))\n\t\t\treturn;\n\n\t\tif (options.reconnectTimeoutInMilliseconds() <= 0 && !options.reconnect()) {\n\t\t\ttimer.shutdown();\n\t\t}\n\n\t\tTransportsUtil.invokeFunction(CLOSE, decoders, functions, String.class, CLOSE.name(), CLOSE.name(), resolver);\n\n\t\tif (webSocket != null && webSocket.isOpen())\n\t\t\twebSocket.sendCloseFrame();\n\n\t\tfutureDone();\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t */\n\t@Override\n\tpublic STATUS status() {\n\t\treturn status;\n\t}\n\n\tvoid futureDone() {\n\t\tif (underlyingFuture != null)\n\t\t\tunderlyingFuture.done();\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t */\n\t@Override\n\tpublic boolean errorHandled() {\n\t\treturn errorHandled.get();\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t */\n\t@Override\n\tpublic void error(Throwable t) {\n\t\tlogger.warn(\"\", t);\n\t\tboolean handled = TransportsUtil.invokeFunction(Event.ERROR, decoders, functions, t.getClass(), t, ERROR.name(), resolver);\n\t\tif (!handled) {\n\t\t\tconnectFutureException(t);\n\t\t}\n\t\tconnectOperationFuture.done();\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t */\n\t@Override\n\tpublic void future(Future f) {\n\t\tthis.underlyingFuture = f;\n\t}\n\n\t@Override\n\tpublic void connectedFuture(Future f) {\n\t\tthis.connectOperationFuture = f;\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t */\n\t@Override\n\tprotected void onBodyPartReceived0(HttpResponseBodyPart bodyPart) throws Exception {\n\t\tlogger.trace(\"Body received {}\", new String(bodyPart.getBodyPartBytes()));\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t */\n\t@Override\n\tprotected void onStatusReceived0(HttpResponseStatus responseStatus) throws Exception {\n\t\tlogger.trace(\"Status received {}\", responseStatus);\n\t\tTransportsUtil.invokeFunction(STATUS, decoders, functions, Integer.class,\n\t\t\t\tnew Integer(responseStatus.getStatusCode()), STATUS.name(), resolver);\n\t\tif (responseStatus.getStatusCode() != 101) {\n\t\t\tlogger.debug(\"Invalid status code {} for WebSocket Handshake\", responseStatus.getStatusCode());\n\t\t\tstatus = Socket.STATUS.ERROR;\n\t\t\tthrow new TransportNotSupported(responseStatus.getStatusCode(), responseStatus.getStatusText());\n\t\t}\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t */\n\t@Override\n\tprotected void onHeadersReceived0(HttpHeaders headers) throws Exception {\n\t\tlogger.trace(\"Headers received {}\", headers);\n\n\t\tMap<String, String> headerMap = new HashMap<String, String>();\n\t\tfor (Map.Entry<String, String> entry : headers) {\n\t\t\theaderMap.put(entry.getKey(), entry.getValue());\n\t\t}\n\t\tTransportsUtil.invokeFunction(HEADERS, decoders, functions, Map.class, headerMap, HEADERS.name(), resolver);\n\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t */\n\t@Override\n\tprotected void onCompleted0() throws Exception {\n\t\tlogger.trace(\"onCompleted {}\", webSocket);\n\t\tif (webSocket == null) {\n\t\t\tlogger.error(\"WebSocket Handshake Failed\");\n\t\t\tstatus = Socket.STATUS.ERROR;\n\t\t\treturn;\n\t\t}\n\t\tTransportsUtil.invokeFunction(TRANSPORT, decoders, functions, Request.TRANSPORT.class, name(), TRANSPORT.name(),\n\t\t\t\tresolver);\n\t}\n\n\tvoid unlockFuture() {\n\t\ttry {\n\t\t\tconnectOperationFuture.finishOrThrowException();\n\t\t} catch (IOException e) {\n\t\t\tlogger.warn(\"\", e);\n\t\t}\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t */\n\t@Override\n\tprotected void onOpen0() {\n\t\tlogger.trace(\"onOpen {}\", webSocket);\n\n\t\tif (connectOperationFuture != null && !protocolEnabled) {\n\t\t\tunlockFuture();\n\t\t}\n\n\t\tWebSocketListener l = new TextListener();\n\t\tif (supportBinary) {\n\t\t\tl = new BinaryListener(l);\n\t\t}\n\t\twebSocket.addWebSocketListener(l);\n\t\tl.onOpen(webSocket);\n\t}\n\n\t@Override\n\tprotected void setWebSocket0(NettyWebSocket webSocket) {\n\t\tthis.webSocket = webSocket;\n\t}\n\n\tvoid connectFutureException(Throwable t) {\n\t\tIOException e = IOException.class.isAssignableFrom(t.getClass()) ? (IOException) t\n\t\t\t\t: new IOException(t);\n\t\tconnectOperationFuture.ioException(e);\n\t}\n\n\tvoid tryReconnect() {\n\n\t\treconnectAttempt.incrementAndGet();\n\n\t\tif (options.reconnectTimeoutInMilliseconds() > 0) {\n\t\t\ttimer.schedule(new Runnable() {\n\t\t\t\tpublic void run() {\n\t\t\t\t\treconnect();\n\t\t\t\t}\n\t\t\t}, options.reconnectTimeoutInMilliseconds(), TimeUnit.MILLISECONDS);\n\t\t} else {\n\t\t\treconnect();\n\t\t}\n\t}\n\n\tvoid reconnect() {\n\t\ttry {\n\t\t\treconnecting.set(true);\n\t\t\tok.set(false);\n\n\t\t\tstatus = Socket.STATUS.REOPENED;\n\n\t\t\tListenableFuture<NettyWebSocket> webSocketListenableFuture = options.runtime()\n\t\t\t\t\t.executeRequest(requestBuilder.build(), WebSocketTransport.this);\n\n\t\t\tlogger.info(\"try reconnect : attempt [{}/{}]\", reconnectAttempt.get(), options.reconnectAttempts());\n\n\t\t\twebSocketListenableFuture.get();\n\n\t\t\tlogger.info(\"reconnect successful ! in attempt [{}/{}]\", reconnectAttempt.get(),\n\t\t\t\t\toptions.reconnectAttempts());\n\n\t\t\tTransportsUtil.invokeFunction(REOPENED, decoders, functions, String.class, REOPENED.name(), REOPENED.name(),\n\t\t\t\t\tresolver);\n\n\t\t\tclosed.set(false);\n\t\t\treconnectAttempt.set(0);\n\t\t\treconnecting.set(false);\n\t\t} catch (InterruptedException e) {\n\t\t\treconnecting.set(false);\n\t\t\tlogger.error(\"\", e);\n\t\t} catch (ExecutionException e) {\n\n\t\t\tif (reconnectAttempt.get() < options.reconnectAttempts()) {\n\t\t\t\ttryReconnect();\n\t\t\t} else {\n\t\t\t\treconnecting.set(false);\n\t\t\t\treconnectAttempt.set(0);\n\t\t\t\tonFailure(e.getCause() != null ? e.getCause() : e);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic boolean touchSuccess() {\n\t\treturn ok.getAndSet(true);\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t */\n\t@Override\n\tpublic Request.TRANSPORT name() {\n\t\treturn Request.TRANSPORT.WEBSOCKET;\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t */\n\t@Override\n\tpublic Transport registerF(FunctionWrapper function) {\n\t\tfunctions.add(function);\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t */\n\t// @Override\n\tpublic final void onFailure(Throwable t) {\n\n\t\tif (!reconnecting.get()) {\n\t\t\tlogger.trace(\"onFailure {}\", t);\n\n\n\t\t\tboolean handled = TransportsUtil.invokeFunction(ERROR, decoders, functions, t.getClass(), t, ERROR.name(), resolver);\n\t\t\tif (!handled){\n\t\t\t\tconnectFutureException(t);\n\t\t\t}\n\t\t\terrorHandled.set(handled);\n\t\t\tconnectOperationFuture.done();\n\t\t}\n\t}\n\n\tpublic WebSocketTransport sendMessage(String message) {\n\t\tif (webSocket != null && !status.equals(Socket.STATUS.ERROR) && !status.equals(Socket.STATUS.CLOSE)) {\n\t\t\twebSocket.sendTextFrame(message);\n\t\t}\n\t\treturn this;\n\t}\n\n\tpublic WebSocketTransport sendMessage(byte[] message) {\n\t\tif (webSocket != null && !status.equals(Socket.STATUS.ERROR) && !status.equals(Socket.STATUS.CLOSE)) {\n\t\t\twebSocket.sendBinaryFrame(message);\n\t\t}\n\t\treturn this;\n\t}\n\n\tprivate final class TextListener implements WebSocketListener {\n\n\t\t@Override\n\t\tpublic void onTextFrame(String message, boolean finalFragment, int rsv) {\n\t\t\tlogger.trace(\"onMessage {} for {}\", message, webSocket);\n\t\t\tlogger.trace(\"{} received {}\", name(), message);\n\t\t\tif (protocolReceived || message.length() > 0) {\n\t\t\t\tTransportsUtil.invokeFunction(MESSAGE, decoders, functions, message.getClass(), message, MESSAGE.name(),\n\t\t\t\t\t\tresolver);\n\n\t\t\t\t// Since the protocol is enabled, handshake occurred, now ready so go\n\t\t\t\t// asynchronous\n\t\t\t\tif (connectOperationFuture != null && protocolEnabled) {\n\t\t\t\t\tunlockFuture();\n\t\t\t\t}\n\t\t\t}\n\t\t\tprotocolReceived = true;\n\t\t}\n\n\t\t@Override\n\t\tpublic void onOpen(WebSocket websocket) {\n\t\t\tlogger.trace(\"onOpen for {}\", webSocket);\n\n\t\t\t// Could have been closed during the handshake.\n\t\t\tif (status.equals(Socket.STATUS.CLOSE) || status.equals(Socket.STATUS.ERROR))\n\t\t\t\treturn;\n\n\t\t\tclosed.set(false);\n\t\t\tEvent newStatus = status.equals(Socket.STATUS.INIT) ? OPEN : REOPENED;\n\t\t\tstatus = Socket.STATUS.OPEN;\n\t\t\tTransportsUtil.invokeFunction(newStatus, decoders, functions, String.class, newStatus.name(),\n\t\t\t\t\tnewStatus.name(), resolver);\n\t\t}\n\n\t\t@Override\n\t\tpublic void onClose(WebSocket websocket, int code, String reason) {\n\t\t\tlogger.trace(\"onClose for {}\", webSocket);\n\t\t\tif (closed.get())\n\t\t\t\treturn;\n\n\t\t\tclose();\n\t\t\tif (options.reconnect()) {\n\t\t\t\ttryReconnect();\n\t\t\t}\n\t\t}\n\n\t\t@Override\n\t\tpublic void onError(Throwable t) {\n\t\t\tlogger.trace(\"onError for {}\", t);\n\t\t\tstatus = Socket.STATUS.ERROR;\n\t\t\tlogger.debug(\"\", t);\n\n\t\t\t// On Android, ErrnoException is fired if lose connection (WIFI) or timeout\n\t\t\tif (t.getClass().getName().equals(\"android.system.ErrnoException\")) {\n\t\t\t\tif (options.reconnect()) {\n\t\t\t\t\tclose(); // force release resources and reconnect\n\t\t\t\t\ttryReconnect();\n\t\t\t\t} else {\n\t\t\t\t\tonFailure(new IOException(t.getMessage(), t));\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tonFailure(t);\n\t\t\t}\n\n\t\t}\n\t}\n\n\tprivate final class BinaryListener implements WebSocketListener {\n\n\t\tprivate final WebSocketListener l;\n\n\t\tprivate BinaryListener(WebSocketListener l) {\n\t\t\tthis.l = l;\n\t\t}\n\n\t\t@Override\n\t\tpublic void onBinaryFrame(byte[] message, boolean finalFragment, int rsv) {\n\t\t\tlogger.trace(\"{} received {}\", name(), message);\n\t\t\tif (protocolReceived || (message.length > 0 && !Utils.whiteSpace(message))) {\n\t\t\t\tTransportsUtil.invokeFunction(MESSAGE, decoders, functions, message.getClass(), message, MESSAGE.name(),\n\t\t\t\t\t\tresolver);\n\n\t\t\t\t// Since the protocol is enabled, handshake occurred, now ready so go\n\t\t\t\t// asynchronous\n\t\t\t\tif (connectOperationFuture != null && protocolEnabled) {\n\t\t\t\t\tunlockFuture();\n\t\t\t\t}\n\t\t\t}\n\t\t\tprotocolReceived = true;\n\t\t}\n\n\t\t@Override\n\t\tpublic void onOpen(WebSocket websocket) {\n\t\t\tl.onOpen(websocket);\n\t\t}\n\n\t\t@Override\n\t\tpublic void onClose(WebSocket websocket, int code, String reason) {\n\t\t\tl.onClose(websocket, code, reason);\n\t\t}\n\n\t\t@Override\n\t\tpublic void onError(Throwable t) {\n\t\t\tl.onError(t);\n\t\t}\n\t}\n}",
"public class FutureProxy<T extends java.util.concurrent.Future> implements Future {\n\n private final Socket socket;\n private final T proxyiedFuture;\n private IOException ioException;\n\n public FutureProxy(Socket socket, T proxyiedFuture) {\n this.socket = socket;\n this.proxyiedFuture = proxyiedFuture;\n }\n\n @Override\n public Future fire(Object data) throws IOException {\n return socket.fire(data);\n }\n\n @Override\n public Future finishOrThrowException() throws IOException{\n done();\n if (ioException != null) {\n throw ioException;\n }\n return this;\n }\n\n @Override\n public Future ioException(IOException t) {\n ioException = t;\n return this;\n }\n\n @Override\n public void done() {\n if (ListenableFuture.class.isAssignableFrom(proxyiedFuture.getClass())) {\n ListenableFuture.class.cast(proxyiedFuture).done();\n } else if (Future.class.isAssignableFrom(proxyiedFuture.getClass())) {\n Future.class.cast(proxyiedFuture).done();\n }\n }\n\n @Override\n public boolean cancel(boolean mayInterruptIfRunning) {\n if (ListenableFuture.class.isAssignableFrom(proxyiedFuture.getClass())) {\n return ListenableFuture.class.cast(proxyiedFuture).cancel(mayInterruptIfRunning);\n } else if (Future.class.isAssignableFrom(proxyiedFuture.getClass())) {\n return Future.class.cast(proxyiedFuture).cancel(mayInterruptIfRunning);\n }\n return false;\n }\n\n @Override\n public boolean isCancelled() {\n return proxyiedFuture.isCancelled();\n }\n\n @Override\n public boolean isDone() {\n return proxyiedFuture.isDone();\n }\n\n @Override\n public Socket get() throws InterruptedException, ExecutionException {\n proxyiedFuture.get();\n return socket;\n }\n\n @Override\n public Socket get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {\n proxyiedFuture.get(timeout, unit);\n return socket;\n }\n\n @Override\n public void close() {\n if (socket != null) {\n socket.close();\n }\n }\n}"
] | import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.util.concurrent.SettableFuture;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.util.List;
import org.asynchttpclient.Response;
import org.atmosphere.wasync.FunctionWrapper;
import org.atmosphere.wasync.Future;
import org.atmosphere.wasync.Options;
import org.atmosphere.wasync.Request;
import org.atmosphere.wasync.Transport;
import org.atmosphere.wasync.impl.DefaultFuture;
import org.atmosphere.wasync.impl.SocketRuntime;
import org.atmosphere.wasync.transport.WebSocketTransport;
import org.atmosphere.wasync.util.FutureProxy; | /*
* Copyright 2008-2022 Async-IO.org
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.atmosphere.wasync.serial;
/**
* Serial extension for the {@link SocketRuntime}
*
* @author Jeanfrancois Arcand
*/
public class SerialSocketRuntime extends SocketRuntime {
private final static Logger logger = LoggerFactory.getLogger(SerialSocketRuntime.class);
private final SerializedSocket serializedSocket;
| public SerialSocketRuntime(Transport transport, Options options, DefaultFuture rootFuture, SerializedSocket serializedSocket, List<FunctionWrapper> functions) { | 0 |
tteguayco/JITRAX | src/es/ull/etsii/jitrax/database/DatabaseComparator.java | [
"public class Attribute {\n\n\tprivate String name;\n\tprivate DataType dataType;\n\t\n\tpublic Attribute(String aName, DataType aDataType) {\n\t\tname = aName;\n\t\tdataType = aDataType;\n\t}\n\t\n\tpublic boolean equals(Object object) {\n\t\tif (object != null && object instanceof Attribute) {\n\t\t\tAttribute anotherAttr = (Attribute) object;\n\t\t\t\n\t\t\t// Comparing names and domains (data types)\n\t\t\tif (this.getName().equalsIgnoreCase(anotherAttr.getName())) {\n\t\t\t\tif (this.getDataType() == anotherAttr.getDataType()) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn false;\n\t}\n\t\n\tpublic int hashCode() {\n\t\treturn getName().hashCode() * getDataType().hashCode();\n\t}\n\t\n\tpublic String toString() {\n\t\tString toString = \"\";\t\n\t\ttoString += getName() + \" (\" + getDataType() + \")\";\n\t\n\t\treturn toString;\n\t}\n\t\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic DataType getDataType() {\n\t\treturn dataType;\n\t}\n\n\tpublic void setDataType(DataType dataType) {\n\t\tthis.dataType = dataType;\n\t}\n}",
"public enum DataType {\n\tCHAR, STRING, INT, FLOAT, DATE;\n\t\n\tpublic String toString() {\n\t\tswitch(this) {\n\t\t\tcase CHAR: return \"Char\";\n\t\t\tcase STRING: return \"String\";\n\t\t\tcase INT: return \"Integer\";\n\t\t\tcase FLOAT: return \"Float\";\n\t\t\tcase DATE: return \"Date\";\n\t\t\tdefault: return \"\";\n\t\t}\n\t}\n}",
"public class Database {\n\n\tprivate String name;\n\tprivate ArrayList<Table> tables;\n\tprivate DbmsDriver dbmsDriver;\n\t\n\t/**\n\t * @param name name for the database.\n\t */\n\tpublic Database(String aName) {\n\t\tname = aName;\n\t\ttables = new ArrayList<Table>();\n\t}\n\t\n\tpublic Database(String aName, ArrayList<Table> tableList) {\n\t\tname = aName;\n\t\ttables = tableList;\n\t}\n\t\n\tpublic void addTable(Table newTable) throws DuplicateTableException {\n\t\tif (containsTable(newTable.getName())) {\n\t\t\tthrow new DuplicateTableException();\n\t\t}\n\t\t\n\t\tgetTables().add(newTable);\n\t}\n\t\n\tpublic void removeTable(Table tableToRemove) {\n\t\tfor (int i = 0; i < tables.size(); i++) {\n\t\t\tif (tables.get(i).getName().equalsIgnoreCase(tableToRemove.getName())) {\n\t\t\t\ttables.remove(i);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic String[] getTablesNames() {\n\t\tString[] tablesNames = new String[getTables().size()];\n\t\t\n\t\tfor (int i = 0; i < getTables().size(); i++) {\n\t\t\ttablesNames[i] = getTables().get(i).getName();\n\t\t}\n\t\t\n\t\treturn tablesNames;\n\t}\n\t\n\t/**\n\t * Ask if the database contains the specified table \n\t * (case sensitive way).\n\t * \n\t * @param tableName\n\t * @return\n\t */\n\tpublic boolean containsTable(String tableName) {\n\t\tfor (int i = 0; i < getTables().size(); i++) {\n\t\t\tif (getTables().get(i).getName().equalsIgnoreCase(tableName)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn false;\n\t}\n\t\n\t/**\n\t * Returns the attribute which matches the name.\n\t * @param attrName\n\t * @return\n\t */\n\tpublic Attribute getAttributeByName(String attrName) {\n\t\tfor (int i = 0; i < getTables().size(); i++) {\n\t\t\tfor (int j = 0; j < getTables().get(i).getAttributes().size(); j++) {\n\t\t\t\tAttribute auxAttr = getTables().get(i).getAttributes().get(j);\n\t\t\t\tif (attrName.equalsIgnoreCase(auxAttr.getName())) {\n\t\t\t\t\treturn auxAttr;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn null;\n\t}\n\t\n\tpublic String toString() {\n\t\treturn getName();\n\t}\n\t\n\tpublic String toDSL() {\n\t\tString toString = \"\";\n\t\t\n\t\ttoString += \"DATABASE \" + getName() + \";\\n\";\n\t\t\n\t\tfor (int i = 0; i < getTables().size(); i++) {\n\t\t\ttoString += \"\\nTABLE \" + getTables().get(i).getName() + \" (\";\n\t\t\t\n\t\t\t// Attributes with domains\n\t\t\tfor (int j = 0; j < getTables().get(i).getAttributes().size(); j++) {\n\t\t\t\ttoString += getTables().get(i).getAttributes().get(j).getName() + \": \" +\n\t\t\t\t\t\tgetTables().get(i).getAttributes().get(j).getDataType();\n\t\t\t\t\n\t\t\t\t// Add semicolon\n\t\t\t\tif (j < getTables().get(i).getAttributes().size() - 1) {\n\t\t\t\t\ttoString += \",\\n\";\n\t\t\t\t} \n\t\t\t\t\n\t\t\t\telse {\n\t\t\t\t\ttoString += \")\\n\";\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\ttoString += \"=>\\n\";\n\t\t\t\n\t\t\t// Rows\n\t\t\tfor (int j = 0; j < getTables().get(i).getRows().size(); j++) {\n\t\t\t\ttoString += \"(\";\n\t\t\t\tfor (int k = 0; k < getTables().get(i).getRows().get(j).size(); k++) {\n\t\t\t\t\tString datum = getTables().get(i).getRows().get(j).getData().get(k).getStringValue();\n\t\t\t\t\ttoString += datum;\n\t\t\t\t\t\n\t\t\t\t\tif (k < getTables().get(i).getRows().get(j).size() - 1) {\n\t\t\t\t\t\ttoString += \",\";\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\telse {\n\t\t\t\t\t\ttoString += \");\\n\";\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn toString;\n\t}\n\t\n\t/**\n\t * Returns the table whose name matches the specified.\n\t * \n\t * @param tableName\n\t * @return\n\t */\n\tpublic Table getTableByName(String tableName) {\n\t\tfor (int i = 0; i < getTables().size(); i++) {\n\t\t\tif (tableName.equalsIgnoreCase(getTables().get(i).getName())) {\n\t\t\t\treturn getTables().get(i);\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn null;\n\t}\n\t\n\t/**\n\t * Returns the number of tables the DB has.\n\t * @return\n\t */\n\tpublic int getNumOfTables() {\n\t\treturn getTables().size();\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic ArrayList<Table> getTables() {\n\t\treturn tables;\n\t}\n\n\tpublic void setTables(ArrayList<Table> tables) {\n\t\tthis.tables = tables;\n\t}\n\n\tpublic DbmsDriver getDbmsDriver() {\n\t\treturn dbmsDriver;\n\t}\n\n\tpublic void setDbmsDriver(DbmsDriver dbmsDriver) {\n\t\tthis.dbmsDriver = dbmsDriver;\n\t}\n}",
"public class Datum {\n\tprivate String stringValue;\n\t\n\tpublic Datum(String aValue) {\n\t\tstringValue = aValue;\n\t}\n\t\n\tpublic boolean equals(Datum anOther) {\n\t\tif (anOther.getStringValue().equals(this.getStringValue())) {\n\t\t\treturn true;\n\t\t}\n\t\t\n\t\treturn false;\n\t}\n\t\n\tpublic String toString() {\n\t\tString toString = \"\";\n\t\ttoString += getStringValue();\n\t\t\n\t\treturn toString;\n\t}\n\t\n\tpublic String getStringValue() {\n\t\treturn stringValue;\n\t}\n\n\tpublic void setStringValue(String stringValue) {\n\t\tthis.stringValue = stringValue;\n\t}\n}",
"public class Row {\n\t\n\tprivate ArrayList<Attribute> tableAttributes;\n\tprivate ArrayList<Datum> data;\n\t\n\tpublic Row(ArrayList<Attribute> attributes, ArrayList<Datum> rowData) {\n\t\ttableAttributes = attributes;\n\t\tdata = rowData;\n\t}\n\n\t/**\n\t * The size of a row is its number of attributes or column.\n\t * @return\n\t */\n\tpublic int size() {\n\t\treturn getData().size();\n\t}\n\t\n\tpublic boolean equals(Row anOther) {\n\t\tif (anOther.size() != this.size()) {\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\t// Comparing Data\n\t\tfor (int i = 0; i < anOther.size(); i++) {\n\t\t\tif (!anOther.getDatum(i).equals(this.getDatum(i))) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn true;\n\t}\n\t\n\tpublic Datum getDatum(int index) {\n\t\treturn getData().get(index);\n\t}\n\t\n\tpublic String toString() {\n\t\tString toString = \"\";\n\t\t\n\t\tfor (int i = 0; i < getData().size(); i++) {\n\t\t\ttoString += getData().get(i).getStringValue() + \",\";\n\t\t}\n\t\t\n\t\treturn toString;\n\t}\n\t\n\tpublic ArrayList<Attribute> getTableAttributes() {\n\t\treturn tableAttributes;\n\t}\n\n\tpublic void setTableAttributes(ArrayList<Attribute> tableAttributes) {\n\t\tthis.tableAttributes = tableAttributes;\n\t}\n\n\tpublic ArrayList<Datum> getData() {\n\t\treturn data;\n\t}\n\n\tpublic void setData(ArrayList<Datum> data) {\n\t\tthis.data = data;\n\t}\n}",
"public class Table {\n\tprivate String name;\n\tprivate ArrayList<Attribute> attributes;\n\tprivate LinkedHashMap<String, Integer> attributesNames;\n\tprivate ArrayList<Row> rows;\n\t\n\tpublic Table(String aName, ArrayList<Attribute> attrList) {\n\t\tname = aName;\n\t\tattributes = attrList;\n\t\tattributesNames = new LinkedHashMap<String, Integer>();\n\t\trows = new ArrayList<Row>();\n\t}\n\n\t/**\n\t * Returns true if an attribute already exists.\n\t * @param anAttribute\n\t * @return\n\t */\n\tprivate boolean attributeExists(String attributeName) {\n\t\tif (getAttributesNames().containsKey(attributeName)) {\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\tpublic boolean attributeExists(String attrName, DataType attrDataType) {\n\t\tfor (int i = 0; i < getAttributes().size(); i++) {\n\t\t\tif (getAttributes().get(i).getName().equalsIgnoreCase(attrName) \n\t\t\t\t\t&& getAttributes().get(i).getDataType() == attrDataType) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn false;\n\t}\n\t\n\tpublic Attribute getAttributeByName(String attrName) {\n\t\tfor (int i = 0; i < getAttributes().size(); i++) {\n\t\t\tif (getAttributes().get(i).getName().equalsIgnoreCase(attrName)) {\n\t\t\t\treturn getAttributes().get(i);\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn null;\n\t}\n\t\n\tpublic Row getRowAt(int rowIndex) {\n\t\treturn rows.get(rowIndex);\n\t}\n\t\n\t/**\n\t * Returns the names of the columns of this table.\n\t */\n\tpublic String[] getColumnsNames() {\n\t\tString[] columnNames = new String[getAttributes().size()];\n\t\t\n\t\tfor (int i = 0; i < getAttributes().size(); i++) {\n\t\t\tcolumnNames[i] = getAttributes().get(i).getName();\n\t\t}\n\t\t\n\t\treturn columnNames;\n\t}\n\t\n\tpublic String[][] getRowsData() {\n\t\tString[][] rowsData = new String[getRows().size()][getAttributes().size()];\n\t\t\n\t\tfor (int i = 0; i < getRows().size(); i++) {\n\t\t\tfor (int j = 0; j < getRows().get(i).size(); j++) {\n\t\t\t\trowsData[i][j] = getRows().get(i).getData().get(j).getStringValue();\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn rowsData;\n\t}\n\t\n\t/**\n\t * The size of a table will be its number of attributes.\n\t * @return\n\t */\n\tpublic int getNumOfColumns() {\n\t\treturn getAttributes().size();\n\t}\n\t\n\tpublic int getNumOfRows() {\n\t\treturn getRows().size();\n\t}\n\t\n\t/**\n\t * Adds a new row or tuple to this table.\n\t * @return\n\t */\n\tpublic void addRow(ArrayList<Datum> newRowData) {\n\t\tRow newRow = new Row(getAttributes(), newRowData);\n\t\tgetRows().add(newRow);\n\t}\n\t\n\tpublic void addRow(Row newRow) {\n\t\tgetRows().add(newRow);\n\t}\n\t\n\tpublic void addRowIfNotExist(Row newRow) {\n\t\tfor (int i = 0; i < getRows().size(); i++) {\n\t\t\tif (getRows().get(i).equals(newRow)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\t\n\t\taddRow(newRow);\n\t}\n\t\n\tpublic void removeRowByIndex(int rowIndex) {\n\t\tgetRows().remove(rowIndex);\n\t}\n\t\n\t/**\n\t * Adds a new attribute to the table. Returns false if couldn't do it\n\t * because the attribute already exists.\n\t * @param attributeName\n\t * @param attributeDatatype\n\t * @return\n\t */\n\tpublic boolean addAttribute(String attributeName, DataType attributeDatatype) {\n\t\tif (!attributeExists(attributeName)) {\n\t\t\tAttribute newAttribute = new Attribute(attributeName, attributeDatatype);\n\t\t\tgetAttributes().add(newAttribute);\n\t\t\treturn true;\n\t\t\t\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\tpublic String toString() {\n\t\tString toString = \"\";\n\t\t\n\t\ttoString += \"TABLE \" + getName() + \"\\n\";\n\t\ttoString += \"ATTRIBUTES\\n\";\n\t\tfor (int i = 0; i < getAttributes().size(); i++) {\n\t\t\ttoString += getAttributes().get(i).toString() + \"\\n\";\n\t\t}\n\t\t\n\t\ttoString += \"DATA\\n\";\n\t\tfor (int i = 0; i < getRows().size(); i++) {\n\t\t\ttoString += getRows().get(i).toString() + \"\\n\";\n\t\t}\n\t\t\n\t\treturn toString;\n\t}\n\t\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic ArrayList<Attribute> getAttributes() {\n\t\treturn attributes;\n\t}\n\n\tpublic void setAttributes(ArrayList<Attribute> attributes) {\n\t\tthis.attributes = attributes;\n\t}\n\n\tpublic HashMap<String, Integer> getAttributesNames() {\n\t\treturn attributesNames;\n\t}\n\n\tpublic void setAttributesNames(LinkedHashMap<String, Integer> attributesNames) {\n\t\tthis.attributesNames = attributesNames;\n\t}\n\n\tpublic ArrayList<Row> getRows() {\n\t\treturn rows;\n\t}\n\n\tpublic void setRows(ArrayList<Row> rows) {\n\t\tthis.rows = rows;\n\t}\n}"
] | import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import es.ull.etsii.jitrax.adt.Attribute;
import es.ull.etsii.jitrax.adt.DataType;
import es.ull.etsii.jitrax.adt.Database;
import es.ull.etsii.jitrax.adt.Datum;
import es.ull.etsii.jitrax.adt.Row;
import es.ull.etsii.jitrax.adt.Table; |
// Getting the number of rows returned (number of attributes in the current table)
// and storing it in the 'numberOfAttributesForRemote'
if (attrResultSet != null) {
attrResultSet.beforeFirst();
attrResultSet.last();
numberOfAttributesForRemote = attrResultSet.getRow();
attrResultSet.beforeFirst();
}
// If the number of attributes differs, databases are not compatibles
if (currentLocalTable.getNumOfColumns() != numberOfAttributesForRemote) {
return false;
}
// COMPARING ATTRIBUTES
while (attrResultSet.next()) {
String attrName = attrResultSet.getString("COLUMN_NAME");
String attrType = attrResultSet.getString("TYPE_NAME");
DataType attrDataType;
// Comparing data types
if (attrType.contains("varchar")) {
attrDataType = DataType.STRING;
} else if (attrType.contains("char")) {
attrDataType = DataType.CHAR;
} else if (attrType.contains("int")) {
attrDataType = DataType.INT;
} else if (attrType.contains("float")) {
attrDataType = DataType.FLOAT;
} else if (attrType.contains("date")) {
attrDataType = DataType.DATE;
} else {
attrDataType = null;
}
// Check if the attribute exists on the current table
if (!currentLocalTable.attributeExists(attrName, attrDataType)) {
return false;
}
}
}
}
tablesResultSet.isBeforeFirst();
}
catch (SQLException e) {
e.printStackTrace();
}
return true;
}
private boolean tablesContentsCoincide() {
Table currentLocalTable;
// COMPARING ROWS
for (int tableIndex = 0; tableIndex < localTablesOnDbms.size(); tableIndex++) {
currentLocalTable = localTablesOnDbms.get(tableIndex);
try {
for (int i = 0; i < getDatabase().getNumOfTables(); i++) {
int numOfRows = 0;
Statement st = getDbmsConnection().createStatement();
ResultSet countRS = st.executeQuery("SELECT COUNT(*) FROM " +
currentLocalTable.getName());
countRS.next();
numOfRows = countRS.getInt(1);
// Check matching between number of rows (on DBMS and locally)
if (currentLocalTable.getNumOfRows() != numOfRows) {
return false;
}
// Compare contents
String[][] rowsData = currentLocalTable.getRowsData();
for (int j = 0; j < rowsData.length; j++) {
String query = "SELECT * FROM " + currentLocalTable.getName() + " WHERE ";
for (int k = 0; k < rowsData[j].length; k++) {
query += currentLocalTable.getAttributes().get(k).getName() + "=";
query += rowsData[j][k];
if (k < rowsData[j].length - 1) {
query += " AND ";
}
}
ResultSet rs = st.executeQuery(query);
//System.out.println(query);
if (!rs.next()) {
return false;
}
}
}
}
catch (SQLException e) {
e.printStackTrace();
}
}
return true;
}
private void insertDbmsRowsToLocalTable() throws SQLException {
tablesResultSet.beforeFirst();
// For each table on the DBMS
while (tablesResultSet.next()) {
String remoteTableName = tablesResultSet.getString("TABLE_NAME");
Table localTable = database.getTableByName(remoteTableName);
if (localTable != null) {
// Getting all the rows
Statement st = getDbmsConnection().createStatement();
ResultSet rowsRS = st.executeQuery("SELECT * FROM " +
remoteTableName);
// Insert them locally if they not exist
ArrayList<Attribute> attrs = localTable.getAttributes();
ArrayList<Datum> data; | Row newRow = null; | 4 |
xpush/lib-xpush-android | sample/src/main/java/io/xpush/sampleChat/fragments/ChatFragment.java | [
"public class Constants {\n public static final int REQUEST_SIGNUP = 100;\n\n public static final int REQUEST_EDIT_IMAGE = 111;\n public static final int REQUEST_EDIT_NICKNAME = 112;\n public static final int REQUEST_EDIT_STATUS_MESSAGE = 113;\n\n public static final int REQUEST_INVITE_USER = 201;\n\n public static final int REQUEST_IMAGE_SELECT = 210;\n public static final int REQUEST_IMAGE_CAPTURE = 211;\n\n public static final String CRASH_TEXT = \"oooops ! I crashed, but a report has been sent to my developer to help fix the issue !\";\n public static final MediaType MEDIA_TYPE_PNG = MediaType.parse(\"image/png\");\n}",
"public interface CallbackEvent {\n public void call(Object... args);\n}",
"public class XPushCore {\n\n private static final int NETWORK_WIFI = 1;\n private static final int NETWORK_MOBILE = 2;\n private static final int NETWORK_NOT_AVAILABLE = 0;\n\n private static XPushSession mXpushSession;\n\n private static final String TAG = XPushCore.class.getSimpleName();\n\n public static XPushCore sInstance;\n\n private static String mHostname;\n private static String mAppId;\n private static String mDeviceId;\n private static Context baseContext;\n\n private static Socket mGlobalSocket;\n\n\n private HashMap<String, Emitter.Listener> mEvents;\n\n private static final AtomicBoolean mGlobalSocketConnected = new AtomicBoolean();\n private static final AtomicBoolean mConnecting = new AtomicBoolean();\n\n private static CountDownLatch latch = new CountDownLatch(2);\n\n public static void initialize(Context context){\n if( sInstance == null ){\n sInstance = new XPushCore(context);\n sInstance.init();\n }\n }\n\n public static XPushCore getInstance(){\n\n if( sInstance == null ){\n sInstance = new XPushCore();\n sInstance.init();\n }\n\n return sInstance;\n }\n\n public XPushCore(){\n }\n\n public XPushCore(Context context){\n baseContext = context;\n }\n\n\n private void init(){\n if( getBaseContext() != null ) {\n mXpushSession = restoreXpushSession();\n mHostname = getBaseContext().getString(R.string.host_name);\n mAppId = getBaseContext().getString(R.string.app_id);\n mDeviceId = getBaseContext().getString(R.string.device_id);\n }\n }\n\n public static String getHostname(){\n return mHostname;\n }\n\n public static String getAppId(){\n return mAppId;\n }\n\n public static void setBaseContext(Context context){\n baseContext = context;\n XPushCore.getInstance().init();\n }\n\n public static Context getBaseContext(){\n if( baseContext == null){\n Log.w(TAG, \"!!!!! baseContext is null !!!!!\");\n baseContext = ApplicationController.getInstance();\n }\n return baseContext;\n }\n\n public static void setGlobalSocket(Socket socket){\n mGlobalSocket = socket;\n latch.countDown();\n }\n\n public static void setGlobalSocketConnected(){\n mGlobalSocketConnected.getAndSet(true);\n }\n\n private Socket getClient() {\n\n try {\n if( !mGlobalSocketConnected.get() ) {\n\n // create three threads passing a CountDownLatch\n Thread T1 = new Thread(){\n public void run() {\n Log.d(TAG, \"--- connect --- \");\n connect();\n }\n };\n\n Thread T2 = new Thread(){\n public void run() {\n try {\n Thread.sleep(10);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n latch.countDown();\n }\n };\n\n T1.start();\n T2.start();\n\n try {\n latch.await(6, TimeUnit.SECONDS);\n } catch(InterruptedException ie) {\n ie.printStackTrace();\n }\n }\n } catch (Exception e) {\n // Happens if someone interrupts your thread.\n e.printStackTrace();\n }\n\n if( mGlobalSocket == null ){\n Log.d(TAG, \"null null null\");\n }\n\n return mGlobalSocket;\n }\n\n public static boolean isGlobalConnected(){\n return mGlobalSocketConnected.get();\n }\n\n /**\n *\n * Auth start\n *\n *\n */\n public static void register(String id, String password, String name, final CallbackEvent callbackEvent){\n\n getInstance();\n\n final Map<String,String> params = new HashMap<String, String>();\n\n if( name != null ) {\n\n JSONObject data = new JSONObject();\n try {\n data.put(\"NM\", name);\n } catch (JSONException e) {\n e.printStackTrace();\n }\n params.put(\"DT\", data.toString());\n }\n\n params.put(\"A\", mAppId);\n params.put(\"U\", id);\n params.put(\"PW\", password);\n params.put(\"D\", mDeviceId);\n SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());\n if( null != pref.getString(\"REGISTERED_NOTIFICATION_ID\", null)){\n params.put(\"N\", pref.getString(\"REGISTERED_NOTIFICATION_ID\", null) );\n }\n String url = mHostname+\"/user/register\";\n\n StringRequest request = new StringRequest(url, params,\n new Response.Listener<JSONObject>() {\n @Override\n public void onResponse(JSONObject response) {\n Log.d(TAG, response.toString());\n try {\n if( \"ok\".equalsIgnoreCase(response.getString(\"status\")) ){\n callbackEvent.call();\n } else {\n if( response.has(\"message\") ){\n callbackEvent.call(response.getString(\"status\"), response.getString(\"message\") );\n } else {\n callbackEvent.call(response.getString(\"status\"));\n }\n }\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n },\n new Response.ErrorListener() {\n @Override\n public void onErrorResponse(VolleyError error) {\n error.printStackTrace();\n callbackEvent.call( error.getMessage() );\n }\n }\n );\n\n RequestQueue queue = Volley.newRequestQueue(getBaseContext());\n queue.add(request);\n }\n\n /**\n *\n * Auth start\n *\n *\n */\n public static void login(String id, String password, final CallbackEvent callbackEvent){\n\n getInstance();\n\n final Map<String,String> params = new HashMap<String, String>();\n\n params.put(\"A\", mAppId);\n params.put(\"U\", id);\n params.put(\"PW\", password);\n params.put(\"D\", mDeviceId);\n SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());\n if( null != pref.getString(\"REGISTERED_NOTIFICATION_ID\", null)){\n params.put(\"N\", pref.getString(\"REGISTERED_NOTIFICATION_ID\", null) );\n }\n\n String url = mHostname+\"/auth\";\n\n LoginRequest request = new LoginRequest(getBaseContext(), url, params,\n new Response.Listener<JSONObject>() {\n @Override\n public void onResponse(JSONObject response) {\n try {\n if( \"ok\".equalsIgnoreCase(response.getString(\"status\")) ){\n callbackEvent.call();\n } else {\n if( response.has(\"message\") ){\n callbackEvent.call(response.getString(\"status\"), response.getString(\"message\") );\n } else {\n callbackEvent.call(response.getString(\"status\"));\n }\n }\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n },\n new Response.ErrorListener() {\n @Override\n public void onErrorResponse(VolleyError error) {\n error.printStackTrace();\n callbackEvent.call( \"SERVER-ERROR\", error.getMessage() );\n }\n }\n );\n\n RequestQueue queue = Volley.newRequestQueue(getBaseContext());\n queue.add(request);\n }\n\n /**\n *\n * logout\n *\n *\n */\n public static void logout(){\n getInstance();\n mXpushSession = null;\n XPushService.actionStop(baseContext);\n sInstance = null;\n\n SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());\n SharedPreferences.Editor editor = pref.edit();\n editor.remove(\"XPUSH_SESSION\");\n editor.commit();\n }\n\n /**\n *\n * Add device start\n *\n *\n */\n public static void addDevice(String id, String password, final CallbackEvent callbackEvent){\n\n getInstance();\n\n final Map<String,String> params = new HashMap<String, String>();\n\n params.put(\"A\", mAppId);\n params.put(\"U\", id);\n params.put(\"PW\", password);\n params.put(\"D\", mDeviceId);\n\n String url = mHostname+\"/device/add\";\n\n LoginRequest request = new LoginRequest(getBaseContext(), url, params,\n new Response.Listener<JSONObject>() {\n @Override\n public void onResponse(JSONObject response) {\n try {\n if( \"ok\".equalsIgnoreCase(response.getString(\"status\")) ){\n callbackEvent.call();\n } else {\n if( response.has(\"message\") ){\n callbackEvent.call(response.getString(\"status\"), response.getString(\"message\") );\n } else {\n callbackEvent.call(response.getString(\"status\"));\n }\n }\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n },\n new Response.ErrorListener() {\n @Override\n public void onErrorResponse(VolleyError error) {\n error.printStackTrace();\n callbackEvent.call(\"SERVER-ERROR\", error.getMessage());\n }\n }\n );\n\n RequestQueue queue = Volley.newRequestQueue(getBaseContext());\n queue.add(request);\n }\n\n public static void updateToken(final CallbackEvent callbackEvent){\n updateUser(null, callbackEvent);\n }\n\n public static void updateUser(final JSONObject mJsonUserData, final CallbackEvent callbackEvent){\n if( mXpushSession == null ){\n return;\n }\n\n getInstance();\n\n final Map<String,String> params = new HashMap<String, String>();\n\n params.put(\"A\", mAppId);\n params.put(\"U\", mXpushSession.getId());\n params.put(\"PW\", mXpushSession.getPassword());\n params.put(\"D\", mXpushSession.getDeviceId());\n\n if( mJsonUserData != null ) {\n params.put(\"DT\", mJsonUserData.toString());\n }\n\n SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());\n if( null != pref.getString(\"REGISTERED_NOTIFICATION_ID\", null)){\n params.put(\"N\", pref.getString(\"REGISTERED_NOTIFICATION_ID\", null) );\n }\n\n String url = getBaseContext().getString(R.string.host_name)+\"/user/update\";\n\n StringRequest request = new StringRequest(url, params,\n new Response.Listener<JSONObject>() {\n @Override\n public void onResponse(JSONObject response) {\n Log.d(TAG, \"Update user success ======================\");\n Log.d(TAG, response.toString());\n try {\n if( \"ok\".equalsIgnoreCase(response.getString(\"status\")) ){\n Log.d(TAG, response.getString(\"status\"));\n\n if( mJsonUserData != null ) {\n if (mJsonUserData.has(\"I\")) {\n mXpushSession.setImage(mJsonUserData.getString(\"I\"));\n }\n if (mJsonUserData.has(\"NM\")) {\n mXpushSession.setName(mJsonUserData.getString(\"NM\"));\n }\n if (mJsonUserData.has(\"MG\")) {\n mXpushSession.setMessage(mJsonUserData.getString(\"MG\"));\n }\n }\n\n if( params.containsKey(\"N\")) {\n mXpushSession.setNotiId(params.get(\"N\"));\n }\n\n // SessionData Update\n SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(baseContext);\n SharedPreferences.Editor editor = pref.edit();\n editor.putString(\"XPUSH_SESSION\", mXpushSession.toJSON().toString());\n editor.commit();\n\n if( mJsonUserData != null ) {\n callbackEvent.call(mJsonUserData);\n } else {\n callbackEvent.call(response);\n }\n }\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n },\n new Response.ErrorListener() {\n @Override\n public void onErrorResponse(VolleyError error) {\n Log.d(TAG, \"Update user error ======================\");\n error.printStackTrace();\n }\n }\n );\n\n RequestQueue queue = Volley.newRequestQueue(getBaseContext());\n queue.add(request);\n }\n\n /**\n *\n * Session Start\n *\n */\n public static XPushSession restoreXpushSession(){\n getInstance();\n if( mXpushSession == null ){\n SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());\n final String sessionStr = pref.getString(\"XPUSH_SESSION\", \"\");\n if( !\"\".equals( sessionStr ) ){\n try {\n mXpushSession = new XPushSession( new JSONObject( sessionStr ) );\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n }\n\n return mXpushSession;\n }\n\n public static boolean isLogined(){\n getInstance();\n if( restoreXpushSession() != null ){\n return true;\n } else {\n return false;\n }\n }\n\n public static XPushSession getXpushSession(){\n getInstance();\n if( mXpushSession == null ){\n restoreXpushSession();\n }\n\n return mXpushSession;\n }\n\n /**\n *\n * Channel start\n *\n *\n */\n\n public static void createChannel(final XPushChannel xpushChannel, final CallbackEvent callbackEvent){\n\n JSONArray userArray = new JSONArray();\n for( String userId : xpushChannel.getUsers() ){\n userArray.put(userId);\n }\n final String cid = xpushChannel.getId() != null ? xpushChannel.getId() : XPushUtils.generateChannelId(xpushChannel.getUsers());\n xpushChannel.setId( cid );\n\n JSONObject jsonObject = new JSONObject();\n try {\n jsonObject.put(\"C\", cid);\n jsonObject.put(\"U\", userArray);\n\n } catch (JSONException e) {\n e.printStackTrace();\n }\n\n if ( mGlobalSocket == null || !mGlobalSocket.connected() ){\n Log.d(TAG, \"Not connected\");\n return;\n }\n\n getInstance().getClient().emit(\"channel.create\", jsonObject, new Ack() {\n @Override\n public void call(Object... args) {\n JSONObject response = (JSONObject) args[0];\n\n if (response.has(\"status\")) {\n try {\n Log.d(TAG, response.getString(\"status\"));\n if (\"ok\".equalsIgnoreCase(response.getString(\"status\")) || \"WARN-EXISTED\".equals(response.getString(\"status\"))\n // duplicate\n || (\"ERR-INTERNAL\".equals(response.getString(\"status\"))) && response.get(\"message\").toString().indexOf(\"E11000\") > -1) {\n\n getChannel(cid, callbackEvent);\n }\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n }\n });\n }\n\n\n public static void getChannel(final String channelId, final CallbackEvent callbackEvent){\n getChannel(getBaseContext(), channelId, callbackEvent);\n }\n\n public static void getChannel(Context context, final String channelId, final CallbackEvent callbackEvent){\n getInstance();\n String url = null;\n try {\n url = mHostname + \"/node/\"+ getInstance().getAppId()+\"/\"+ URLEncoder.encode(channelId, \"UTF-8\");\n } catch (UnsupportedEncodingException e) {\n e.printStackTrace();\n }\n\n StringRequest request = new StringRequest(url,\n new Response.Listener<JSONObject>() {\n @Override\n public void onResponse(JSONObject response) {\n try {\n ChannelCore result = null;\n if( \"ok\".equalsIgnoreCase(response.getString(\"status\")) ){\n JSONObject serverInfo = response.getJSONObject(\"result\").getJSONObject(\"server\");\n result = new ChannelCore(channelId, serverInfo.getString(\"url\"), serverInfo.getString(\"name\") );\n }\n\n callbackEvent.call( result );\n } catch (JSONException e) {\n e.printStackTrace();\n callbackEvent.call();\n }\n }\n },\n new Response.ErrorListener() {\n @Override\n public void onErrorResponse(VolleyError error) {\n error.printStackTrace();\n callbackEvent.call(error.getMessage());\n }\n }\n );\n\n RequestQueue queue = Volley.newRequestQueue(context);\n queue.add(request);\n }\n\n public static void storeChannel(XPushChannel channel){\n getInstance();\n ContentValues values = new ContentValues();\n values.put(ChannelTable.KEY_ID, channel.getId());\n values.put(ChannelTable.KEY_NAME, channel.getName());\n values.put(ChannelTable.KEY_IMAGE, channel.getImage());\n values.put(ChannelTable.KEY_MESSAGE, channel.getMessage());\n values.put(ChannelTable.KEY_UPDATED, System.currentTimeMillis());\n\n values.put(XpushContentProvider.SQL_INSERT_OR_REPLACE, true);\n getBaseContext().getContentResolver().insert(XpushContentProvider.CHANNEL_CONTENT_URI, values);\n }\n\n /**\n *\n * Group Start\n *\n */\n public static void getFriends(final CallbackEvent callbackEvent) {\n\n\n JSONObject jsonObject = new JSONObject();\n\n try {\n jsonObject.put(\"GR\", mXpushSession.getId());\n } catch (JSONException e) {\n e.printStackTrace();\n }\n\n try {\n getInstance().getClient().emit(\"group.list\", jsonObject, new Ack() {\n @Override\n public void call(Object... args) {\n JSONObject response = (JSONObject) args[0];\n\n Log.d(TAG, response.toString());\n if (response.has(\"result\")) {\n try {\n JSONArray result = (JSONArray) response.getJSONArray(\"result\");\n callbackEvent.call(result);\n\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n }\n });\n } catch ( Exception ee ){\n ee.printStackTrace();\n }\n }\n\n public static void storeFriends(final Context mContext, final JSONArray result) {\n getInstance();\n try {\n List<ContentValues> valuesToInsert = new ArrayList<ContentValues>();\n\n for (int inx = 0; inx < result.length(); inx++) {\n JSONObject json = (JSONObject) result.get(inx);\n\n ContentValues contentValues = new ContentValues();\n contentValues.put(UserTable.KEY_ID, json.getString(\"U\"));\n\n if (json.has(\"DT\") && !json.isNull(\"DT\")) {\n Object obj = json.get(\"DT\");\n JSONObject data = null;\n if (obj instanceof JSONObject) {\n data = (JSONObject) obj;\n } else if (obj instanceof String) {\n data = new JSONObject((String) obj);\n }\n\n if (data.has(\"NM\")) {\n contentValues.put(UserTable.KEY_NAME, data.getString(\"NM\"));\n }\n if (data.has(\"MG\")) {\n contentValues.put(UserTable.KEY_MESSAGE, data.getString(\"MG\"));\n }\n if (data.has(\"I\")) {\n contentValues.put(UserTable.KEY_IMAGE, data.getString(\"I\"));\n }\n } else {\n contentValues.put(UserTable.KEY_NAME, json.getString(\"U\"));\n }\n\n contentValues.put(XpushContentProvider.SQL_INSERT_OR_REPLACE, true);\n valuesToInsert.add(contentValues);\n }\n\n\n mContext.getContentResolver().bulkInsert(XpushContentProvider.USER_CONTENT_URI, valuesToInsert.toArray(new ContentValues[0]));\n\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n\n public static void addFriend(final Context mContext, final XPushUser user, final CallbackEvent callbackEvent) {\n\n JSONObject jsonObject = new JSONObject();\n JSONArray array = new JSONArray();\n\n try {\n array.put( user.getId() );\n\n jsonObject.put(\"GR\", XPushCore.getXpushSession().getId() );\n jsonObject.put(\"U\", array);\n } catch (JSONException e) {\n e.printStackTrace();\n }\n\n getInstance().getClient().emit(\"group.add\", jsonObject, new Ack() {\n @Override\n public void call(Object... args) {\n JSONObject response = (JSONObject) args[0];\n Log.d(TAG, response.toString());\n try {\n if (\"ok\".equalsIgnoreCase(response.getString(\"status\"))) {\n\n ContentValues contentValues = new ContentValues();\n contentValues.put(UserTable.KEY_ID, user.getId());\n contentValues.put(UserTable.KEY_NAME, user.getName());\n contentValues.put(UserTable.KEY_MESSAGE, user.getMessage());\n contentValues.put(UserTable.KEY_IMAGE, user.getImage());\n\n contentValues.put(XpushContentProvider.SQL_INSERT_OR_REPLACE, true);\n mContext.getContentResolver().insert(XpushContentProvider.USER_CONTENT_URI, contentValues);\n\n callbackEvent.call();\n }\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n });\n }\n\n public static void searchUser(final Context context, String searchKey, final CallbackEvent callbackEvent){\n searchUser(context, searchKey, 1, 50, callbackEvent);\n }\n\n public static void searchUser(final Context context, String searchKey, int pageNum, int pageSize, final CallbackEvent callbackEvent){\n\n getInstance();\n\n JSONObject options = new JSONObject();\n\n try {\n options.put(\"pageNum\", pageNum);\n options.put(\"pageSize\", pageSize);\n } catch (JSONException e) {\n e.printStackTrace();\n }\n\n final Map<String,String> params = new HashMap<String, String>();\n params.put(\"A\", mAppId);\n params.put(\"K\", searchKey);\n params.put(\"option\", options.toString());\n\n String url = mHostname+\"/user/search\";\n\n StringRequest request = new StringRequest(url, params,\n new Response.Listener<JSONObject>() {\n @Override\n public void onResponse(JSONObject response) {\n try {\n Log.d(TAG, \"====== search user response ====== \" + response.toString() );\n if( \"ok\".equalsIgnoreCase(response.getString(\"status\")) ){\n JSONArray result = (JSONArray) response.getJSONObject(\"result\").getJSONArray(\"users\");\n\n ArrayList<XPushUser> users = new ArrayList<XPushUser>();\n\n for (int inx = 0; inx < result.length(); inx++) {\n JSONObject json = (JSONObject) result.get(inx);\n Log.d(TAG, json.toString());\n\n XPushUser xpushUser = new XPushUser();\n\n xpushUser.setId(json.getString(\"U\"));\n\n if (json.has(\"DT\") && !json.isNull(\"DT\")) {\n Object obj = json.get(\"DT\");\n JSONObject data = null;\n if (obj instanceof JSONObject) {\n data = (JSONObject) obj;\n } else if (obj instanceof String) {\n data = new JSONObject((String) obj);\n }\n\n if (data.has(\"NM\")) {\n xpushUser.setName(data.getString(\"NM\"));\n } else {\n xpushUser.setName(json.getString(\"U\"));\n }\n if (data.has(\"MG\")) {\n xpushUser.setMessage(data.getString(\"MG\"));\n }\n if (data.has(\"I\")) {\n xpushUser.setImage(data.getString(\"I\"));\n }\n } else {\n xpushUser.setName(json.getString(\"U\"));\n }\n\n users.add(xpushUser);\n }\n\n callbackEvent.call(users);\n }\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n },\n new Response.ErrorListener() {\n @Override\n public void onErrorResponse(VolleyError error) {\n error.printStackTrace();\n callbackEvent.call(error.getMessage());\n }\n }\n );\n\n RequestQueue queue = Volley.newRequestQueue(context);\n queue.add(request);\n }\n\n public static String[] uploadImage(Uri uri){\n\n getInstance();\n\n String[] results = new String[3];\n\n String downloadUrl = null;\n String url = mXpushSession.getServerUrl()+\"/upload\";\n JSONObject userData = new JSONObject();\n\n try {\n userData.put( \"U\", mXpushSession.getId() );\n userData.put( \"D\", mDeviceId );\n } catch (JSONException e) {\n e.printStackTrace();\n }\n\n String realPath = ContentUtils.getRealPath(getBaseContext(), uri);\n File aFile = new File(realPath);\n\n BitmapFactory.Options options = new BitmapFactory.Options();\n options.inJustDecodeBounds = true;\n BitmapFactory.decodeFile(realPath, options);\n\n int imageWidth = options.outWidth;\n int imageHeight = options.outHeight;\n\n RequestBody requestBody = new MultipartBuilder()\n .type(MultipartBuilder.FORM)\n .addFormDataPart(\"file\", aFile.getName(), RequestBody.create(Constants.MEDIA_TYPE_PNG, aFile)).build();\n\n\n String appId = XPushCore.getAppId();\n\n Request request = new Request.Builder()\n .url(url)\n .addHeader(\"XP-A\", appId )\n .addHeader(\"XP-C\", getXpushSession().getId() +\"^\"+ appId)\n .addHeader(\"XP-U\", userData.toString() )\n .addHeader(\"XP-FU-org\", aFile.getName())\n .addHeader(\"XP-FU-nm\", aFile.getName().substring(0, aFile.getName().lastIndexOf(\".\") ) )\n .addHeader(\"XP-FU-tp\", \"image\")\n .post(requestBody)\n .build();\n\n OkHttpClient client = new OkHttpClient();\n\n com.squareup.okhttp.Response response = null;\n try {\n response = client.newCall(request).execute();\n if (!response.isSuccessful()) {\n throw new IOException(\"Unexpected code \" + response);\n }\n\n JSONObject res = new JSONObject( response.body().string() );\n Log.d(TAG, res.toString() );\n\n if( \"ok\".equals(res.getString(\"status\")) ) {\n JSONObject result = res.getJSONObject(\"result\");\n\n String channel = result.getString(\"channel\");\n String tname = result.getString(\"name\");\n\n downloadUrl = mXpushSession.getServerUrl() + \"/download/\" + appId + \"/\" + channel + \"/\" + mXpushSession.getId() + \"/\" + tname;\n\n Log.d(TAG, downloadUrl );\n }\n\n\n results[0] = downloadUrl;\n results[1] = String.valueOf(imageWidth);\n results[2] = String.valueOf(imageHeight);\n\n } catch (IOException e) {\n e.printStackTrace();\n } catch (JSONException e) {\n e.printStackTrace();\n }\n\n return results;\n }\n\n public synchronized void connect() {\n\n if( getOnlineType() == NETWORK_NOT_AVAILABLE ){\n Log.d(TAG, \"Network is not available\");\n return;\n }\n\n if( mConnecting.get() ){\n Log.d(TAG, \"Tring connect\");\n return;\n }\n\n mConnecting.set(true);\n\n // fetch the device ID from the preferences.\n String appId = getBaseContext().getString(R.string.app_id);\n String url = mXpushSession.getServerUrl() + \"/global\";\n\n IO.Options opts = new IO.Options();\n opts.forceNew = true;\n opts.reconnectionAttempts = 20;\n try {\n opts.query = \"A=\"+appId+\"&U=\"+ URLEncoder.encode(mXpushSession.getId(), \"UTF-8\")+\"&TK=\"+mXpushSession.getToken()+\"&D=\"+mXpushSession.getDeviceId();\n } catch (UnsupportedEncodingException e) {\n e.printStackTrace();\n }\n\n IO.Options mOpts = opts;\n Log.i(TAG, \"Connecting with URL in XPushCore : \" + url);\n try {\n mGlobalSocket = IO.socket(url, mOpts);\n HashMap<String, Emitter.Listener> events = new HashMap<>();\n\n events.put(Socket.EVENT_CONNECT, onConnectSuccess);\n events.put(Socket.EVENT_CONNECT_ERROR, onConnectError);\n events.put(\"_event\", onNewMessage);\n\n if (events != null) {\n for (String eventName : events.keySet()) {\n mGlobalSocket.on(eventName, events.get(eventName));\n }\n }\n\n mEvents = events;\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n mGlobalSocket.connect();\n }\n\n private Emitter.Listener onNewMessage = new Emitter.Listener() {\n @Override\n public void call(final Object... args) {\n JSONObject json = (JSONObject) args[0];\n Log.d(TAG, \"on GlobalMesssage\" );\n XPushService.handleMessage(baseContext, json);\n }\n };\n\n private Emitter.Listener onConnectSuccess = new Emitter.Listener() {\n @Override\n public void call(Object... args) {\n Log.d(TAG, \"connect sucesss\");\n mConnecting.set(false);\n setGlobalSocketConnected();\n }\n };\n\n private Emitter.Listener onConnectError = new Emitter.Listener() {\n @Override\n public void call(Object... args) {\n\n if( args[0] instanceof SocketIOException) {\n SocketIOException e = (SocketIOException) args[0];\n Log.d(TAG, e.getMessage());\n } else if ( args[0] instanceof EngineIOException){\n EngineIOException e = (EngineIOException) args[0];\n Log.d(TAG, e.getMessage());\n }\n mConnecting.set(false);\n }\n };\n\n private int getOnlineType() {\n try {\n ConnectivityManager conMan = (ConnectivityManager) baseContext.getSystemService(Context.CONNECTIVITY_SERVICE);\n\n NetworkInfo.State wifi = conMan.getNetworkInfo(1).getState(); // wifi\n if (wifi == NetworkInfo.State.CONNECTED || wifi == NetworkInfo.State.CONNECTING)\n return NETWORK_WIFI;\n\n NetworkInfo.State mobile = conMan.getNetworkInfo(0).getState();\n if (mobile == NetworkInfo.State.CONNECTED || mobile == NetworkInfo.State.CONNECTING)\n return NETWORK_MOBILE;\n\n } catch (NullPointerException e) {\n return NETWORK_NOT_AVAILABLE;\n }\n\n return NETWORK_NOT_AVAILABLE;\n }\n\n public void disconnect(){\n for (String eventName : mEvents.keySet()) {\n this.off(eventName);\n }\n Log.d(TAG, \"=== disconnect global socket ===\");\n mGlobalSocket.disconnect();\n }\n\n public Socket getGlobalSocket(){\n return mGlobalSocket;\n }\n\n public boolean isConnecting(){\n return mConnecting.get();\n }\n\n public void on(String event, Emitter.Listener eventListener) {\n if( !mEvents.containsKey( event) ){\n mGlobalSocket.on(event, eventListener);\n }\n }\n\n public void off(String event) {\n mGlobalSocket.off(event);\n }\n}",
"public abstract class XPushChatFragment extends Fragment implements LoaderManager.LoaderCallbacks<List<XPushMessage>>{\n\n public static final String TAG = XPushChatFragment.class.getSimpleName();\n protected static final int INIT_VIEW_COUNT = 16;\n\n private int mViewCount;\n\n private RecyclerView mRecyclerView;\n private EditText mInputMessageView;\n protected MessageListAdapter mAdapter;\n private boolean mTyping = false;\n\n private String mUserId;\n private String mUsername;\n\n private XPushChannel mXpushChannel;\n\n protected String mChannel;\n protected Activity mActivity;\n protected ArrayList<String> mUsers = new ArrayList<String>();\n\n private XPushSession mSession;\n\n private SQLiteDatabase mDatabase;\n private XPushMessageDataSource mDataSource;\n private DBHelper mDbHelper;\n\n private List<XPushMessage> mXpushMessages = new ArrayList<XPushMessage>();\n protected ArrayList<XPushUser> mXpushUsers = new ArrayList<XPushUser>();\n\n private MessageDataLoader mDataLoader;\n private RecyclerOnScrollListener mOnScrollListener;\n\n private LinearLayoutManager mLayoutManager;\n\n protected ChannelCore mChannelCore;\n\n public XPushChatFragment() {\n super();\n }\n\n private long lastReceiveTime = 0L;\n\n protected boolean newChannelFlag;\n protected boolean resetChannelFlag;\n protected boolean restartLoader;\n\n private Bundle mChannelBundle;\n\n private Bundle mSavedInstanceState;\n\n\n private AtomicBoolean isPaused = new AtomicBoolean();\n\n @Override\n public void onAttach(Activity activity) {\n super.onAttach(activity);\n mAdapter = new MessageListAdapter(activity, mXpushMessages);\n }\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n mViewCount = INIT_VIEW_COUNT;\n mActivity = getActivity();\n\n mDbHelper = new DBHelper(mActivity);\n mDatabase = mDbHelper.getWritableDatabase();\n mDataSource = new XPushMessageDataSource(mDatabase, getActivity().getString(R.string.message_table_name), getActivity().getString(R.string.user_table_name));\n\n mSession = XPushCore.getXpushSession();\n newChannelFlag = mActivity.getIntent().getBooleanExtra(\"newChannel\", false);\n\n if( savedInstanceState == null ){\n mChannelBundle = mActivity.getIntent().getBundleExtra(XPushChannel.CHANNEL_BUNDLE);\n\n } else {\n mChannelBundle = savedInstanceState.getBundle(XPushChannel.CHANNEL_BUNDLE);\n mViewCount = savedInstanceState.getInt(\"mViewCount\");\n if( mDataLoader == null ){\n\n resetChannelFlag = true;\n restartLoader = true;\n }\n }\n\n mXpushChannel = new XPushChannel(mChannelBundle);\n mChannel = mXpushChannel.getId();\n\n if (null == mXpushChannel.getName()) {\n\n Uri singleUri = Uri.parse(XpushContentProvider.CHANNEL_CONTENT_URI + \"/\" + mChannel);\n Cursor cursor = mActivity.getContentResolver().query(singleUri, ChannelTable.ALL_PROJECTION, null, null, null);\n if (cursor != null && cursor.getCount() > 0) {\n cursor.moveToFirst();\n mXpushChannel = new XPushChannel(cursor);\n newChannelFlag = false;\n }\n }\n\n mUserId = mSession.getId();\n mUsername = mSession.getName();\n setHasOptionsMenu(true);\n\n mActivity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);\n getLoaderManager().initLoader(0, null, this);\n\n mSavedInstanceState = savedInstanceState;\n }\n\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container,\n Bundle savedInstanceState) {\n return inflater.inflate(R.layout.fragment_chat, container, false);\n }\n\n @Override\n public void onResume(){\n super.onResume();\n Log.d(TAG, \" ===== resume ===== \");\n isPaused.set(true);\n\n newChannelFlag = mActivity.getIntent().getBooleanExtra(\"newChannel\", false);\n if( !resetChannelFlag ) {\n resetChannelFlag = mActivity.getIntent().getBooleanExtra(\"resetChannel\", false);\n }\n\n Log.d(TAG, \"resetChannelFlag : \" + resetChannelFlag);\n Log.d(TAG, \"newChannelFlag : \"+newChannelFlag );\n Log.d(TAG, \"restartLoader : \"+restartLoader );\n\n if( resetChannelFlag ) {\n mViewCount = INIT_VIEW_COUNT;\n\n mChannelBundle = mActivity.getIntent().getBundleExtra(XPushChannel.CHANNEL_BUNDLE);\n mXpushChannel = new XPushChannel(mChannelBundle);\n\n mChannel = mXpushChannel.getId();\n mUsers = mXpushChannel.getUsers();\n\n mActivity.getIntent().putExtra(\"resetChannel\", false);\n mXpushMessages.clear();\n\n String selection = MessageTable.KEY_CHANNEL + \"='\" + mChannel +\"'\";\n String sortOrder = MessageTable.KEY_UPDATED + \" DESC LIMIT \" + String.valueOf(mViewCount);\n\n mDataLoader = new MessageDataLoader(mActivity, mDataSource, selection, null, null, null, sortOrder);\n\n if( restartLoader ) {\n mXpushMessages.clear();\n mAdapter.notifyDataSetChanged();\n getLoaderManager().restartLoader(0, null, this);\n getChannelAndConnect();\n } else {\n createChannelAndConnect(mXpushChannel);\n }\n } else if( newChannelFlag ){\n createChannelAndConnect(mXpushChannel);\n } else if( mChannelCore == null || !mChannelCore.connected() ) {\n\n if( mChannelCore != null ) {\n connectChannel();\n } else {\n getChannelAndConnect();\n }\n }\n }\n\n @Override\n public void onPause() {\n super.onPause();\n Log.d(TAG, \" ===== pause ===== \");\n isPaused.set(false);\n }\n\n @Override\n public void onViewCreated(View view, Bundle savedInstanceState) {\n super.onViewCreated(view, savedInstanceState);\n\n mRecyclerView = (RecyclerView) view.findViewById(R.id.messages);\n mLayoutManager = new LinearLayoutManager(getActivity());\n\n mRecyclerView.setLayoutManager(mLayoutManager);\n mRecyclerView.setAdapter(mAdapter);\n\n mInputMessageView = (EditText) view.findViewById(R.id.message_input);\n mInputMessageView.setOnEditorActionListener(new TextView.OnEditorActionListener() {\n @Override\n public boolean onEditorAction(TextView v, int id, KeyEvent event) {\n if (id == R.id.send || id == EditorInfo.IME_NULL) {\n attemptSend();\n return true;\n }\n return false;\n }\n });\n\n mInputMessageView.addTextChangedListener(new TextWatcher() {\n @Override\n public void beforeTextChanged(CharSequence s, int start, int count, int after) {\n }\n\n @Override\n public void onTextChanged(CharSequence s, int start, int before, int count) {\n if (null == mUsername) return;\n if (mChannelCore == null || !mChannelCore.connected()) return;\n\n if (!mTyping) {\n mTyping = true;\n }\n }\n\n @Override\n public void afterTextChanged(Editable s) {\n }\n });\n\n mRecyclerView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {\n @Override\n public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {\n if (mInputMessageView.hasFocus() && oldBottom > bottom) {\n mRecyclerView.scrollBy(0, oldBottom - bottom);\n }\n }\n });\n\n Button sendButton = (Button) view.findViewById(R.id.send_button);\n sendButton.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n attemptSend();\n }\n });\n }\n\n @Override\n public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {\n inflater.inflate(R.menu.menu_chat, menu);\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n int id = item.getItemId();\n\n if (id == R.id.action_leave) {\n\n AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);\n builder.setTitle( mActivity.getString(R.string.action_leave_dialog_title))\n .setMessage( mActivity.getString(R.string.action_leave_dialog_description))\n .setCancelable(false)\n .setPositiveButton(\"OK\", new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int whichButton) {\n channelLeave();\n }\n })\n .setNegativeButton(\"Cancel\", new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int whichButton) {\n dialog.cancel();\n }\n\n });\n\n AlertDialog dialog = builder.create(); // 알림창 객체 생성\n dialog.show(); // 알림창 띄우기\n\n return true;\n }\n\n return super.onOptionsItemSelected(item);\n }\n\n\n private void refreshContent(){\n\n new Handler().postDelayed(new Runnable() {\n @Override\n public void run() {\n XPushMessage message = mXpushMessages.get(0);\n\n mViewCount = mViewCount * 2;\n String selection = MessageTable.KEY_CHANNEL + \"='\" + mChannel + \"' and \" + MessageTable.KEY_UPDATED + \" < \" + message.getUpdated();\n String sortOrder = MessageTable.KEY_UPDATED + \" DESC LIMIT \" + mViewCount;\n\n mDataLoader.setSelection(selection);\n mDataLoader.setSortOrder(sortOrder);\n\n List<XPushMessage> messages = mDataLoader.loadInBackground();\n mDataLoader.deliverResult(messages);\n }\n }, 1);\n }\n\n private void connectChannel() {\n\n HashMap<String, Emitter.Listener> events = new HashMap<>();\n\n events.put(Socket.EVENT_CONNECT_ERROR, onConnectError);\n events.put(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);\n events.put(Socket.EVENT_CONNECT, onConnectSuccess);\n events.put(\"message\", onMessage);\n\n mChannelCore.connect(events);\n }\n\n private void addMessage(XPushMessage xpushMessage) {\n mXpushMessages.add(xpushMessage);\n mAdapter.notifyItemInserted(mXpushMessages.size() - 1);\n scrollToBottom();\n }\n\n private void attemptSend() {\n if (null == mUserId) return;\n if (mChannelCore == null || !mChannelCore.connected()) return;\n\n mTyping = false;\n\n String message = mInputMessageView.getText().toString().trim();\n if (TextUtils.isEmpty(message)) {\n mInputMessageView.requestFocus();\n return;\n }\n\n mInputMessageView.setText(\"\");\n mChannelCore.sendMessage(message);\n }\n\n private void leave() {\n\n mUsername = null;\n mChannelCore.disconnect();\n\n Uri channelUri = Uri.parse(XpushContentProvider.CHANNEL_CONTENT_URI + \"/\" + mChannel );\n mActivity.getContentResolver().delete(channelUri, null, null);\n\n Uri messageUri = Uri.parse(XpushContentProvider.MESSAGE_CONTENT_URI + \"/\" + mChannel );\n mActivity.getContentResolver().delete(messageUri, null, null);\n\n Handler handler = new Handler(Looper.getMainLooper());\n handler.postDelayed(new Runnable() {\n @Override\n public void run() {\n mActivity.finish();\n }\n }, 150);\n }\n\n private Emitter.Listener onConnectSuccess = new Emitter.Listener() {\n @Override\n\n public void call(Object... args) {\n ContentValues values = new ContentValues();\n values.put(ChannelTable.KEY_ID, mChannel );\n values.put(ChannelTable.KEY_COUNT, 0);\n\n // Reset Unread Message Count\n Uri singleUri = Uri.parse(XpushContentProvider.CHANNEL_CONTENT_URI + \"/\" + mChannel );\n mActivity.getContentResolver().update(singleUri, values, null, null);\n\n // Reset Badge\n Intent intent = new Intent(mActivity,BadgeIntentService.class);\n mActivity.startService(intent);\n\n mChannelCore.channelGet(new CallbackEvent() {\n @Override\n public void call(Object... args) {\n if( args != null && args.length > 0 && args[0] != null) {\n JSONObject response = (JSONObject) args[0];\n\n if( response.has(\"result\") ){\n try {\n JSONArray dts = response.getJSONObject(\"result\").getJSONArray(\"UDTS\");\n\n mXpushUsers.clear();\n mUsers.clear();\n for( int inx = 0 ; inx < dts.length() ; inx++ ){\n XPushUser tmpUser = new XPushUser(dts.getJSONObject(inx));\n mXpushUsers.add(new XPushUser(dts.getJSONObject(inx)));\n mUsers.add( tmpUser.getId() );\n }\n\n sendInviteMessage();\n\n } catch (Exception e ){\n e.printStackTrace();\n }\n }\n }\n }\n });\n }\n };\n\n private void sendInviteMessage(){\n\n if( (newChannelFlag || resetChannelFlag ) && ( mXpushUsers != null && mXpushUsers.size() > 2 ) ){\n\n if( mSavedInstanceState == null || ( mSavedInstanceState != null && !mSavedInstanceState.getBoolean(\"invitedSuccess\", false) ) ) {\n\n Handler handler = new Handler(Looper.getMainLooper());\n handler.postDelayed(new Runnable() {\n @Override\n public void run() {\n String message = mUsername + \" Invite \" + mXpushChannel.getName();\n mXpushChannel.getUserNames().add(XPushCore.getXpushSession().getName());\n mChannelCore.sendMessage(message, \"IN\", mUsers);\n }\n }, 150);\n\n if( !newChannelFlag ) {\n mActivity.getIntent().putExtra(\"resetChannel\", false);\n resetChannelFlag = false;\n }\n }\n\n }\n }\n\n private Emitter.Listener onConnectError = new Emitter.Listener() {\n @Override\n public void call(Object... args) {\n\n Log.d(TAG, \"error\");\n\n if( args[0] instanceof SocketIOException) {\n SocketIOException e = (SocketIOException) args[0];\n Log.d(TAG, e.getMessage());\n } else if ( args[0] instanceof EngineIOException){\n EngineIOException e = (EngineIOException) args[0];\n Log.d(TAG, e.getMessage());\n }\n\n mActivity.runOnUiThread(new Runnable() {\n @Override\n public void run() {\n Toast.makeText(mActivity, R.string.error_connect, Toast.LENGTH_LONG).show();\n }\n });\n }\n };\n\n private Emitter.Listener onMessage = new Emitter.Listener() {\n @Override\n public void call(final Object... args) {\n JSONObject data = (JSONObject) args[0];\n saveMessage(data);\n }\n };\n\n private void disconnect(){\n if( mChannelCore != null && mChannelCore.connected() ) {\n mChannelCore.disconnect();\n }\n }\n\n @Override\n public Loader<List<XPushMessage>> onCreateLoader(int id, Bundle args) {\n\n String selection = MessageTable.KEY_CHANNEL + \"='\" + mChannel +\"'\";\n String sortOrder = MessageTable.KEY_UPDATED + \" DESC LIMIT \" + String.valueOf(mViewCount);\n\n mDataLoader = new MessageDataLoader(mActivity, mDataSource, selection, null, null, null, sortOrder);\n return mDataLoader;\n }\n\n @Override\n public void onLoadFinished(Loader<List<XPushMessage>> loader, List<XPushMessage> data) {\n\n boolean onStarting = false;\n if( mXpushMessages.size() == 0 ){\n onStarting = true;\n }\n\n Collections.sort(data, new TimestampAscCompare());\n\n\n if( mXpushMessages.size() == 0 ) {\n mXpushMessages.addAll(0, data);\n } else {\n\n // Prevent dulplicate\n if( mXpushMessages.size() > 0 && data.size() > 0 && mXpushMessages.get(0).getUpdated() != data.get(0).getUpdated() ){\n mXpushMessages.addAll(0, data);\n }\n }\n\n mAdapter.notifyDataSetChanged();\n\n if( onStarting ) {\n mOnScrollListener = new RecyclerOnScrollListener(mLayoutManager, RecyclerOnScrollListener.RecylclerDirection.UP) {\n @Override\n public void onLoadMore(int current_page) {\n Log.d(TAG, \" onLoadMore : \"+ current_page);\n refreshContent();\n }\n };\n\n scrollToBottom();\n mRecyclerView.addOnScrollListener(mOnScrollListener);\n\n } else {\n mRecyclerView.scrollToPosition(mXpushMessages.size() - data.size() + 1);\n }\n }\n\n @Override\n public void onLoaderReset(Loader<List<XPushMessage>> loader) {\n mXpushMessages.clear();\n mAdapter.notifyDataSetChanged();\n }\n\n @Override\n public void onDestroy() {\n\n if( mChannelCore != null && mChannelCore.connected() ) {\n disconnect();\n }\n\n super.onDestroy();\n mDbHelper.close();\n mDatabase.close();\n mDataSource = null;\n mDbHelper = null;\n mDatabase = null;\n }\n\n private void scrollToBottom() {\n mRecyclerView.scrollToPosition(mAdapter.getItemCount() - 1);\n }\n\n static class TimestampAscCompare implements Comparator<XPushMessage> {\n public int compare(XPushMessage arg0, XPushMessage arg1) {\n return arg0.getUpdated() < arg1.getUpdated() ? -1 : arg0.getUpdated() > arg1.getUpdated() ? 1:0;\n }\n }\n\n private void saveMessage( JSONObject data ){\n\n Log.d(TAG, \"onMessage : \" + data.toString());\n final XPushMessage xpushMessage = new XPushMessage( data );\n\n try {\n ContentValues values = new ContentValues();\n\n if (xpushMessage.getType() == XPushMessage.TYPE_INVITE) {\n xpushMessage.setType(XPushMessage.TYPE_INVITE);\n values.put(ChannelTable.KEY_USERS, TextUtils.join(\"@!@\", xpushMessage.getUsers()));\n\n if( newChannelFlag ) {\n values.put(ChannelTable.KEY_NAME, mXpushChannel.getName());\n }\n } else if ( xpushMessage.getType() == XPushMessage.TYPE_LEAVE){\n xpushMessage.setType(XPushMessage.TYPE_LEAVE);\n } else {\n if (mSession.getId().equals(xpushMessage.getSenderId())) {\n if( xpushMessage.getType() == XPushMessage.TYPE_IMAGE ) {\n xpushMessage.setType(XPushMessage.TYPE_SEND_IMAGE);\n } else {\n xpushMessage.setType(XPushMessage.TYPE_SEND_MESSAGE);\n }\n } else {\n if( xpushMessage.getType() == XPushMessage.TYPE_IMAGE ) {\n xpushMessage.setType(XPushMessage.TYPE_RECEIVE_IMAGE);\n } else {\n xpushMessage.setType(XPushMessage.TYPE_RECEIVE_MESSAGE);\n }\n }\n }\n\n if( mUsers != null && mUsers.size() > 2 ) {\n values.put(ChannelTable.KEY_NAME, mXpushChannel.getName());\n } else {\n if (XPushMessage.TYPE_SEND_MESSAGE == xpushMessage.getType() || XPushMessage.TYPE_SEND_IMAGE == xpushMessage.getType() ) {\n values.put(ChannelTable.KEY_NAME, mXpushChannel.getName());\n values.put(ChannelTable.KEY_IMAGE, mXpushChannel.getImage());\n } else if (XPushMessage.TYPE_RECEIVE_MESSAGE == xpushMessage.getType() || XPushMessage.TYPE_RECEIVE_IMAGE == xpushMessage.getType() ) {\n values.put(ChannelTable.KEY_NAME, xpushMessage.getSenderName());\n values.put(ChannelTable.KEY_IMAGE, xpushMessage.getImage());\n }\n }\n\n values.put(ChannelTable.KEY_ID, xpushMessage.getChannel());\n values.put(ChannelTable.KEY_MESSAGE, xpushMessage.getMessage());\n values.put(ChannelTable.KEY_MESSAGE_TYPE, xpushMessage.getType());\n values.put(ChannelTable.KEY_UPDATED, xpushMessage.getUpdated());\n\n PowerManager pm = (PowerManager) mActivity.getSystemService(Context.POWER_SERVICE);\n boolean isScreenOn = false;\n if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT_WATCH) {\n isScreenOn = pm.isInteractive();\n } else {\n isScreenOn = pm.isScreenOn();\n }\n\n // Update channel count\n if( !isScreenOn || !isPaused.get() ) {\n\n Uri singleUri = Uri.parse(XpushContentProvider.CHANNEL_CONTENT_URI + \"/\" + xpushMessage.getChannel());\n Cursor cursor = mActivity.getContentResolver().query(singleUri, ChannelTable.ALL_PROJECTION, null, null, null);\n if (cursor != null && cursor.getCount() > 0) {\n cursor.moveToFirst();\n int count = cursor.getInt(cursor.getColumnIndexOrThrow(ChannelTable.KEY_COUNT));\n values.put(ChannelTable.KEY_COUNT, count + 1);\n } else {\n values.put(ChannelTable.KEY_COUNT, 1);\n }\n\n } else {\n values.put(ChannelTable.KEY_COUNT, 0);\n }\n\n values.put(XpushContentProvider.SQL_INSERT_OR_REPLACE, true);\n mActivity.getContentResolver().insert(XpushContentProvider.CHANNEL_CONTENT_URI, values);\n\n // INSERT INTO MESSAGE TABLE\n lastReceiveTime = xpushMessage.getUpdated();\n mDataSource.insert(xpushMessage);\n\n newChannelFlag = false;\n\n mActivity.runOnUiThread(new Runnable() {\n @Override\n public void run() {\n addMessage(xpushMessage);\n }\n });\n\n if( !isScreenOn || !isPaused.get() ) {\n Intent broadcastIntent = new Intent(mActivity, PushMsgReceiver.class);\n broadcastIntent.setAction(\"io.xpush.chat.MGRECVD\");\n\n broadcastIntent.putExtra(\"rcvd.C\", xpushMessage.getChannel());\n broadcastIntent.putExtra(\"rcvd.NM\", xpushMessage.getSenderName());\n broadcastIntent.putExtra(\"rcvd.MG\", xpushMessage.getMessage());\n broadcastIntent.putExtra(\"rcvd.TP\", xpushMessage.getType() );\n\n mActivity.sendBroadcast(broadcastIntent);\n }\n\n } catch (Exception e ){\n e.printStackTrace();\n }\n }\n\n private void createChannelAndConnect(XPushChannel xpushChannel){\n XPushCore.createChannel(xpushChannel, new CallbackEvent() {\n @Override\n public void call(Object... args) {\n if (args[0] != null) {\n mChannelCore = (ChannelCore) args[0];\n\n // newChannelFlag 를 false로\n mActivity.getIntent().putExtra(\"newChannel\", false);\n connectChannel();\n }\n }\n });\n }\n\n private void getChannelAndConnect(){\n\n XPushCore.getChannel(mActivity, mChannel, new CallbackEvent() {\n @Override\n public void call(Object... args) {\n if (args[0] != null) {\n mChannelCore = (ChannelCore) args[0];\n connectChannel();\n }\n }\n });\n }\n\n //add unread message\n private void messageUnread(){\n mChannelCore.getMessageUnread(lastReceiveTime, new CallbackEvent() {\n @Override\n public void call(Object... args) {\n if (args != null && args.length > 0 && args[0] != null) {\n JSONArray messages = (JSONArray) args[0];\n try {\n for (int inx = 0; inx < messages.length(); inx++) {\n saveMessage(messages.getJSONObject(inx));\n }\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n }\n });\n }\n\n protected void channelLeave(){\n\n // 1:1 Channel, only delete local data\n if( mUsers != null && mUsers.size() > 2 ){\n mChannelCore.channelLeave(new CallbackEvent() {\n @Override\n public void call(Object... args) {\n\n // SEND leave message\n mChannelCore.sendMessage(mUsername + \" leave this chat room\", \"OUT\");\n Handler handler = new Handler(Looper.getMainLooper());\n handler.postDelayed(new Runnable() {\n @Override\n public void run() {\n leave();\n }\n }, 150);\n }\n });\n } else {\n leave();\n }\n }\n\n protected ArrayList<String> getImageList(){\n String selection = MessageTable.KEY_CHANNEL + \"='\" + mChannel + \"' and \" + \"a.\"+MessageTable.KEY_TYPE + \" IN (\"+XPushMessage.TYPE_RECEIVE_IMAGE+\",\"+XPushMessage.TYPE_SEND_IMAGE+\" ) \";\n String sortOrder = MessageTable.KEY_UPDATED;\n\n ArrayList<String> images = new ArrayList<String>();\n List<XPushMessage> messages = mDataSource.read(selection, null, null, null, sortOrder);\n for( XPushMessage message : messages ){\n images.add( message.getMessage() );\n }\n return images;\n }\n\n\n @Override\n public void onSaveInstanceState(Bundle savedState) {\n super.onSaveInstanceState(savedState);\n\n savedState.putInt(\"mViewCount\", mViewCount);\n savedState.putBundle(XPushChannel.CHANNEL_BUNDLE, mChannelBundle);\n }\n}",
"public class XPushMessage {\n\n public static final int TYPE_SEND_MESSAGE = 0;\n public static final int TYPE_RECEIVE_MESSAGE = 1;\n\n public static final int TYPE_INVITE = 2;\n public static final int TYPE_LEAVE = 3;\n\n public static final int TYPE_IMAGE = 4;\n public static final int TYPE_SEND_IMAGE = 5;\n public static final int TYPE_RECEIVE_IMAGE = 6;\n\n private String rowId;\n private String id;\n private String channel;\n private String senderId;\n private String senderName;\n private String image;\n private String count;\n private String message;\n private int type;\n private JSONObject metadata;\n private long updated;\n private ArrayList<String> users;\n\n public String getRowId() {\n return rowId;\n }\n\n public void setRowId(String rowId) {\n this.rowId = rowId;\n }\n\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n public String getChannel() {\n return channel;\n }\n\n public void setChannel(String channel) {\n this.channel = channel;\n }\n\n public String getSenderId() {\n return senderId;\n }\n\n public void setSenderId(String senderId) {\n this.senderId = senderId;\n }\n\n public String getSenderName() {\n return senderName;\n }\n\n public void setSenderName(String senderName) {\n this.senderName = senderName;\n }\n\n public String getImage() {\n return image;\n }\n\n public void setImage(String image) {\n this.image = image;\n }\n\n public String getCount() {\n return count;\n }\n\n public void setCount(String count) {\n this.count = count;\n }\n\n public String getMessage() {\n return message;\n }\n\n public void setMessage(String message) {\n this.message = message;\n }\n\n public int getType() {\n return type;\n }\n\n public void setType(int type) {\n this.type = type;\n }\n\n public long getUpdated() {\n return updated;\n }\n\n public void setUpdated(long updated) {\n this.updated = updated;\n }\n\n public ArrayList<String> getUsers(){\n return this.users;\n }\n\n public void setUsers(ArrayList<String> users){\n this.users = users;\n }\n\n public JSONObject getMetadata() {\n return metadata;\n }\n\n public void setMetadata(JSONObject metadata) {\n this.metadata = metadata;\n }\n\n public XPushMessage(){\n }\n\n public XPushMessage(JSONObject data) {\n\n JSONObject uo = null;\n try {\n if( data.has(\"UO\") ) {\n uo = data.getJSONObject(\"UO\");\n\n if( uo.has(\"U\") ){\n this.senderId = uo.getString(\"U\");\n }\n\n if( uo.has(\"NM\") ){\n this.senderName = uo.getString(\"NM\");\n }\n\n if( uo.has(\"I\") ) {\n this.image = uo.getString(\"I\");\n }\n }\n\n // Message Type\n if( data.has(\"TP\") ){\n if( \"IN\".equals(data.getString(\"TP\")) ) {\n this.type = TYPE_INVITE;\n } else if( \"OUT\".equals(data.getString(\"TP\")) ) {\n this.type = TYPE_LEAVE;\n } else if( \"IM\".equals(data.getString(\"TP\")) ) {\n this.type = TYPE_IMAGE;\n }\n }\n\n // Message Metadata\n if( data.has(\"MD\") ){\n this.metadata = data.getJSONObject(\"MD\");\n }\n\n this.channel = data.getString(\"C\");\n\n if( data.has(\"US\") ){\n String usersStr = data.getString(\"US\");\n this.users = new ArrayList<String>(Arrays.asList(usersStr.split(\"@!@\")));\n } else if( this.channel != null && this.channel.indexOf(\"@!@\") > -1 && this.channel.lastIndexOf(\"^\") > 0 ){\n String usersStr = this.channel.substring( 0, this.channel.lastIndexOf(\"^\") );\n this.users = new ArrayList<String>(Arrays.asList(usersStr.split(\"@!@\")));\n }\n\n this.message = URLDecoder.decode( data.getString(\"MG\"), \"UTF-8\");\n this.updated = data.getLong(\"TS\");\n\n this.id = channel +\"_\" + updated;\n\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n public XPushMessage(Cursor cursor){\n this.rowId= cursor.getString(cursor.getColumnIndexOrThrow(MessageTable.KEY_MESSAGE));\n this.id= cursor.getString(cursor.getColumnIndexOrThrow(MessageTable.KEY_ID));\n this.senderName= cursor.getString(cursor.getColumnIndexOrThrow(MessageTable.KEY_SENDER));\n this.image= cursor.getString(cursor.getColumnIndexOrThrow(MessageTable.KEY_IMAGE));\n this.message= cursor.getString(cursor.getColumnIndexOrThrow(MessageTable.KEY_MESSAGE));\n this.type= cursor.getInt(cursor.getColumnIndexOrThrow(MessageTable.KEY_TYPE));\n this.updated= cursor.getLong(cursor.getColumnIndexOrThrow(MessageTable.KEY_UPDATED));\n\n String metadata = cursor.getString(cursor.getColumnIndexOrThrow(MessageTable.KEY_METADATA));\n if( metadata != null ){\n try {\n this.metadata = new JSONObject(metadata);\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n }\n\n @Override\n public String toString(){\n return \"XPushMessage{\" +\n \"rowId='\" + rowId + '\\'' +\n \", id='\" + id + '\\'' +\n \", senderId='\" + senderId + '\\'' +\n \", image='\" + image + '\\'' +\n \", message='\" + message + '\\'' +\n \", type='\" + type + '\\'' +\n \", updated='\" + updated + '\\'' +\n '}';\n }\n}",
"public class ContentUtils {\n\n private static final String[] sArrays = {\"png\",\"jpg\",\"jpeg\",\"bmp\",\"gif\"};\n private static final ArrayList<String> imageExtList = new ArrayList<String>(Arrays.asList(sArrays));\n\n @SuppressLint(\"NewApi\")\n public static String getRealPathFromURI_API19(Context context, Uri uri){\n String filePath = \"\";\n String wholeID = DocumentsContract.getDocumentId(uri);\n\n String id = \";\";\n // Split at colon, use second item in the array\n if( wholeID.indexOf( \":\" ) > 0 ) {\n id = wholeID.split(\":\")[1];\n }\n\n String[] column = { MediaStore.Images.Media.DATA };\n\n // where id is equal to\n String sel = MediaStore.Images.Media._ID + \"=?\";\n\n Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,\n column, sel, new String[]{ id }, null);\n\n int columnIndex = cursor.getColumnIndex(column[0]);\n\n if (cursor.moveToFirst()) {\n filePath = cursor.getString(columnIndex);\n }\n cursor.close();\n return filePath;\n }\n\n\n @SuppressLint(\"NewApi\")\n public static String getRealPathFromURI_API11to18(Context context, Uri contentUri) {\n String[] proj = { MediaStore.Images.Media.DATA };\n String result = null;\n\n if (Looper.myLooper() == null) {\n Looper.prepare();\n }\n\n CursorLoader cursorLoader = new CursorLoader(\n context,\n contentUri, proj, null, null, null);\n Cursor cursor = cursorLoader.loadInBackground();\n\n if(cursor != null){\n int column_index =\n cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);\n cursor.moveToFirst();\n result = cursor.getString(column_index);\n }\n return result;\n }\n\n public static String getRealPathFromURI_BelowAPI11(Context context, Uri contentUri){\n\n if (Looper.myLooper() == null) {\n Looper.prepare();\n }\n\n String[] proj = { MediaStore.Images.Media.DATA };\n Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);\n int column_index\n = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);\n cursor.moveToFirst();\n return cursor.getString(column_index);\n }\n\n public static String getRealPath(Context context, Uri uri){\n String realPath = null;\n\n if( uri.toString().startsWith(\"file:\")){\n realPath = uri.toString().replace(\"file:\", \"\");\n } else {\n\n // SDK < API11\n if (Build.VERSION.SDK_INT < 11) {\n realPath = ContentUtils.getRealPathFromURI_BelowAPI11(context, uri);\n // SDK >= 11 && SDK < 19\n } else if (Build.VERSION.SDK_INT < 19) {\n realPath = ContentUtils.getRealPathFromURI_API11to18(context, uri);\n // SDK > 19 (Android 4.4)\n } else {\n if (uri.toString().indexOf(\"documents\") > 0) {\n realPath = ContentUtils.getRealPathFromURI_API19(context, uri);\n } else {\n realPath = ContentUtils.getRealPathFromURI_API11to18(context, uri);\n }\n }\n }\n\n return realPath;\n }\n\n\n public static boolean isImagePath(String path){\n\n boolean result = false;\n if( path.indexOf(\".\") > -1 ) {\n String ext = path.substring(path.lastIndexOf(\".\") + 1);\n if (imageExtList.indexOf(ext) > -1) {\n result = true;\n }\n }\n return result;\n }\n\n public static int[] getActualImageSize(int originalWidth , int originalHeight, Context context ){\n int[] results = new int[2];\n\n double ratio = (double) originalWidth / (double) originalHeight;\n\n double w = 0;\n double h = 0;\n\n boolean isMaxWidth = false;\n int maxWidth = 240;\n if( maxWidth > originalWidth ) {\n w = originalWidth;\n } else {\n isMaxWidth = true;\n w = maxWidth;\n }\n\n boolean isMaxHeight = false;\n int maxHeight = 240;\n if( maxHeight > originalHeight ){\n h = originalHeight;\n } else {\n isMaxHeight = true;\n h = maxHeight;\n }\n\n if( isMaxWidth && isMaxHeight ){\n if( originalWidth > originalHeight ){\n h = w / ratio;\n } else {\n w = h * ratio;\n }\n } else if( isMaxWidth ){\n h = w / ratio;\n } else if ( isMaxHeight ){\n w = h * ratio;\n }\n\n int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (int) w, context.getResources().getDisplayMetrics());\n int height = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (int)h, context.getResources().getDisplayMetrics());\n\n results[0] = width;\n results[1] = height;\n\n return results;\n }\n\n public static String getInputStringLength(String paramString, int paramInt){\n if (paramString == null) {\n return null;\n }\n return String.format(Locale.US, \"%1$d/%2$d\", new Object[] { Integer.valueOf(paramString.length()), Integer.valueOf(paramInt) });\n }\n}",
"public class MessageListAdapter extends RecyclerView.Adapter<MessageListAdapter.ViewHolder> {\n\n private List<XPushMessage> mXPushMessages;\n private static MessageClickListener mMessageClickListener;\n private Context mContext;\n\n public MessageListAdapter(Context context, List<XPushMessage> xpushMessages) {\n mContext = context;\n mXPushMessages = xpushMessages;\n }\n\n @Override\n public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\n int layout = -1;\n if (viewType == XPushMessage.TYPE_SEND_MESSAGE ) {\n layout = R.layout.item_send_message;\n } else if (viewType == XPushMessage.TYPE_RECEIVE_MESSAGE ) {\n layout = R.layout.item_receive_message;\n } else if (viewType == XPushMessage.TYPE_INVITE || viewType == XPushMessage.TYPE_LEAVE ) {\n layout = R.layout.item_invite_message;\n } else if (viewType == XPushMessage.TYPE_SEND_IMAGE ) {\n layout = R.layout.item_send_image;\n } else if (viewType == XPushMessage.TYPE_RECEIVE_IMAGE ) {\n layout = R.layout.item_receive_image;\n }\n\n View v = LayoutInflater.from(parent.getContext()).inflate(layout, parent, false);\n return new ViewHolder(v);\n }\n\n @Override\n public void onBindViewHolder(ViewHolder viewHolder, int position) {\n XPushMessage xpushMessage = mXPushMessages.get(position);\n\n viewHolder.setUsername(xpushMessage.getSenderName());\n viewHolder.setTime(xpushMessage.getUpdated());\n viewHolder.setImage(xpushMessage.getImage());\n viewHolder.setMessage(xpushMessage.getMessage(), xpushMessage.getType(), xpushMessage.getMetadata());\n }\n\n @Override\n public int getItemCount() {\n return mXPushMessages.size();\n }\n\n @Override\n public int getItemViewType(int position) {\n return mXPushMessages.get(position).getType();\n }\n\n public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {\n private TextView tvUser;\n\n private TextView tvTime;\n private SimpleDraweeView thumbNail;\n private View vMessage;\n private View vClickableView;\n\n private ViewHolder(View itemView) {\n super(itemView);\n\n tvTime = (TextView) itemView.findViewById(R.id.tvTime);\n tvUser = (TextView) itemView.findViewById(R.id.tvUser);\n thumbNail = (SimpleDraweeView) itemView.findViewById(R.id.thumbnail);\n vMessage = (View) itemView.findViewById(R.id.vMessage);\n vClickableView = (View)itemView.findViewById(R.id.bubble);\n vClickableView.setOnClickListener(this);\n vClickableView.setOnLongClickListener(this);\n }\n\n @Override\n public void onClick(View view) {\n int position = ViewHolder.super.getAdapterPosition();\n mMessageClickListener.onMessageClick(mXPushMessages.get(position).getMessage(), mXPushMessages.get(position).getType());\n }\n\n @Override\n public boolean onLongClick(View view) {\n int position = ViewHolder.super.getAdapterPosition();\n mMessageClickListener.onMessageLongClick(mXPushMessages.get(position).getMessage(), mXPushMessages.get(position).getType());\n return true;\n }\n\n public void setUsername(String username) {\n if (null == tvUser) return;\n tvUser.setText(username);\n }\n\n public void setMessage(String message, int type, final JSONObject metatdata) {\n\n if (null == vMessage) return;\n if( type == XPushMessage.TYPE_SEND_IMAGE || type == XPushMessage.TYPE_RECEIVE_IMAGE ) {\n\n\n final ImageView imageView = ((ImageView) vMessage);\n if( metatdata != null ){\n try {\n int metaWidth = metatdata.getInt(\"W\");\n int metaHeight = metatdata.getInt(\"H\");\n\n if( metaWidth > 0 && metaHeight > 0 ) {\n int results[] = ContentUtils.getActualImageSize(metaWidth, metaHeight, mContext);\n LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(results[0], results[1]);\n imageView.setLayoutParams(layoutParams);\n }\n } catch ( JSONException e ){\n e.printStackTrace();\n }\n }\n\n Glide.with(mContext)\n .load(Uri.parse(message))\n .asBitmap()\n .diskCacheStrategy(DiskCacheStrategy.ALL)\n .fitCenter()\n .into(new SimpleTarget<Bitmap>() {\n @Override\n public void onResourceReady(Bitmap bitmap, GlideAnimation anim) {\n int originalWidth = bitmap.getWidth();\n int originalHeight = bitmap.getHeight();\n\n if( metatdata == null ) {\n //int results[] = ContentUtils.getActualImageSize(originalWidth, originalHeight, mContext);\n //LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(results[0], results[1]);\n //imageView.setLayoutParams(layoutParams);\n }\n imageView.setImageBitmap(bitmap);\n }\n });\n } else {\n ( (TextView) vMessage ).setText(message);\n }\n }\n\n public void setTime(long timestamp) {\n if (null == tvTime) return;\n tvTime.setText(DateUtils.getDate(timestamp, \"a h:mm\"));\n }\n\n public void setImage(String image) {\n if (null == image || null == thumbNail) return;\n thumbNail.setImageURI(Uri.parse(image));\n }\n }\n\n public void setOnItemClickListener(MessageClickListener clickListener) {\n MessageListAdapter.mMessageClickListener = clickListener;\n }\n\n public interface MessageClickListener {\n public void onMessageClick(String message, int type);\n\n public void onMessageLongClick(String message, int type);\n }\n}",
"public class ImageViewerActivity extends AppCompatActivity {\n\n private static final String TAG = ImageViewerActivity.class.getSimpleName();\n\n ArrayList<String> mImageList;\n private GalleryPagerAdapter mAdapter;\n private int mCurrentIndex;\n\n @Bind(R.id.tvIndicator)\n TextView mTvIndicator;\n\n @Bind(R.id.btnClose)\n ImageView mBtnClose;\n\n @Bind(R.id.viewPager)\n ViewPager mViewPager;\n\n @OnClick(R.id.btnClose)\n void close() {\n finish();\n }\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_image_viewer);\n ButterKnife.bind(this);\n\n Intent intent = getIntent();\n String selectedImage = intent.getStringExtra(\"selectedImage\");\n mImageList = intent.getStringArrayListExtra(\"imageList\");\n\n if( mImageList == null ) {\n mImageList = new ArrayList<String>();\n if (mImageList.indexOf(selectedImage) < 0) {\n mImageList.add(selectedImage);\n }\n }\n\n mAdapter = new GalleryPagerAdapter(this);\n mViewPager.setAdapter(mAdapter);\n mViewPager.setOffscreenPageLimit(4);\n\n mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {\n @Override\n public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {\n\n }\n\n @Override\n public void onPageSelected(int position) {\n mCurrentIndex = position ;\n setIndicatior();\n }\n\n @Override\n public void onPageScrollStateChanged(int state) {\n\n }\n });\n\n //init current\n if (mImageList.indexOf(selectedImage) > -1){\n mCurrentIndex = mImageList.indexOf(selectedImage);\n mViewPager.setCurrentItem( mCurrentIndex );\n }\n\n setIndicatior();\n }\n\n private void setIndicatior(){\n String text = String.format(Locale.US, \"%1$d/%2$d\", new Object[] { mCurrentIndex+1, mImageList.size() });\n mTvIndicator.setText( text );\n }\n\n class GalleryPagerAdapter extends PagerAdapter {\n\n Context _context;\n LayoutInflater _inflater;\n\n public GalleryPagerAdapter(Context context) {\n _context = context;\n _inflater = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n }\n\n @Override\n public int getCount() {\n return mImageList.size();\n }\n\n @Override\n public boolean isViewFromObject(View view, Object object) {\n return view == ((LinearLayout) object);\n }\n\n @Override\n public Object instantiateItem(ViewGroup container, final int position) {\n View itemView = _inflater.inflate(R.layout.item_image_viewer, container, false);\n container.addView(itemView);\n\n final SubsamplingScaleImageView imageView = (SubsamplingScaleImageView) itemView.findViewById(R.id.image);\n Glide.with(_context)\n .load(mImageList.get(position))\n .asBitmap()\n .into(new SimpleTarget<Bitmap>() {\n @Override\n public void onResourceReady(Bitmap bitmap, GlideAnimation anim) {\n imageView.setImage(ImageSource.bitmap(bitmap));\n }\n });\n\n return itemView;\n }\n\n @Override\n public void destroyItem(ViewGroup container, int position, Object object) {\n container.removeView((LinearLayout) object);\n }\n }\n}",
"public class SelectFriendActivity extends AppCompatActivity {\n\n public static final String TAG = SelectFriendActivity.class.getSimpleName();\n\n private SelectFriendFragment f;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_content);\n\n f = new SelectFriendFragment();\n f.setArguments(getIntent().getExtras());\n\n if (savedInstanceState == null) {\n getSupportFragmentManager().beginTransaction().add(R.id.content, f, TAG).commit();\n }\n\n Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);\n setSupportActionBar(toolbar);\n\n final ActionBar ab = getSupportActionBar();\n }\n\n}"
] | import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import butterknife.Bind;
import butterknife.ButterKnife;
import io.xpush.chat.common.Constants;
import io.xpush.chat.core.CallbackEvent;
import io.xpush.chat.core.XPushCore;
import io.xpush.chat.fragments.XPushChatFragment;
import io.xpush.chat.models.XPushMessage;
import io.xpush.chat.util.ContentUtils;
import io.xpush.chat.view.adapters.MessageListAdapter;
import io.xpush.sampleChat.R;
import io.xpush.sampleChat.activities.ImageViewerActivity;
import io.xpush.sampleChat.activities.SelectFriendActivity; | package io.xpush.sampleChat.fragments;
public class ChatFragment extends XPushChatFragment {
public static final String TAG = ChatFragment.class.getSimpleName();
@Bind(R.id.action_chat_plus)
ImageView mChatPlus;
@Bind(R.id.hidden_panel)
RelativeLayout mHiddenPannel;
@Bind(R.id.grid_chat_plus)
GridView mGridView;
private Integer[] mThumbIds = { R.drawable.ic_photo_black, R.drawable.ic_camera_black };
private Integer[] mTitles = { R.string.action_select_photo, R.string.action_take_photo };
private String mCurrentPhotoPath;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
super.mAdapter.setOnItemClickListener(new MessageListAdapter.MessageClickListener() {
@Override
public void onMessageClick(String message, int type) {
if( type == XPushMessage.TYPE_RECEIVE_IMAGE || type == XPushMessage.TYPE_SEND_IMAGE ){
Intent intent = new Intent(mActivity, ImageViewerActivity.class);
intent.putExtra("selectedImage", message);
intent.putStringArrayListExtra("imageList", getImageList() );
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
mActivity.startActivity(intent);
}
}
@Override
public void onMessageLongClick(String message, int type) {
Log.d(TAG, "long clicked : " + message );
if( type == XPushMessage.TYPE_RECEIVE_MESSAGE || type == XPushMessage.TYPE_SEND_MESSAGE ){
ClipboardManager cm = (ClipboardManager)mActivity.getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText( " Chat Message : ", message );
cm.setPrimaryClip(clip);
Toast.makeText(mActivity, "Copied to clipboard", Toast.LENGTH_SHORT).show();
}
}
});
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_chat_new, menu);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ButterKnife.bind(this, view);
mGridView.setAdapter(new ChatMenuAdapter());
mChatPlus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mHiddenPannel.getVisibility() == View.GONE) {
mHiddenPannel.setVisibility(View.VISIBLE);
mChatPlus.setImageResource(R.drawable.ic_close_black);
} else {
mHiddenPannel.setVisibility(View.GONE);
mChatPlus.setImageResource(R.drawable.ic_add_black);
}
}
});
mGridView.setNumColumns(mTitles.length);
mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> listView, View view, int position, long id) {
if (position == 0) {
openGallery();
} else if (position == 1) {
takePicture();
}
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_leave) {
AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
builder.setTitle(mActivity.getString(R.string.action_leave_dialog_title))
.setMessage(mActivity.getString(R.string.action_leave_dialog_description))
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
channelLeave();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
AlertDialog dialog = builder.create(); // 알림창 객체 생성
dialog.show(); // 알림창 띄우기
return true;
} else if (id == R.id.action_invite) { | Intent intent = new Intent(mActivity, SelectFriendActivity.class); | 8 |
christophersmith/summer-mqtt | summer-mqtt-paho/src/test/java/com/github/christophersmith/summer/mqtt/paho/service/AutomaticReconnectTest.java | [
"public enum MqttClientConnectionType\n{\n /**\n * Represents a connection type that can only publish messages.\n */\n PUBLISHER,\n /**\n * Represents a connection type that can both publish and receive messages.\n */\n PUBSUB,\n /**\n * Represents a connection type can only receive messages.\n */\n SUBSCRIBER;\n}",
"public enum MqttQualityOfService\n{\n /**\n * Represents a Quality of Service (Qos) of 0, for At Most Once.\n */\n QOS_0(0),\n /**\n * Represents a Quality of Service (Qos) of 1, for At Least Once.\n */\n QOS_1(1),\n /**\n * Represents a Quality of Service (Qos) of 2, for Exactly Once.\n */\n QOS_2(2);\n\n private transient final int levelIdentifier;\n\n MqttQualityOfService(final int levelIdentifier)\n {\n this.levelIdentifier = levelIdentifier;\n }\n\n /**\n * Returns an {@code int} value representation of the Quality of Service Level for this\n * instance.\n * \n * @return the Level Identifier\n */\n public int getLevelIdentifier()\n {\n return levelIdentifier;\n }\n\n /**\n * Finds the {@link MqttQualityOfService} instance that matches the {@code levelIdentifier}\n * value.\n * <p>\n * If the {@code levelIdentifier} does not match a {@code MqttQualityOfService} instance, a\n * default value of {@link MqttQualityOfService#QOS_0} will be returned.\n * \n * @param levelIdentifier the Level Identifier to search by\n * @return a {@code MqttQualityOfService} value\n */\n public static final MqttQualityOfService findByLevelIdentifier(final int levelIdentifier)\n {\n MqttQualityOfService record = QOS_0;\n for (MqttQualityOfService value : values())\n {\n if (value.getLevelIdentifier() == levelIdentifier)\n {\n record = value;\n break;\n }\n }\n return record;\n }\n}",
"public class MqttClientConnectedEvent extends MqttConnectionStatusEvent\n{\n private static final long serialVersionUID = 8351820761307561719L;\n private String serverUri;\n private String[] subscribedTopics;\n\n /**\n * The default constructor.\n * \n * @param clientId the Client ID value\n * @param serverUri the Server URI value\n * @param subscribedTopics the subscribed Topics\n * @param source the {@link Object} that published this event\n * \n * @throws IllegalArgumentException if the {@code clientId} or {@code serverUri} is null or\n * empty, or if the {@code subscribedTopics} value is null\n */\n public MqttClientConnectedEvent(String clientId, String serverUri, String[] subscribedTopics,\n Object source)\n {\n super(clientId, source);\n Assert.hasText(serverUri, \"'serverUri' must be set!\");\n Assert.notNull(subscribedTopics, \"'subscribedTopics' must be set!\");\n this.serverUri = serverUri;\n this.subscribedTopics = subscribedTopics;\n }\n\n /**\n * Returns the Server URI this Client is connected to.\n * \n * @return the Server URI value\n */\n public String getServerUri()\n {\n return serverUri;\n }\n\n /**\n * Returns a String array of the Topics this Client is subscribed to.\n * \n * @return the subscribed Topics\n */\n public String[] getSubscribedTopics()\n {\n return subscribedTopics;\n }\n}",
"public class MqttClientConnectionFailureEvent extends MqttConnectionStatusEvent\n{\n private static final long serialVersionUID = -5582288189040167240L;\n private boolean autoReconnect;\n private Throwable throwable;\n\n /**\n * The default constructor.\n * \n * @param clientId the Client ID value\n * @param autoReconnect whether the Client will automatically reconnect\n * @param throwable the originating {@link Throwable}\n * @param source the {@link Object} that published this event\n * \n * @throws IllegalArgumentException if the {@code clientId} is null or empty\n */\n public MqttClientConnectionFailureEvent(String clientId, boolean autoReconnect,\n Throwable throwable, Object source)\n {\n super(clientId, source);\n this.autoReconnect = autoReconnect;\n this.throwable = throwable;\n }\n\n /**\n * Returns whether the {@link MqttClientService} instance will reconnect automatically.\n * \n * @return true or false\n */\n public boolean isAutoReconnect()\n {\n return autoReconnect;\n }\n\n /**\n * Returns the originating {@link Throwable} that caused this issue.\n * \n * @return a {@link Throwable}\n */\n public Throwable getThrowable()\n {\n return throwable;\n }\n}",
"public class MqttClientConnectionLostEvent extends MqttConnectionStatusEvent\n{\n private static final long serialVersionUID = 8706554560333104589L;\n private boolean autoReconnect;\n\n /**\n * The default constructor.\n * \n * @param clientId the Client ID value\n * @param autoReconnect whether the Client will automatically reconnect\n * @param source the {@link Object} that published this event\n * \n * @throws IllegalArgumentException if the {@code clientId} is null or empty\n */\n public MqttClientConnectionLostEvent(String clientId, boolean autoReconnect, Object source)\n {\n super(clientId, source);\n this.autoReconnect = autoReconnect;\n }\n\n /**\n * Returns whether the {@link MqttClientService} instance will reconnect automatically.\n * \n * @return true or false\n */\n public boolean isAutoReconnect()\n {\n return autoReconnect;\n }\n}",
"public class MqttClientDisconnectedEvent extends MqttConnectionStatusEvent\n{\n private static final long serialVersionUID = -5289350768631174578L;\n\n /**\n * The default constructor.\n * \n * @param clientId the Client ID value\n * @param source the {@link Object} that published this event\n * \n * @throws IllegalArgumentException if the {@code clientId} is null or empty\n */\n public MqttClientDisconnectedEvent(String clientId, Object source)\n {\n super(clientId, source);\n }\n}",
"public class MqttConnectionStatusEvent extends MqttStatusEvent\n{\n private static final long serialVersionUID = -531996904510858561L;\n\n /**\n * The default constructor.\n * \n * @param clientId the Client ID value\n * @param source the {@link Object} that published this event\n * \n * @throws IllegalArgumentException if the {@code clientId} is null or empty\n */\n public MqttConnectionStatusEvent(String clientId, Object source)\n {\n super(clientId, source);\n }\n}",
"public class BrokerHelper\n{\n private static final String CLIENT_ID = MqttAsyncClient.generateClientId();\n private static final String BROKER_URI_FORMAT = \"tcp://%s:%s\";\n private static final String BROKER_HOST_NAME = \"mqtt.eclipse.org\";\n private static final int BROKER_PORT = 1883;\n private static final String PROXY_HOST_NAME = \"localhost\";\n private static final int PROXY_PORT = 10080;\n\n public static String getClientId()\n {\n return CLIENT_ID;\n }\n\n public static String getBrokerHostName()\n {\n return BROKER_HOST_NAME;\n }\n\n public static int getBrokerPort()\n {\n return BROKER_PORT;\n }\n\n public static String getBrokerUri()\n {\n return String.format(BROKER_URI_FORMAT, BROKER_HOST_NAME, String.valueOf(BROKER_PORT));\n }\n\n public static String getProxyHostName()\n {\n return PROXY_HOST_NAME;\n }\n\n public static int getProxyPort()\n {\n return PROXY_PORT;\n }\n\n public static String getProxyUri()\n {\n return String.format(BROKER_URI_FORMAT, PROXY_HOST_NAME, String.valueOf(PROXY_PORT));\n }\n}",
"public class DefaultReconnectService implements ReconnectService\n{\n private static final long DEFAULT_CONNECTION_DELAY_SECONDS = 1;\n private static final long MAX_CONNECTION_DELAY_SECONDS = 20;\n private boolean connected;\n private long connectionDelaySeconds = DEFAULT_CONNECTION_DELAY_SECONDS;\n\n @Override\n public void connected(boolean successful)\n {\n this.connected = successful;\n if (connected)\n {\n connectionDelaySeconds = DEFAULT_CONNECTION_DELAY_SECONDS;\n }\n else\n {\n connectionDelaySeconds = connectionDelaySeconds\n * 2;\n }\n if (connectionDelaySeconds > MAX_CONNECTION_DELAY_SECONDS)\n {\n connectionDelaySeconds = MAX_CONNECTION_DELAY_SECONDS;\n }\n }\n\n @Override\n public Date getNextReconnectionDate()\n {\n return Date.from(ZonedDateTime.now().plusSeconds(connectionDelaySeconds).toInstant());\n }\n}"
] | import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.netcrusher.core.reactor.NioReactor;
import org.netcrusher.tcp.TcpCrusher;
import org.netcrusher.tcp.TcpCrusherBuilder;
import org.springframework.context.ApplicationListener;
import org.springframework.context.support.StaticApplicationContext;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.support.ExecutorSubscribableChannel;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ConcurrentTaskScheduler;
import com.github.christophersmith.summer.mqtt.core.MqttClientConnectionType;
import com.github.christophersmith.summer.mqtt.core.MqttQualityOfService;
import com.github.christophersmith.summer.mqtt.core.event.MqttClientConnectedEvent;
import com.github.christophersmith.summer.mqtt.core.event.MqttClientConnectionFailureEvent;
import com.github.christophersmith.summer.mqtt.core.event.MqttClientConnectionLostEvent;
import com.github.christophersmith.summer.mqtt.core.event.MqttClientDisconnectedEvent;
import com.github.christophersmith.summer.mqtt.core.event.MqttConnectionStatusEvent;
import com.github.christophersmith.summer.mqtt.paho.service.util.BrokerHelper;
import com.github.christophersmith.summer.mqtt.paho.service.util.DefaultReconnectService; | /*******************************************************************************
* Copyright (c) 2019 Christopher Smith - https://github.com/christophersmith
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.github.christophersmith.summer.mqtt.paho.service;
public class AutomaticReconnectTest implements ApplicationListener<MqttConnectionStatusEvent>
{
private static NioReactor REACTOR;
private static TcpCrusher CRUSHER_PROXY;
private AtomicInteger clientConnectedCount = new AtomicInteger(0);
private AtomicInteger clientDisconnectedCount = new AtomicInteger(0);
private AtomicInteger clientLostConnectionCount = new AtomicInteger(0);
private AtomicInteger clientFailedConnectionCount = new AtomicInteger(0);
@BeforeClass
public static void initialize() throws IOException
{
REACTOR = new NioReactor();
CRUSHER_PROXY = TcpCrusherBuilder.builder().withReactor(REACTOR)
.withBindAddress(BrokerHelper.getProxyHostName(), BrokerHelper.getProxyPort())
.withConnectAddress(BrokerHelper.getBrokerHostName(), BrokerHelper.getBrokerPort())
.buildAndOpen();
}
@AfterClass
public static void shutdown()
{
CRUSHER_PROXY.close();
REACTOR.close();
}
private StaticApplicationContext getStaticApplicationContext()
{
clientConnectedCount.set(0);
clientDisconnectedCount.set(0);
clientLostConnectionCount.set(0);
clientFailedConnectionCount.set(0);
StaticApplicationContext applicationContext = new StaticApplicationContext();
applicationContext.addApplicationListener(this);
applicationContext.refresh();
applicationContext.start();
return applicationContext;
}
@Test
public void testGoodConnection() throws MqttException
{
StaticApplicationContext applicationContext = getStaticApplicationContext();
MessageChannel inboundMessageChannel = new ExecutorSubscribableChannel();
PahoAsyncMqttClientService service = new PahoAsyncMqttClientService(
BrokerHelper.getProxyUri(), BrokerHelper.getClientId(), MqttClientConnectionType.PUBSUB,
null);
service.setApplicationEventPublisher(applicationContext);
service.setInboundMessageChannel(inboundMessageChannel);
service.subscribe(String.format("client/%s", BrokerHelper.getClientId()), | MqttQualityOfService.QOS_0); | 1 |
gejiaheng/Protein | app/src/main/java/com/ge/protein/comment/CommentListRepository.java | [
"public final class ApiConstants {\n\n private ApiConstants() {\n throw new AssertionError(\"No construction for constant class\");\n }\n\n // general constants of Dribbble API\n public static final String DRIBBBLE_V1_BASE_URL = \"https://api.dribbble.com\";\n public static final String DRIBBBLE_AUTHORIZE_URL = \"https://dribbble.com/oauth/authorize\";\n public static final String DRIBBBLE_GET_ACCESS_TOKEN_URL = \"https://dribbble.com/oauth/token\";\n\n // for both flavor open and play\n public static final String DRIBBBLE_AUTHORIZE_CALLBACK_URI = \"x-protein-oauth-dribbble://callback\";\n public static final String DRIBBBLE_AUTHORIZE_CALLBACK_URI_SCHEMA = \"x-protein-oauth-dribbble\";\n public static final String DRIBBBLE_AUTHORIZE_CALLBACK_URI_HOST = \"callback\";\n public static final String DRIBBBLE_AUTHORIZE_SCOPE = \"public write comment upload\";\n\n public static final int PER_PAGE = 20;\n}",
"public class ServiceGenerator {\n\n private static String lastToken;\n\n private static Gson gson = new GsonBuilder()\n .registerTypeAdapterFactory(ProteinAdapterFactory.create())\n .create();\n\n private static Cache cache;\n\n private static Retrofit retrofit;\n\n public static void init(Context context) {\n if (cache != null) {\n throw new IllegalStateException(\"Retrofit cache already initialized.\");\n }\n cache = new Cache(context.getCacheDir(), 20 * 1024 * 1024);\n }\n\n public static Retrofit retrofit() {\n return retrofit;\n }\n\n public static <S> S createService(Class<S> serviceClass, final AccessToken token) {\n String currentToken = token == null ? BuildConfig.DRIBBBLE_CLIENT_ACCESS_TOKEN : token.access_token();\n if (retrofit == null || !currentToken.equals(lastToken)) {\n lastToken = currentToken;\n OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();\n httpClientBuilder.addInterceptor(chain -> {\n Request original = chain.request();\n\n Request.Builder requestBuilder = original.newBuilder()\n .header(\"Accept\", \"application/json\")\n .header(\"Authorization\", \"Bearer\" + \" \" + lastToken)\n .method(original.method(), original.body());\n\n Request request = requestBuilder.build();\n return chain.proceed(request);\n }).cache(cache);\n if (BuildConfig.DEBUG) {\n httpClientBuilder.addNetworkInterceptor(new StethoInterceptor());\n }\n Retrofit.Builder retrofitBuilder = new Retrofit.Builder()\n .baseUrl(ApiConstants.DRIBBBLE_V1_BASE_URL)\n .addConverterFactory(GsonConverterFactory.create(gson))\n .addCallAdapterFactory(RxJava2CallAdapterFactory.create());\n OkHttpClient httpClient = httpClientBuilder.build();\n retrofit = retrofitBuilder.client(httpClient).build();\n }\n\n return retrofit.create(serviceClass);\n }\n\n}",
"public interface ShotsService {\n\n @GET(\"/v1/shots/{shot_id}\")\n Observable<Response<Shot>> getShot(@Path(\"shot_id\") long shotId);\n\n @GET(\"/v1/shots\")\n Observable<Response<List<Shot>>> listShots(@Query(\"list\") String list,\n @Query(\"timeframe\") String timeframe,\n @Query(\"date\") String date,\n @Query(\"sort\") String sort,\n @Query(\"per_page\") int perPage);\n\n @GET(\"/v1/users/{user_id}/shots\")\n Observable<Response<List<Shot>>> listShotsForUser(@Path(\"user_id\") long userId,\n @Query(\"per_page\") int perPage);\n\n @GET\n Observable<Response<List<Shot>>> listShotsOfNextPage(@Url String url);\n\n @GET(\"/v1/shots/{shot_id}/comments\")\n Observable<Response<List<Comment>>> listCommentsForShot(@Path(\"shot_id\") long shotId,\n @Query(\"per_page\") int perPage);\n\n @GET\n Observable<Response<List<Comment>>> listCommentsOfNextPage(@Url String url);\n\n @GET(\"/v1/shots/{shot_id}/like\")\n Observable<Response<ShotLike>> checkLike(@Path(\"shot_id\") long shotId);\n\n @POST(\"/v1/shots/{shot_id}/like\")\n Observable<Response<ShotLike>> likeShot(@Path(\"shot_id\") long shotId);\n\n @DELETE(\"/v1/shots/{shot_id}/like\")\n Observable<Response<ShotLike>> unlikeShot(@Path(\"shot_id\") long shotId);\n\n @POST(\"/v1/shots/{shot_id}/comments\")\n Observable<Response<Comment>> createCommentForShot(@Path(\"shot_id\") long shotId,\n @Query(\"body\") String content);\n}",
"@AutoValue\npublic abstract class Comment implements Parcelable {\n\n public abstract long id();\n\n public abstract String body();\n\n public abstract long likes_count();\n\n public abstract String likes_url();\n\n public abstract String created_at();\n\n public abstract String updated_at();\n\n public abstract User user();\n\n public static TypeAdapter<Comment> typeAdapter(Gson gson) {\n return new AutoValue_Comment.GsonTypeAdapter(gson).nullSafe();\n }\n}",
"public class AccountManager {\n\n private static AccountManager accountManager = new AccountManager();\n private AccessToken accessToken;\n private User me;\n\n private AccountManager() {\n }\n\n public static AccountManager getInstance() {\n return accountManager;\n }\n\n public AccessToken getAccessToken() {\n return accessToken;\n }\n\n public void setAccessToken(AccessToken accessToken) {\n this.accessToken = accessToken;\n }\n\n public void setAccessToken(String token) {\n accessToken = new GsonBuilder()\n .registerTypeAdapterFactory(ProteinAdapterFactory.create())\n .create()\n .fromJson(token, AccessToken.class);\n }\n\n public boolean isLogin() {\n return accessToken != null;\n }\n\n public User getMe() {\n return me;\n }\n\n public void setMe(User me) {\n this.me = me;\n }\n\n public void clear() {\n accessToken = null;\n me = null;\n }\n}"
] | import com.ge.protein.data.api.ApiConstants;
import com.ge.protein.data.api.ServiceGenerator;
import com.ge.protein.data.api.service.ShotsService;
import com.ge.protein.data.model.Comment;
import com.ge.protein.util.AccountManager;
import java.util.List;
import io.reactivex.Observable;
import retrofit2.Response; | /*
* Copyright 2017 Jiaheng Ge
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ge.protein.comment;
class CommentListRepository {
private ShotsService shotsService;
CommentListRepository() {
shotsService = ServiceGenerator.createService(ShotsService.class,
AccountManager.getInstance().getAccessToken());
}
| Observable<Response<List<Comment>>> getCommentsForShot(long shotId) { | 3 |
Sefford/material-in-30-minutes | app/src/main/java/com/sefford/material/sample/contacts/details/ui/presenters/ContactDetailPresenter.java | [
"@Module(injects = {ContactListActivity.class,\n ContactDetailsActivity.class},\n library = true,\n complete = false)\npublic class LocalBusModule {\n\n public static final String LOCAL_BUS = \"Local\";\n\n @Singleton\n @Provides\n @Named(LOCAL_BUS)\n public Bus provideLocalBus(Bus bus) {\n return bus;\n }\n\n @Singleton\n @Provides\n @Named(LOCAL_BUS)\n public Postable provideLocalPostable(@Named(LOCAL_BUS) Bus bus) {\n return bus;\n }\n}",
"public class Bus implements Postable, com.sefford.brender.interfaces.Postable {\n\n final EventBus bus;\n\n @Inject\n public Bus(EventBus bus) {\n this.bus = bus;\n }\n\n public void register(Object target) {\n if (!bus.isRegistered(target)) {\n bus.register(target);\n }\n }\n\n public void unregister(Object target) {\n if (bus.isRegistered(target)) {\n bus.unregister(target);\n }\n }\n\n @Override\n public void post(Object message) {\n bus.post(message);\n }\n}",
"public class GetContact extends StandaloneInteractor<Long> {\n\n final Repository<Long, Contact> repository;\n\n /**\n * Creates a new instance of the Standalone Interactor.\n *\n * @param log Logging facilities\n * @param executor Execution element\n * @param repository\n */\n @Inject\n public GetContact(Loggable log, ThreadPoolExecutor executor, Repository<Long, Contact> repository) {\n super(log, executor);\n this.repository = repository;\n }\n\n @Override\n protected Interactor instantiateInteractor(Postable bus, Long id) {\n return new CacheInteractor(bus, log, new GetContactDelegate(repository, id));\n }\n}",
"public class GetContactResponse implements Response {\n\n final Contact contact;\n final ContactData phones;\n final ContactData mails;\n\n public GetContactResponse(Contact contact, ContactData phones, ContactData mails) {\n this.contact = contact;\n this.phones = phones;\n this.mails = mails;\n }\n\n @Override\n public boolean isSuccess() {\n return true;\n }\n\n @Override\n public boolean isFromNetwork() {\n return false;\n }\n\n public Contact getContact() {\n return contact;\n }\n\n public ContactData getPhones() {\n return phones;\n }\n\n public ContactData getMails() {\n return mails;\n }\n}",
"public class ContactDetailView {\n\n final RecyclerRendererAdapter adapter;\n final List<Renderable> contactData;\n final LetterTileDrawable placeholder;\n final Resources resources;\n\n @InjectView(R.id.rv_data)\n RecyclerView rvData;\n @InjectView(R.id.iv_cover)\n ImageView ivCover;\n @InjectView(R.id.tb_main)\n Toolbar toolbar;\n @InjectView(R.id.ctl_container)\n CollapsingToolbarLayout ctlContainer;\n\n Picasso picasso;\n\n String name;\n String color;\n\n public ContactDetailView(RecyclerRendererAdapter adapter, List<Renderable> contactData, Resources resources) {\n this.adapter = adapter;\n this.contactData = contactData;\n this.resources = resources;\n this.placeholder = new LetterTileDrawable(resources, 0);\n }\n\n public void bind(View view) {\n ButterKnife.inject(this, view);\n picasso = Picasso.with(view.getContext());\n ctlContainer.setTitle(name);\n toolbar.setTitle(name);\n rvData.setAdapter(adapter);\n rvData.setLayoutManager(new LinearLayoutManager(view.getContext(), LinearLayoutManager.VERTICAL, false));\n ivCover.setBackground(placeholder);\n }\n\n public void configurePlaceholder(String name, String color) {\n this.name = name;\n this.color = color;\n placeholder.setContactDetails(name, color);\n }\n\n public void release() {\n ButterKnife.reset(this);\n }\n\n public void setCover(Contact contact) {\n picasso.load(contact.getPhoto())\n .placeholder(placeholder)\n .error(placeholder)\n .into(ivCover);\n }\n\n public void setMails(ContactData mails) {\n if (!mails.getElements().isEmpty()) {\n this.contactData.add(mails);\n adapter.notifyDataSetChanged();\n }\n }\n\n public void setPhones(ContactData phones) {\n if (!phones.getElements().isEmpty()) {\n this.contactData.add(phones);\n adapter.notifyDataSetChanged();\n }\n }\n\n public void addTrolling() {\n this.contactData.add(new Trolling());\n adapter.notifyDataSetChanged();\n }\n}"
] | import com.sefford.material.sample.common.injection.modules.LocalBusModule;
import com.sefford.material.sample.common.internal.Bus;
import com.sefford.material.sample.contacts.details.interactors.GetContact;
import com.sefford.material.sample.contacts.details.responses.GetContactResponse;
import com.sefford.material.sample.contacts.details.ui.views.ContactDetailView;
import javax.inject.Inject;
import javax.inject.Named; | /*
* Copyright (C) 2015 Saúl Díaz
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sefford.material.sample.contacts.details.ui.presenters;
/**
* Presenter that absorbs all the UI-related lifecycle for {@link com.sefford.material.sample.contacts.details.ui.activities.ContactDetailsActivity ContactDetailActivity}
*/
public class ContactDetailPresenter {
final Bus bus; | final GetContact getContact; | 2 |
kwon37xi/hibernate4-memcached | hibernate4-memcached-core/src/main/java/kr/pe/kwonnam/hibernate4memcached/regions/EntityMemcachedRegion.java | [
"public class CacheNamespace implements Serializable {\n /**\n * name of region\n */\n private String name;\n\n /**\n * if this value is true, the memcached adapter should implement namespace pattern\n * or ignore namespace pattern.\n * <p/>\n * see <a href=\"https://code.google.com/p/memcached/wiki/NewProgrammingTricks#Namespacing\">Memcached Namespacing</a>\n */\n private boolean namespaceExpirationRequired;\n\n public CacheNamespace(String name, boolean namespaceExpirationRequired) {\n this.name = name;\n this.namespaceExpirationRequired = namespaceExpirationRequired;\n }\n\n public String getName() {\n return name;\n }\n\n public boolean isNamespaceExpirationRequired() {\n return namespaceExpirationRequired;\n }\n\n @Override\n public boolean equals(Object o) {\n if (o == null) {\n return false;\n }\n if (this == o) {\n return true;\n }\n if (getClass() != o.getClass()) {\n return false;\n }\n\n CacheNamespace otherCacheNamespace = (CacheNamespace) o;\n\n return new EqualsBuilder().append(name, otherCacheNamespace.name)\n .append(namespaceExpirationRequired, otherCacheNamespace.namespaceExpirationRequired).isEquals();\n }\n\n @Override\n public int hashCode() {\n return new HashCodeBuilder().append(name).append(namespaceExpirationRequired).toHashCode();\n }\n\n @Override\n public String toString() {\n return new ToStringBuilder(this).append(\"name\", name).append(\"namespaceExpirationRequired\", namespaceExpirationRequired).toString();\n }\n}",
"public interface MemcachedAdapter {\n /**\n * Lifecycle callback to perform initialization.\n *\n * @param properties the defined cfg properties\n */\n void init(OverridableReadOnlyProperties properties);\n\n /**\n * Lifecycle callback to perform cleanup.\n */\n void destroy();\n\n /**\n * get value from memcached\n */\n Object get(CacheNamespace cacheNamespace, String key);\n\n /**\n * set value to memcache with expirySeconds\n */\n void set(CacheNamespace cacheNamespace, String key, Object value, int expirySeconds);\n\n /**\n * delete key from memcached\n */\n void delete(CacheNamespace cacheNamespace, String key);\n\n /**\n * increase given increment couter and return new value.\n *\n * @param cacheNamespace cache namespace\n * @param key counter key\n * @param by the amount of increment\n * @param defaultValue default value when the key missing\n * @return increased value\n */\n long increaseCounter(CacheNamespace cacheNamespace, String key, long by, long defaultValue, int expirySeconds);\n\n /**\n * get current value from increment counter\n *\n * @param cacheNamespace cache namespace\n * @param key counter key\n * @param defaultValue default value when the key missing\n * @return current value of counter without increment\n */\n long getCounter(CacheNamespace cacheNamespace, String key, long defaultValue, int expirySeconds);\n\n /**\n * Evict namespace\n *\n * @param cacheNamespace cache namespace\n */\n void evictAll(CacheNamespace cacheNamespace);\n}",
"public class NonstrictReadWriteEntityRegionAccessStrategy extends BaseEntityMemcachedRegionAccessStrategy {\n private Logger log = LoggerFactory.getLogger(NonstrictReadWriteEntityRegionAccessStrategy.class);\n\n public NonstrictReadWriteEntityRegionAccessStrategy(EntityMemcachedRegion entityMemcachedRegion) {\n super(entityMemcachedRegion);\n }\n\n @Override\n public boolean insert(Object key, Object value, Object version) throws CacheException {\n log.debug(\"region access strategy nonstrict-read-write entity insert() {} {}\", getInternalRegion().getCacheNamespace(), key);\n // On nonstrict-read-write, Hibernate never calls this method.\n return false;\n }\n\n @Override\n public boolean afterInsert(Object key, Object value, Object version) throws CacheException {\n log.debug(\"region access strategy nonstrict-read-write entity afterInsert() {} {}\", getInternalRegion().getCacheNamespace(), key);\n // On nonstrict-read-write, Hibernate never calls this method.\n return false;\n }\n\n /**\n * not necessary in nostrict-read-write\n *\n * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy\n */\n @Override\n public boolean update(Object key, Object value, Object currentVersion, Object previousVersion) throws CacheException {\n log.debug(\"region access strategy nonstrict-read-write entity update() {} {}\", getInternalRegion().getCacheNamespace(), key);\n return false;\n }\n\n /**\n * need evict the key, after update.\n *\n * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy\n */\n @Override\n public boolean afterUpdate(Object key, Object value, Object currentVersion, Object previousVersion, SoftLock lock) throws CacheException {\n log.debug(\"region access strategy nonstrict-read-write entity afterUpdate() {} {}\", getInternalRegion().getCacheNamespace(), key);\n getInternalRegion().evict(key);\n return false;\n }\n}",
"public class ReadOnlyEntityRegionAccessStrategy extends BaseEntityMemcachedRegionAccessStrategy {\n private Logger log = LoggerFactory.getLogger(ReadOnlyEntityRegionAccessStrategy.class);\n\n public ReadOnlyEntityRegionAccessStrategy(EntityMemcachedRegion entityMemcachedRegion) {\n super(entityMemcachedRegion);\n }\n\n @Override\n public boolean insert(Object key, Object value, Object version) throws CacheException {\n log.debug(\"region access strategy readonly entity insert() {} {}\", getInternalRegion().getCacheNamespace(), key);\n // On read-only, Hibernate never calls this method.\n return false;\n }\n\n @Override\n public boolean afterInsert(Object key, Object value, Object version) throws CacheException {\n log.debug(\"region access strategy readonly entity afterInsert() {} {}\", getInternalRegion().getCacheNamespace(), key);\n // On read-only, Hibernate never calls this method.\n return false;\n }\n\n /**\n * read-onluy does not support update.\n */\n @Override\n public boolean update(Object key, Object value, Object currentVersion, Object previousVersion) throws CacheException {\n log.debug(\"region access strategy readonly entity update() {} {}\", getInternalRegion().getCacheNamespace(), key);\n throw new UnsupportedOperationException(\"ReadOnly strategy does not support update.\");\n }\n\n /**\n * read-only does not support update.\n */\n @Override\n public boolean afterUpdate(Object key, Object value, Object currentVersion, Object previousVersion, SoftLock lock) throws CacheException {\n log.debug(\"region access strategy readonly entity afterUpdate() {} {}\", getInternalRegion().getCacheNamespace(), key);\n throw new UnsupportedOperationException(\"ReadOnly strategy does not support update.\");\n }\n}",
"public interface HibernateCacheTimestamper {\n\n void setSettings(Settings settings);\n\n void setProperties(OverridableReadOnlyProperties properties);\n\n void setMemcachedAdapter(MemcachedAdapter memcachedAdapter);\n\n /** initialize timestamp object */\n void init();\n\n /** get next timestamp */\n long next();\n}",
"public interface OverridableReadOnlyProperties {\n String getProperty(String key);\n\n String getProperty(String key, String defaultValue);\n\n String getRequiredProperty(String key);\n}"
] | import kr.pe.kwonnam.hibernate4memcached.memcached.CacheNamespace;
import kr.pe.kwonnam.hibernate4memcached.memcached.MemcachedAdapter;
import kr.pe.kwonnam.hibernate4memcached.strategies.NonstrictReadWriteEntityRegionAccessStrategy;
import kr.pe.kwonnam.hibernate4memcached.strategies.ReadOnlyEntityRegionAccessStrategy;
import kr.pe.kwonnam.hibernate4memcached.timestamper.HibernateCacheTimestamper;
import kr.pe.kwonnam.hibernate4memcached.util.OverridableReadOnlyProperties;
import org.hibernate.cache.CacheException;
import org.hibernate.cache.spi.CacheDataDescription;
import org.hibernate.cache.spi.EntityRegion;
import org.hibernate.cache.spi.access.AccessType;
import org.hibernate.cache.spi.access.EntityRegionAccessStrategy;
import org.hibernate.cfg.Settings; | package kr.pe.kwonnam.hibernate4memcached.regions;
/**
* @author KwonNam Son (kwon37xi@gmail.com)
*/
public class EntityMemcachedRegion extends TransactionalDataMemcachedRegion implements EntityRegion {
public EntityMemcachedRegion(String regionName, OverridableReadOnlyProperties properties, CacheDataDescription metadata, Settings settings, MemcachedAdapter memcachedAdapter, HibernateCacheTimestamper hibernateCacheTimestamper) { | super(new CacheNamespace(regionName, true), properties, metadata, settings, memcachedAdapter, hibernateCacheTimestamper); | 0 |
gyf-dev/ImmersionBar | immersionbar-sample/src/main/java/com/gyf/immersionbar/sample/activity/DialogActivity.java | [
"@TargetApi(Build.VERSION_CODES.KITKAT)\npublic final class ImmersionBar implements ImmersionCallback {\n\n private final Activity mActivity;\n private Fragment mSupportFragment;\n private android.app.Fragment mFragment;\n private Dialog mDialog;\n private Window mWindow;\n private ViewGroup mDecorView;\n private ViewGroup mContentView;\n private ImmersionBar mParentBar;\n\n /**\n * 是否是在Fragment里使用\n */\n private boolean mIsFragment = false;\n /**\n * 是否是DialogFragment\n */\n private boolean mIsDialogFragment = false;\n /**\n * 是否是在Dialog里使用\n */\n private boolean mIsDialog = false;\n /**\n * 用户配置的bar参数\n */\n private BarParams mBarParams;\n /**\n * 系统bar相关信息\n */\n private BarConfig mBarConfig;\n /**\n * 导航栏的高度,适配Emui3系统有用\n */\n private int mNavigationBarHeight = 0;\n /**\n * 导航栏的宽度,适配Emui3系统有用\n */\n private int mNavigationBarWidth = 0;\n /**\n * ActionBar的高度\n */\n private int mActionBarHeight = 0;\n /**\n * 软键盘监听相关\n */\n private FitsKeyboard mFitsKeyboard = null;\n /**\n * 用户使用tag增加的bar参数的集合\n */\n private final Map<String, BarParams> mTagMap = new HashMap<>();\n /**\n * 当前顶部布局和状态栏重叠是以哪种方式适配的\n */\n private int mFitsStatusBarType = FLAG_FITS_DEFAULT;\n /**\n * 是否已经调用过init()方法了\n */\n private boolean mInitialized = false;\n /**\n * ActionBar是否是在LOLLIPOP下设备使用\n */\n private boolean mIsActionBarBelowLOLLIPOP = false;\n\n private boolean mKeyboardTempEnable = false;\n\n private int mPaddingLeft = 0, mPaddingTop = 0, mPaddingRight = 0, mPaddingBottom = 0;\n\n /**\n * 在Activity使用\n * With immersion bar.\n *\n * @param activity the activity\n * @return the immersion bar\n */\n public static ImmersionBar with(@NonNull Activity activity) {\n return getRetriever().get(activity, false);\n }\n\n /**\n * 在Activity使用\n *\n * @param activity the activity\n * @param isOnly the is only fragment实例对象是否唯一,默认是false,不唯一,isOnly影响tag以何种形式生成\n * @return the immersion bar\n */\n public static ImmersionBar with(@NonNull Activity activity, boolean isOnly) {\n return getRetriever().get(activity, isOnly);\n }\n\n /**\n * 在Fragment使用\n * With immersion bar.\n *\n * @param fragment the fragment\n * @return the immersion bar\n */\n public static ImmersionBar with(@NonNull Fragment fragment) {\n return getRetriever().get(fragment, false);\n }\n\n /**\n * 在Fragment使用\n * With immersion bar.\n *\n * @param fragment the fragment\n * @param isOnly the is only fragment实例对象是否唯一,默认是false,不唯一,isOnly影响tag以何种形式生成\n * @return the immersion bar\n */\n public static ImmersionBar with(@NonNull Fragment fragment, boolean isOnly) {\n return getRetriever().get(fragment, isOnly);\n }\n\n /**\n * 在Fragment使用\n * With immersion bar.\n *\n * @param fragment the fragment\n * @return the immersion bar\n */\n public static ImmersionBar with(@NonNull android.app.Fragment fragment) {\n return getRetriever().get(fragment, false);\n }\n\n /**\n * 在Fragment使用\n * With immersion bar.\n *\n * @param fragment the fragment\n * @param isOnly the is only fragment实例对象是否唯一,默认是false,不唯一,isOnly影响tag以何种形式生成\n * @return the immersion bar\n */\n public static ImmersionBar with(@NonNull android.app.Fragment fragment, boolean isOnly) {\n return getRetriever().get(fragment, isOnly);\n }\n\n /**\n * 在DialogFragment使用\n * With immersion bar.\n *\n * @param dialogFragment the dialog fragment\n * @return the immersion bar\n */\n public static ImmersionBar with(@NonNull DialogFragment dialogFragment) {\n return getRetriever().get(dialogFragment, false);\n }\n\n /**\n * 在DialogFragment使用\n *\n * @param dialogFragment the dialog fragment\n * @param isOnly the is only fragment实例对象是否唯一,默认是false,不唯一,isOnly影响tag以何种形式生成\n * @return the immersion bar\n */\n public static ImmersionBar with(@NonNull DialogFragment dialogFragment, boolean isOnly) {\n return getRetriever().get(dialogFragment, isOnly);\n }\n\n /**\n * 在DialogFragment使用\n * With immersion bar.\n *\n * @param dialogFragment the dialog fragment\n * @return the immersion bar\n */\n public static ImmersionBar with(@NonNull android.app.DialogFragment dialogFragment) {\n return getRetriever().get(dialogFragment, false);\n }\n\n /**\n * 在DialogFragment使用\n *\n * @param dialogFragment the dialog fragment\n * @param isOnly the is only fragment实例对象是否唯一,默认是false,不唯一,isOnly影响tag以何种形式生成\n * @return the immersion bar\n */\n public static ImmersionBar with(@NonNull android.app.DialogFragment dialogFragment, boolean isOnly) {\n return getRetriever().get(dialogFragment, isOnly);\n }\n\n /**\n * 在dialog里使用\n * With immersion bar.\n *\n * @param activity the activity\n * @param dialog the dialog\n * @return the immersion bar\n */\n public static ImmersionBar with(@NonNull Activity activity, @NonNull Dialog dialog) {\n return getRetriever().get(activity, dialog, false);\n }\n\n /**\n * 在dialog里使用\n *\n * @param activity the activity\n * @param dialog the dialog\n * @param isOnly the is only fragment实例对象是否唯一,默认是false,不唯一,isOnly影响tag以何种形式生成\n * @return the immersion bar\n */\n public static ImmersionBar with(@NonNull Activity activity, @NonNull Dialog dialog, boolean isOnly) {\n return getRetriever().get(activity, dialog, isOnly);\n }\n\n /**\n * 在Dialog里销毁,不包括DialogFragment\n *\n * @param activity the activity\n * @param dialog the dialog\n */\n public static void destroy(@NonNull Activity activity, @NonNull Dialog dialog) {\n getRetriever().destroy(activity, dialog, false);\n }\n\n /**\n * 在Dialog里销毁,不包括DialogFragment\n *\n * @param activity the activity\n * @param dialog the dialog\n * @param isOnly the is only fragment实例对象是否唯一,默认是false,不唯一,isOnly影响tag以何种形式生成\n */\n public static void destroy(@NonNull Activity activity, @NonNull Dialog dialog, boolean isOnly) {\n getRetriever().destroy(activity, dialog, isOnly);\n }\n\n /**\n * 通过上面配置后初始化后方可成功调用\n */\n public void init() {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && mBarParams.barEnable) {\n //更新Bar的参数\n updateBarParams();\n //设置沉浸式\n setBar();\n //修正界面显示\n fitsWindows();\n //适配软键盘与底部输入框冲突问题\n fitsKeyboard();\n //变色view\n transformView();\n mInitialized = true;\n }\n }\n\n /**\n * 内部方法无需调用\n */\n void onDestroy() {\n //取消监听\n cancelListener();\n if (mIsDialog && mParentBar != null) {\n mParentBar.mBarParams.keyboardEnable = mParentBar.mKeyboardTempEnable;\n if (mParentBar.mBarParams.barHide != BarHide.FLAG_SHOW_BAR) {\n mParentBar.setBar();\n }\n }\n mInitialized = false;\n }\n\n void onResume() {\n updateBarConfig();\n if (!mIsFragment && mInitialized && mBarParams != null) {\n if (OSUtils.isEMUI3_x() && mBarParams.navigationBarWithEMUI3Enable) {\n init();\n } else {\n if (mBarParams.barHide != BarHide.FLAG_SHOW_BAR) {\n setBar();\n }\n }\n }\n }\n\n void onConfigurationChanged(Configuration newConfig) {\n updateBarConfig();\n if (OSUtils.isEMUI3_x() || Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {\n if (mInitialized && !mIsFragment && mBarParams.navigationBarWithKitkatEnable) {\n init();\n } else {\n fitsWindows();\n }\n } else {\n fitsWindows();\n }\n }\n\n /**\n * 更新Bar的参数\n * Update bar params.\n */\n private void updateBarParams() {\n adjustDarkModeParams();\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {\n //获得Bar相关信息\n if (!mInitialized || mIsFragment) {\n updateBarConfig();\n }\n if (mParentBar != null) {\n //如果在Fragment中使用,让Activity同步Fragment的BarParams参数\n if (mIsFragment) {\n mParentBar.mBarParams = mBarParams;\n }\n //如果dialog里设置了keyboardEnable为true,则Activity中所设置的keyboardEnable为false\n if (mIsDialog) {\n if (mParentBar.mKeyboardTempEnable) {\n mParentBar.mBarParams.keyboardEnable = false;\n }\n }\n }\n }\n }\n\n /**\n * 初始化状态栏和导航栏\n */\n void setBar() {\n //防止系统栏隐藏时内容区域大小发生变化\n int uiFlags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE;\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && !OSUtils.isEMUI3_x()) {\n //适配刘海屏\n fitsNotchScreen();\n //初始化5.0以上,包含5.0\n uiFlags = initBarAboveLOLLIPOP(uiFlags);\n //android 6.0以上设置状态栏字体为暗色\n uiFlags = setStatusBarDarkFont(uiFlags);\n //android 8.0以上设置导航栏图标为暗色\n uiFlags = setNavigationIconDark(uiFlags);\n //适配android 11以上\n setBarDarkFont();\n } else {\n //初始化5.0以下,4.4以上沉浸式\n initBarBelowLOLLIPOP();\n }\n //隐藏状态栏或者导航栏\n uiFlags = hideBarBelowR(uiFlags);\n //应用flag\n mDecorView.setSystemUiVisibility(uiFlags);\n //适配小米和魅族状态栏黑白\n setSpecialBarDarkMode();\n //适配android 11以上\n hideBarAboveR();\n //导航栏显示隐藏监听,目前只支持带有导航栏的华为和小米手机\n if (mBarParams.onNavigationBarListener != null) {\n NavigationBarObserver.getInstance().register(mActivity.getApplication());\n }\n }\n\n private void setBarDarkFont() {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {\n setStatusBarDarkFontAboveR();\n setNavigationIconDarkAboveR();\n }\n }\n\n private void setSpecialBarDarkMode() {\n if (OSUtils.isMIUI6Later()) {\n //修改miui状态栏字体颜色\n SpecialBarFontUtils.setMIUIBarDark(mWindow, IMMERSION_STATUS_BAR_DARK_MIUI, mBarParams.statusBarDarkFont);\n //修改miui导航栏图标为黑色\n if (mBarParams.navigationBarEnable) {\n SpecialBarFontUtils.setMIUIBarDark(mWindow, IMMERSION_NAVIGATION_BAR_DARK_MIUI, mBarParams.navigationBarDarkIcon);\n }\n }\n // 修改Flyme OS状态栏字体颜色\n if (OSUtils.isFlymeOS4Later()) {\n if (mBarParams.flymeOSStatusBarFontColor != 0) {\n SpecialBarFontUtils.setStatusBarDarkIcon(mActivity, mBarParams.flymeOSStatusBarFontColor);\n } else {\n SpecialBarFontUtils.setStatusBarDarkIcon(mActivity, mBarParams.statusBarDarkFont);\n }\n }\n }\n\n /**\n * 适配刘海屏\n * Fits notch screen.\n */\n private void fitsNotchScreen() {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && !mInitialized) {\n try {\n WindowManager.LayoutParams lp = mWindow.getAttributes();\n lp.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;\n mWindow.setAttributes(lp);\n } catch (Exception e) {\n\n }\n }\n }\n\n /**\n * 初始化android 5.0以上状态栏和导航栏\n *\n * @param uiFlags the ui flags\n * @return the int\n */\n @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)\n private int initBarAboveLOLLIPOP(int uiFlags) {\n //获得默认导航栏颜色\n if (!mInitialized) {\n mBarParams.defaultNavigationBarColor = mWindow.getNavigationBarColor();\n }\n //Activity全屏显示,但状态栏不会被隐藏覆盖,状态栏依然可见,Activity顶端布局部分会被状态栏遮住。\n uiFlags |= View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;\n if (mBarParams.fullScreen && mBarParams.navigationBarEnable) {\n //Activity全屏显示,但导航栏不会被隐藏覆盖,导航栏依然可见,Activity底部布局部分会被导航栏遮住。\n uiFlags |= View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;\n }\n mWindow.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);\n //判断是否存在导航栏\n if (mBarConfig.hasNavigationBar()) {\n mWindow.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);\n }\n //需要设置这个才能设置状态栏和导航栏颜色\n mWindow.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);\n //设置状态栏颜色\n if (mBarParams.statusBarColorEnabled) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {\n mWindow.setStatusBarContrastEnforced(false);\n }\n mWindow.setStatusBarColor(ColorUtils.blendARGB(mBarParams.statusBarColor,\n mBarParams.statusBarColorTransform, mBarParams.statusBarAlpha));\n } else {\n mWindow.setStatusBarColor(ColorUtils.blendARGB(mBarParams.statusBarColor,\n Color.TRANSPARENT, mBarParams.statusBarAlpha));\n }\n //设置导航栏颜色\n if (mBarParams.navigationBarEnable) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {\n mWindow.setNavigationBarContrastEnforced(false);\n }\n mWindow.setNavigationBarColor(ColorUtils.blendARGB(mBarParams.navigationBarColor,\n mBarParams.navigationBarColorTransform, mBarParams.navigationBarAlpha));\n } else {\n mWindow.setNavigationBarColor(mBarParams.defaultNavigationBarColor);\n }\n return uiFlags;\n }\n\n /**\n * 初始化android 4.4和emui3.1状态栏和导航栏\n */\n private void initBarBelowLOLLIPOP() {\n //透明状态栏\n mWindow.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);\n //创建一个假的状态栏\n setupStatusBarView();\n //判断是否存在导航栏,是否禁止设置导航栏\n if (mBarConfig.hasNavigationBar() || OSUtils.isEMUI3_x()) {\n if (mBarParams.navigationBarEnable && mBarParams.navigationBarWithKitkatEnable) {\n //透明导航栏,设置这个,如果有导航栏,底部布局会被导航栏遮住\n mWindow.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);\n } else {\n mWindow.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);\n }\n if (mNavigationBarHeight == 0) {\n mNavigationBarHeight = mBarConfig.getNavigationBarHeight();\n }\n if (mNavigationBarWidth == 0) {\n mNavigationBarWidth = mBarConfig.getNavigationBarWidth();\n }\n //创建一个假的导航栏\n setupNavBarView();\n }\n }\n\n /**\n * 设置一个可以自定义颜色的状态栏\n */\n private void setupStatusBarView() {\n View statusBarView = mDecorView.findViewById(IMMERSION_STATUS_BAR_VIEW_ID);\n if (statusBarView == null) {\n statusBarView = new View(mActivity);\n FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,\n mBarConfig.getStatusBarHeight());\n params.gravity = Gravity.TOP;\n statusBarView.setLayoutParams(params);\n statusBarView.setVisibility(View.VISIBLE);\n statusBarView.setId(IMMERSION_STATUS_BAR_VIEW_ID);\n mDecorView.addView(statusBarView);\n }\n if (mBarParams.statusBarColorEnabled) {\n statusBarView.setBackgroundColor(ColorUtils.blendARGB(mBarParams.statusBarColor,\n mBarParams.statusBarColorTransform, mBarParams.statusBarAlpha));\n } else {\n statusBarView.setBackgroundColor(ColorUtils.blendARGB(mBarParams.statusBarColor,\n Color.TRANSPARENT, mBarParams.statusBarAlpha));\n }\n }\n\n /**\n * 设置一个可以自定义颜色的导航栏\n */\n private void setupNavBarView() {\n View navigationBarView = mDecorView.findViewById(IMMERSION_NAVIGATION_BAR_VIEW_ID);\n if (navigationBarView == null) {\n navigationBarView = new View(mActivity);\n navigationBarView.setId(IMMERSION_NAVIGATION_BAR_VIEW_ID);\n mDecorView.addView(navigationBarView);\n }\n\n FrameLayout.LayoutParams params;\n if (mBarConfig.isNavigationAtBottom()) {\n params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, mBarConfig.getNavigationBarHeight());\n params.gravity = Gravity.BOTTOM;\n } else {\n params = new FrameLayout.LayoutParams(mBarConfig.getNavigationBarWidth(), FrameLayout.LayoutParams.MATCH_PARENT);\n params.gravity = Gravity.END;\n }\n navigationBarView.setLayoutParams(params);\n navigationBarView.setBackgroundColor(ColorUtils.blendARGB(mBarParams.navigationBarColor,\n mBarParams.navigationBarColorTransform, mBarParams.navigationBarAlpha));\n\n if (mBarParams.navigationBarEnable && mBarParams.navigationBarWithKitkatEnable && !mBarParams.hideNavigationBar) {\n navigationBarView.setVisibility(View.VISIBLE);\n } else {\n navigationBarView.setVisibility(View.GONE);\n }\n }\n\n /**\n * 调整深色亮色模式参数\n */\n private void adjustDarkModeParams() {\n int statusBarColor = ColorUtils.blendARGB(mBarParams.statusBarColor,\n mBarParams.statusBarColorTransform, mBarParams.statusBarAlpha);\n if (mBarParams.autoStatusBarDarkModeEnable && statusBarColor != Color.TRANSPARENT) {\n boolean statusBarDarkFont = statusBarColor > IMMERSION_BOUNDARY_COLOR;\n statusBarDarkFont(statusBarDarkFont, mBarParams.autoStatusBarDarkModeAlpha);\n }\n int navigationBarColor = ColorUtils.blendARGB(mBarParams.navigationBarColor,\n mBarParams.navigationBarColorTransform, mBarParams.navigationBarAlpha);\n if (mBarParams.autoNavigationBarDarkModeEnable && navigationBarColor != Color.TRANSPARENT) {\n boolean navigationBarDarkIcon = navigationBarColor > IMMERSION_BOUNDARY_COLOR;\n navigationBarDarkIcon(navigationBarDarkIcon, mBarParams.autoNavigationBarDarkModeAlpha);\n }\n }\n\n /**\n * Hide bar.\n * 隐藏或显示状态栏和导航栏。\n *\n * @param uiFlags the ui flags\n * @return the int\n */\n private int hideBarBelowR(int uiFlags) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {\n return uiFlags;\n }\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {\n switch (mBarParams.barHide) {\n case FLAG_HIDE_BAR:\n uiFlags |= View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION\n | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION\n | View.INVISIBLE;\n break;\n case FLAG_HIDE_STATUS_BAR:\n uiFlags |= View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.INVISIBLE;\n break;\n case FLAG_HIDE_NAVIGATION_BAR:\n uiFlags |= View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION\n | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;\n break;\n case FLAG_SHOW_BAR:\n uiFlags |= View.SYSTEM_UI_FLAG_VISIBLE;\n break;\n default:\n break;\n }\n }\n return uiFlags | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;\n }\n\n /**\n * 修正界面显示\n */\n private void fitsWindows() {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && !OSUtils.isEMUI3_x()) {\n //android 5.0以上解决状态栏和布局重叠问题\n fitsWindowsAboveLOLLIPOP();\n } else {\n //android 5.0以下解决状态栏和布局重叠问题\n fitsWindowsBelowLOLLIPOP();\n }\n //适配状态栏与布局重叠问题\n fitsLayoutOverlap();\n }\n }\n\n /**\n * android 5.0以下解决状态栏和布局重叠问题\n */\n private void fitsWindowsBelowLOLLIPOP() {\n if (mBarParams.isSupportActionBar) {\n mIsActionBarBelowLOLLIPOP = true;\n mContentView.post(this);\n } else {\n mIsActionBarBelowLOLLIPOP = false;\n postFitsWindowsBelowLOLLIPOP();\n }\n }\n\n @Override\n public void run() {\n postFitsWindowsBelowLOLLIPOP();\n }\n\n private void postFitsWindowsBelowLOLLIPOP() {\n //解决android4.4有导航栏的情况下,activity底部被导航栏遮挡的问题和android 5.0以下解决状态栏和布局重叠问题\n fitsWindowsKITKAT();\n //解决华为emui3.1或者3.0导航栏手动隐藏的问题\n if (!mIsFragment && OSUtils.isEMUI3_x()) {\n fitsWindowsEMUI();\n }\n }\n\n /**\n * android 5.0以上解决状态栏和布局重叠问题\n * Fits windows above lollipop.\n */\n private void fitsWindowsAboveLOLLIPOP() {\n if (checkFitsSystemWindows(mDecorView.findViewById(android.R.id.content))) {\n setPadding(0, 0, 0, 0);\n return;\n }\n int top = 0;\n if (mBarParams.fits && mFitsStatusBarType == FLAG_FITS_SYSTEM_WINDOWS) {\n top = mBarConfig.getStatusBarHeight();\n }\n if (mBarParams.isSupportActionBar) {\n top = mBarConfig.getStatusBarHeight() + mActionBarHeight;\n }\n setPadding(0, top, 0, 0);\n }\n\n /**\n * 解决android4.4有导航栏的情况下,activity底部被导航栏遮挡的问题和android 5.0以下解决状态栏和布局重叠问题\n * Fits windows below lollipop.\n */\n private void fitsWindowsKITKAT() {\n if (checkFitsSystemWindows(mDecorView.findViewById(android.R.id.content))) {\n setPadding(0, 0, 0, 0);\n return;\n }\n int top = 0, right = 0, bottom = 0;\n if (mBarParams.fits && mFitsStatusBarType == FLAG_FITS_SYSTEM_WINDOWS) {\n top = mBarConfig.getStatusBarHeight();\n }\n if (mBarParams.isSupportActionBar) {\n top = mBarConfig.getStatusBarHeight() + mActionBarHeight;\n }\n if (mBarConfig.hasNavigationBar() && mBarParams.navigationBarEnable && mBarParams.navigationBarWithKitkatEnable) {\n if (!mBarParams.fullScreen) {\n if (mBarConfig.isNavigationAtBottom()) {\n bottom = mBarConfig.getNavigationBarHeight();\n } else {\n right = mBarConfig.getNavigationBarWidth();\n }\n }\n if (mBarParams.hideNavigationBar) {\n if (mBarConfig.isNavigationAtBottom()) {\n bottom = 0;\n } else {\n right = 0;\n }\n } else {\n if (!mBarConfig.isNavigationAtBottom()) {\n right = mBarConfig.getNavigationBarWidth();\n }\n }\n }\n setPadding(0, top, right, bottom);\n }\n\n /**\n * 注册emui3.x导航栏监听函数\n * Register emui 3 x.\n */\n private void fitsWindowsEMUI() {\n View navigationBarView = mDecorView.findViewById(IMMERSION_NAVIGATION_BAR_VIEW_ID);\n if (mBarParams.navigationBarEnable && mBarParams.navigationBarWithKitkatEnable) {\n if (navigationBarView != null) {\n EMUI3NavigationBarObserver.getInstance().addOnNavigationBarListener(this);\n EMUI3NavigationBarObserver.getInstance().register(mActivity.getApplication());\n }\n } else {\n EMUI3NavigationBarObserver.getInstance().removeOnNavigationBarListener(this);\n navigationBarView.setVisibility(View.GONE);\n }\n }\n\n /**\n * 更新BarConfig\n */\n private void updateBarConfig() {\n mBarConfig = new BarConfig(mActivity);\n if (!mInitialized || mIsActionBarBelowLOLLIPOP) {\n mActionBarHeight = mBarConfig.getActionBarHeight();\n }\n }\n\n @Override\n public void onNavigationBarChange(boolean show, NavigationBarType type) {\n View navigationBarView = mDecorView.findViewById(IMMERSION_NAVIGATION_BAR_VIEW_ID);\n if (navigationBarView != null) {\n mBarConfig = new BarConfig(mActivity);\n int bottom = mContentView.getPaddingBottom(), right = mContentView.getPaddingRight();\n if (!show) {\n //导航键隐藏了\n navigationBarView.setVisibility(View.GONE);\n bottom = 0;\n right = 0;\n } else {\n //导航键显示了\n navigationBarView.setVisibility(View.VISIBLE);\n if (checkFitsSystemWindows(mDecorView.findViewById(android.R.id.content))) {\n bottom = 0;\n right = 0;\n } else {\n if (mNavigationBarHeight == 0) {\n mNavigationBarHeight = mBarConfig.getNavigationBarHeight();\n }\n if (mNavigationBarWidth == 0) {\n mNavigationBarWidth = mBarConfig.getNavigationBarWidth();\n }\n if (!mBarParams.hideNavigationBar) {\n FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) navigationBarView.getLayoutParams();\n if (mBarConfig.isNavigationAtBottom()) {\n params.gravity = Gravity.BOTTOM;\n params.height = mNavigationBarHeight;\n bottom = !mBarParams.fullScreen ? mNavigationBarHeight : 0;\n right = 0;\n } else {\n params.gravity = Gravity.END;\n params.width = mNavigationBarWidth;\n bottom = 0;\n right = !mBarParams.fullScreen ? mNavigationBarWidth : 0;\n }\n navigationBarView.setLayoutParams(params);\n }\n }\n }\n setPadding(0, mContentView.getPaddingTop(), right, bottom);\n }\n }\n\n /**\n * Sets status bar dark font.\n * 设置状态栏字体颜色,android6.0以上\n */\n private int setStatusBarDarkFont(int uiFlags) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {\n if (mBarParams.statusBarDarkFont) {\n return uiFlags | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;\n } else {\n return uiFlags;\n }\n } else {\n return uiFlags;\n }\n }\n\n /**\n * 设置导航栏图标亮色与暗色\n * Sets dark navigation icon.\n */\n private int setNavigationIconDark(int uiFlags) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {\n if (mBarParams.navigationBarDarkIcon) {\n return uiFlags | View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR;\n } else {\n return uiFlags;\n }\n } else {\n return uiFlags;\n }\n }\n\n @RequiresApi(api = Build.VERSION_CODES.R)\n private void setStatusBarDarkFontAboveR() {\n WindowInsetsController windowInsetsController = mContentView.getWindowInsetsController();\n if (mBarParams.statusBarDarkFont) {\n if (mWindow != null) {\n unsetSystemUiFlag(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);\n }\n windowInsetsController.setSystemBarsAppearance(\n WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS,\n WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS);\n } else {\n windowInsetsController.setSystemBarsAppearance(\n 0,\n WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS);\n }\n }\n\n @RequiresApi(api = Build.VERSION_CODES.R)\n private void setNavigationIconDarkAboveR() {\n WindowInsetsController controller = mContentView.getWindowInsetsController();\n if (mBarParams.navigationBarDarkIcon) {\n controller.setSystemBarsAppearance(\n WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS,\n WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS);\n } else {\n controller.setSystemBarsAppearance(\n 0,\n WindowInsetsController.APPEARANCE_LIGHT_NAVIGATION_BARS);\n }\n }\n\n private void hideBarAboveR() {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {\n WindowInsetsControllerCompat controller = ViewCompat.getWindowInsetsController(mContentView);\n if (controller != null) {\n switch (mBarParams.barHide) {\n case FLAG_HIDE_BAR:\n controller.hide(WindowInsetsCompat.Type.statusBars());\n controller.hide(WindowInsetsCompat.Type.navigationBars());\n break;\n case FLAG_HIDE_STATUS_BAR:\n controller.hide(WindowInsetsCompat.Type.statusBars());\n break;\n case FLAG_HIDE_NAVIGATION_BAR:\n controller.hide(WindowInsetsCompat.Type.navigationBars());\n break;\n case FLAG_SHOW_BAR:\n controller.show(WindowInsetsCompat.Type.statusBars());\n controller.show(WindowInsetsCompat.Type.navigationBars());\n break;\n default:\n break;\n }\n controller.setSystemBarsBehavior(WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE);\n }\n }\n }\n\n protected void unsetSystemUiFlag(int systemUiFlag) {\n View decorView = mWindow.getDecorView();\n decorView.setSystemUiVisibility(\n decorView.getSystemUiVisibility()\n & ~systemUiFlag);\n }\n\n /**\n * 适配状态栏与布局重叠问题\n * Fits layout overlap.\n */\n private void fitsLayoutOverlap() {\n int fixHeight = 0;\n if (mBarParams.fitsLayoutOverlapEnable) {\n fixHeight = mBarConfig.getStatusBarHeight();\n }\n switch (mFitsStatusBarType) {\n case FLAG_FITS_TITLE:\n //通过设置paddingTop重新绘制标题栏高度\n setTitleBar(mActivity, fixHeight, mBarParams.titleBarView);\n break;\n case FLAG_FITS_TITLE_MARGIN_TOP:\n //通过设置marginTop重新绘制标题栏高度\n setTitleBarMarginTop(mActivity, fixHeight, mBarParams.titleBarView);\n break;\n case FLAG_FITS_STATUS:\n //通过状态栏高度动态设置状态栏布局\n setStatusBarView(mActivity, fixHeight, mBarParams.statusBarView);\n break;\n default:\n break;\n }\n }\n\n /**\n * 变色view\n * Transform view.\n */\n private void transformView() {\n if (mBarParams.viewMap.size() != 0) {\n Set<Map.Entry<View, Map<Integer, Integer>>> entrySet = mBarParams.viewMap.entrySet();\n for (Map.Entry<View, Map<Integer, Integer>> entry : entrySet) {\n View view = entry.getKey();\n Map<Integer, Integer> map = entry.getValue();\n Integer colorBefore = mBarParams.statusBarColor;\n Integer colorAfter = mBarParams.statusBarColorTransform;\n for (Map.Entry<Integer, Integer> integerEntry : map.entrySet()) {\n colorBefore = integerEntry.getKey();\n colorAfter = integerEntry.getValue();\n }\n if (view != null) {\n if (Math.abs(mBarParams.viewAlpha - 0.0f) == 0) {\n view.setBackgroundColor(ColorUtils.blendARGB(colorBefore, colorAfter, mBarParams.statusBarAlpha));\n } else {\n view.setBackgroundColor(ColorUtils.blendARGB(colorBefore, colorAfter, mBarParams.viewAlpha));\n }\n }\n }\n }\n }\n\n /**\n * 取消注册emui3.x导航栏监听函数和软键盘监听\n * Cancel listener.\n */\n private void cancelListener() {\n if (mActivity != null) {\n if (mFitsKeyboard != null) {\n mFitsKeyboard.cancel();\n mFitsKeyboard = null;\n }\n EMUI3NavigationBarObserver.getInstance().removeOnNavigationBarListener(this);\n NavigationBarObserver.getInstance().removeOnNavigationBarListener(mBarParams.onNavigationBarListener);\n }\n }\n\n /**\n * 解决底部输入框与软键盘问题\n * Keyboard enable.\n */\n private void fitsKeyboard() {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {\n if (!mIsFragment) {\n if (mBarParams.keyboardEnable) {\n if (mFitsKeyboard == null) {\n mFitsKeyboard = new FitsKeyboard(this);\n }\n mFitsKeyboard.enable(mBarParams.keyboardMode);\n } else {\n if (mFitsKeyboard != null) {\n mFitsKeyboard.disable();\n }\n }\n } else {\n if (mParentBar != null) {\n if (mParentBar.mBarParams.keyboardEnable) {\n if (mParentBar.mFitsKeyboard == null) {\n mParentBar.mFitsKeyboard = new FitsKeyboard(mParentBar);\n }\n mParentBar.mFitsKeyboard.enable(mParentBar.mBarParams.keyboardMode);\n } else {\n if (mParentBar.mFitsKeyboard != null) {\n mParentBar.mFitsKeyboard.disable();\n }\n }\n }\n }\n }\n }\n\n void fitsParentBarKeyboard() {\n if (mParentBar != null && mParentBar.mFitsKeyboard != null) {\n mParentBar.mFitsKeyboard.disable();\n mParentBar.mFitsKeyboard.resetKeyboardHeight();\n }\n }\n\n /**\n * Gets bar params.\n *\n * @return the bar params\n */\n public BarParams getBarParams() {\n return mBarParams;\n }\n\n private void setPadding(int left, int top, int right, int bottom) {\n if (mContentView != null) {\n mContentView.setPadding(left, top, right, bottom);\n }\n mPaddingLeft = left;\n mPaddingTop = top;\n mPaddingRight = right;\n mPaddingBottom = bottom;\n }\n\n /**\n * Gets padding left.\n *\n * @return the padding left\n */\n int getPaddingLeft() {\n return mPaddingLeft;\n }\n\n /**\n * Gets padding top.\n *\n * @return the padding top\n */\n int getPaddingTop() {\n return mPaddingTop;\n }\n\n /**\n * Gets padding right.\n *\n * @return the padding right\n */\n int getPaddingRight() {\n return mPaddingRight;\n }\n\n /**\n * Gets padding bottom.\n *\n * @return the padding bottom\n */\n int getPaddingBottom() {\n return mPaddingBottom;\n }\n\n Activity getActivity() {\n return mActivity;\n }\n\n Window getWindow() {\n return mWindow;\n }\n\n Fragment getSupportFragment() {\n return mSupportFragment;\n }\n\n android.app.Fragment getFragment() {\n return mFragment;\n }\n\n /**\n * 是否是在Fragment的使用的\n *\n * @return the boolean\n */\n boolean isFragment() {\n return mIsFragment;\n }\n\n boolean isDialogFragment() {\n return mIsDialogFragment;\n }\n\n /**\n * 是否已经调用过init()方法了\n */\n boolean initialized() {\n return mInitialized;\n }\n\n BarConfig getBarConfig() {\n if (mBarConfig == null) {\n mBarConfig = new BarConfig(mActivity);\n }\n return mBarConfig;\n }\n\n\n int getActionBarHeight() {\n return mActionBarHeight;\n }\n\n /**\n * 判断手机支不支持状态栏字体变色\n * Is support status bar dark font boolean.\n *\n * @return the boolean\n */\n public static boolean isSupportStatusBarDarkFont() {\n return OSUtils.isMIUI6Later() || OSUtils.isFlymeOS4Later()\n || (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M);\n }\n\n /**\n * 判断导航栏图标是否支持变色\n * Is support navigation icon dark boolean.\n *\n * @return the boolean\n */\n public static boolean isSupportNavigationIconDark() {\n return OSUtils.isMIUI6Later() || Build.VERSION.SDK_INT >= Build.VERSION_CODES.O;\n }\n\n /**\n * 为标题栏paddingTop和高度增加fixHeight的高度\n * Sets title bar.\n *\n * @param activity the activity\n * @param fixHeight the fix height\n * @param view the view\n */\n public static void setTitleBar(final Activity activity, int fixHeight, View... view) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {\n if (activity == null) {\n return;\n }\n if (fixHeight < 0) {\n fixHeight = 0;\n }\n for (final View v : view) {\n if (v == null) {\n continue;\n }\n final int statusBarHeight = fixHeight;\n Integer fitsHeight = (Integer) v.getTag(R.id.immersion_fits_layout_overlap);\n if (fitsHeight == null) {\n fitsHeight = 0;\n }\n if (fitsHeight != statusBarHeight) {\n v.setTag(R.id.immersion_fits_layout_overlap, statusBarHeight);\n ViewGroup.LayoutParams layoutParams = v.getLayoutParams();\n if (layoutParams == null) {\n layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);\n }\n if (layoutParams.height == ViewGroup.LayoutParams.WRAP_CONTENT ||\n layoutParams.height == ViewGroup.LayoutParams.MATCH_PARENT) {\n final ViewGroup.LayoutParams finalLayoutParams = layoutParams;\n final Integer finalFitsHeight = fitsHeight;\n v.post(new Runnable() {\n @Override\n public void run() {\n finalLayoutParams.height = v.getHeight() + statusBarHeight - finalFitsHeight;\n v.setPadding(v.getPaddingLeft(),\n v.getPaddingTop() + statusBarHeight - finalFitsHeight,\n v.getPaddingRight(),\n v.getPaddingBottom());\n v.setLayoutParams(finalLayoutParams);\n }\n });\n } else {\n layoutParams.height += statusBarHeight - fitsHeight;\n v.setPadding(v.getPaddingLeft(), v.getPaddingTop() + statusBarHeight - fitsHeight,\n v.getPaddingRight(), v.getPaddingBottom());\n v.setLayoutParams(layoutParams);\n }\n }\n }\n }\n }\n\n /**\n * 为标题栏paddingTop和高度增加状态栏的高度\n * Sets title bar.\n *\n * @param activity the activity\n * @param view the view\n */\n public static void setTitleBar(final Activity activity, View... view) {\n setTitleBar(activity, getStatusBarHeight(activity), view);\n }\n\n public static void setTitleBar(Fragment fragment, int fixHeight, View... view) {\n if (fragment == null) {\n return;\n }\n setTitleBar(fragment.getActivity(), fixHeight, view);\n }\n\n public static void setTitleBar(Fragment fragment, View... view) {\n if (fragment == null) {\n return;\n }\n setTitleBar(fragment.getActivity(), view);\n }\n\n public static void setTitleBar(android.app.Fragment fragment, int fixHeight, View... view) {\n if (fragment == null) {\n return;\n }\n setTitleBar(fragment.getActivity(), fixHeight, view);\n }\n\n public static void setTitleBar(android.app.Fragment fragment, View... view) {\n if (fragment == null) {\n return;\n }\n setTitleBar(fragment.getActivity(), view);\n }\n\n /**\n * 为标题栏marginTop增加fixHeight的高度\n * Sets title bar margin top.\n *\n * @param activity the activity\n * @param fixHeight the fix height\n * @param view the view\n */\n public static void setTitleBarMarginTop(Activity activity, int fixHeight, View... view) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {\n if (activity == null) {\n return;\n }\n if (fixHeight < 0) {\n fixHeight = 0;\n }\n for (View v : view) {\n if (v == null) {\n continue;\n }\n Integer fitsHeight = (Integer) v.getTag(R.id.immersion_fits_layout_overlap);\n if (fitsHeight == null) {\n fitsHeight = 0;\n }\n if (fitsHeight != fixHeight) {\n v.setTag(R.id.immersion_fits_layout_overlap, fixHeight);\n ViewGroup.LayoutParams lp = v.getLayoutParams();\n if (lp == null) {\n lp = new ViewGroup.MarginLayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);\n }\n ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) lp;\n layoutParams.setMargins(layoutParams.leftMargin,\n layoutParams.topMargin + fixHeight - fitsHeight,\n layoutParams.rightMargin,\n layoutParams.bottomMargin);\n v.setLayoutParams(layoutParams);\n }\n }\n }\n }\n\n /**\n * 为标题栏marginTop增加状态栏的高度\n * Sets title bar margin top.\n *\n * @param activity the activity\n * @param view the view\n */\n public static void setTitleBarMarginTop(Activity activity, View... view) {\n setTitleBarMarginTop(activity, getStatusBarHeight(activity), view);\n }\n\n public static void setTitleBarMarginTop(Fragment fragment, int fixHeight, View... view) {\n if (fragment == null) {\n return;\n }\n setTitleBarMarginTop(fragment.getActivity(), fixHeight, view);\n }\n\n public static void setTitleBarMarginTop(Fragment fragment, View... view) {\n if (fragment == null) {\n return;\n }\n setTitleBarMarginTop(fragment.getActivity(), view);\n }\n\n public static void setTitleBarMarginTop(android.app.Fragment fragment, int fixHeight, View...\n view) {\n if (fragment == null) {\n return;\n }\n setTitleBarMarginTop(fragment.getActivity(), fixHeight, view);\n }\n\n public static void setTitleBarMarginTop(android.app.Fragment fragment, View... view) {\n if (fragment == null) {\n return;\n }\n setTitleBarMarginTop(fragment.getActivity(), view);\n }\n\n /**\n * 单独在标题栏的位置增加view,高度为fixHeight的高度\n * Sets status bar view.\n *\n * @param activity the activity\n * @param fixHeight the fix height\n * @param view the view\n */\n public static void setStatusBarView(Activity activity, int fixHeight, View... view) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {\n if (activity == null) {\n return;\n }\n if (fixHeight < 0) {\n fixHeight = 0;\n }\n for (View v : view) {\n if (v == null) {\n continue;\n }\n Integer fitsHeight = (Integer) v.getTag(R.id.immersion_fits_layout_overlap);\n if (fitsHeight == null) {\n fitsHeight = 0;\n }\n if (fitsHeight != fixHeight) {\n v.setTag(R.id.immersion_fits_layout_overlap, fixHeight);\n ViewGroup.LayoutParams lp = v.getLayoutParams();\n if (lp == null) {\n lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0);\n }\n lp.height = fixHeight;\n v.setLayoutParams(lp);\n }\n }\n }\n }\n\n /**\n * 单独在标题栏的位置增加view,高度为状态栏的高度\n * Sets status bar view.\n *\n * @param activity the activity\n * @param view the view\n */\n public static void setStatusBarView(Activity activity, View... view) {\n setStatusBarView(activity, getStatusBarHeight(activity), view);\n }\n\n public static void setStatusBarView(Fragment fragment, int fixHeight, View... view) {\n if (fragment == null) {\n return;\n }\n setStatusBarView(fragment.getActivity(), fixHeight, view);\n }\n\n public static void setStatusBarView(Fragment fragment, View... view) {\n if (fragment == null) {\n return;\n }\n setStatusBarView(fragment.getActivity(), view);\n }\n\n public static void setStatusBarView(android.app.Fragment fragment, int fixHeight, View...\n view) {\n if (fragment == null) {\n return;\n }\n setStatusBarView(fragment.getActivity(), fixHeight, view);\n }\n\n public static void setStatusBarView(android.app.Fragment fragment, View... view) {\n if (fragment == null) {\n return;\n }\n setStatusBarView(fragment.getActivity(), view);\n }\n\n /**\n * 调用系统view的setFitsSystemWindows方法\n * Sets fits system windows.\n *\n * @param activity the activity\n * @param applySystemFits the apply system fits\n */\n public static void setFitsSystemWindows(Activity activity, boolean applySystemFits) {\n if (activity == null) {\n return;\n }\n setFitsSystemWindows(((ViewGroup) activity.findViewById(android.R.id.content)).getChildAt(0), applySystemFits);\n }\n\n public static void setFitsSystemWindows(Activity activity) {\n setFitsSystemWindows(activity, true);\n }\n\n public static void setFitsSystemWindows(Fragment fragment, boolean applySystemFits) {\n if (fragment == null) {\n return;\n }\n setFitsSystemWindows(fragment.getActivity(), applySystemFits);\n }\n\n public static void setFitsSystemWindows(Fragment fragment) {\n if (fragment == null) {\n return;\n }\n setFitsSystemWindows(fragment.getActivity());\n }\n\n public static void setFitsSystemWindows(android.app.Fragment fragment, boolean applySystemFits) {\n if (fragment == null) {\n return;\n }\n setFitsSystemWindows(fragment.getActivity(), applySystemFits);\n }\n\n public static void setFitsSystemWindows(android.app.Fragment fragment) {\n if (fragment == null) {\n return;\n }\n setFitsSystemWindows(fragment.getActivity());\n }\n\n private static void setFitsSystemWindows(View view, boolean applySystemFits) {\n if (view == null) {\n return;\n }\n if (view instanceof ViewGroup) {\n ViewGroup viewGroup = (ViewGroup) view;\n if (viewGroup instanceof DrawerLayout) {\n setFitsSystemWindows(viewGroup.getChildAt(0), applySystemFits);\n } else {\n viewGroup.setFitsSystemWindows(applySystemFits);\n viewGroup.setClipToPadding(true);\n }\n } else {\n view.setFitsSystemWindows(applySystemFits);\n }\n }\n\n /**\n * 检查布局根节点是否使用了android:fitsSystemWindows=\"true\"属性\n * Check fits system windows boolean.\n *\n * @param view the view\n * @return the boolean\n */\n public static boolean checkFitsSystemWindows(View view) {\n if (view == null) {\n return false;\n }\n if (view.getFitsSystemWindows()) {\n return true;\n }\n if (view instanceof ViewGroup) {\n ViewGroup viewGroup = (ViewGroup) view;\n for (int i = 0, count = viewGroup.getChildCount(); i < count; i++) {\n View childView = viewGroup.getChildAt(i);\n if (childView instanceof DrawerLayout) {\n if (checkFitsSystemWindows(childView)) {\n return true;\n }\n }\n if (childView.getFitsSystemWindows()) {\n return true;\n }\n }\n }\n return false;\n }\n\n /**\n * Has navigtion bar boolean.\n * 判断是否存在导航栏\n *\n * @param activity the activity\n * @return the boolean\n */\n @TargetApi(14)\n public static boolean hasNavigationBar(@NonNull Activity activity) {\n BarConfig config = new BarConfig(activity);\n return config.hasNavigationBar();\n }\n\n @TargetApi(14)\n public static boolean hasNavigationBar(@NonNull Fragment fragment) {\n if (fragment.getActivity() == null) {\n return false;\n }\n return hasNavigationBar(fragment.getActivity());\n }\n\n @TargetApi(14)\n public static boolean hasNavigationBar(@NonNull android.app.Fragment fragment) {\n if (fragment.getActivity() == null) {\n return false;\n }\n return hasNavigationBar(fragment.getActivity());\n }\n\n @TargetApi(14)\n public static boolean hasNavigationBar(@NonNull Context context) {\n return getNavigationBarHeight(context) > 0;\n }\n\n /**\n * Gets navigation bar height.\n * 获得导航栏的高度\n *\n * @param activity the activity\n * @return the navigation bar height\n */\n @TargetApi(14)\n public static int getNavigationBarHeight(@NonNull Activity activity) {\n BarConfig config = new BarConfig(activity);\n return config.getNavigationBarHeight();\n }\n\n @TargetApi(14)\n public static int getNavigationBarHeight(@NonNull Fragment fragment) {\n if (fragment.getActivity() == null) {\n return 0;\n }\n return getNavigationBarHeight(fragment.getActivity());\n }\n\n @TargetApi(14)\n public static int getNavigationBarHeight(@NonNull android.app.Fragment fragment) {\n if (fragment.getActivity() == null) {\n return 0;\n }\n return getNavigationBarHeight(fragment.getActivity());\n }\n\n @TargetApi(14)\n public static int getNavigationBarHeight(@NonNull Context context) {\n GestureUtils.GestureBean bean = GestureUtils.getGestureBean(context);\n if (bean.isGesture && !bean.checkNavigation) {\n return 0;\n } else {\n return BarConfig.getNavigationBarHeightInternal(context);\n }\n }\n\n /**\n * Gets navigation bar width.\n * 获得导航栏的宽度\n *\n * @param activity the activity\n * @return the navigation bar width\n */\n @TargetApi(14)\n public static int getNavigationBarWidth(@NonNull Activity activity) {\n BarConfig config = new BarConfig(activity);\n return config.getNavigationBarWidth();\n }\n\n @TargetApi(14)\n public static int getNavigationBarWidth(@NonNull Fragment fragment) {\n if (fragment.getActivity() == null) {\n return 0;\n }\n return getNavigationBarWidth(fragment.getActivity());\n }\n\n @TargetApi(14)\n public static int getNavigationBarWidth(@NonNull android.app.Fragment fragment) {\n if (fragment.getActivity() == null) {\n return 0;\n }\n return getNavigationBarWidth(fragment.getActivity());\n }\n\n @TargetApi(14)\n public static int getNavigationBarWidth(@NonNull Context context) {\n GestureUtils.GestureBean bean = GestureUtils.getGestureBean(context);\n if (bean.isGesture && !bean.checkNavigation) {\n return 0;\n } else {\n return BarConfig.getNavigationBarWidthInternal(context);\n }\n }\n\n /**\n * Is navigation at bottom boolean.\n * 判断导航栏是否在底部\n *\n * @param activity the activity\n * @return the boolean\n */\n @TargetApi(14)\n public static boolean isNavigationAtBottom(@NonNull Activity activity) {\n BarConfig config = new BarConfig(activity);\n return config.isNavigationAtBottom();\n }\n\n @TargetApi(14)\n public static boolean isNavigationAtBottom(@NonNull Fragment fragment) {\n if (fragment.getActivity() == null) {\n return false;\n }\n return isNavigationAtBottom(fragment.getActivity());\n }\n\n @TargetApi(14)\n public static boolean isNavigationAtBottom(@NonNull android.app.Fragment fragment) {\n if (fragment.getActivity() == null) {\n return false;\n }\n return isNavigationAtBottom(fragment.getActivity());\n }\n\n /**\n * Gets status bar height.\n * 或得状态栏的高度\n *\n * @param activity the activity\n * @return the status bar height\n */\n @TargetApi(14)\n public static int getStatusBarHeight(@NonNull Activity activity) {\n BarConfig config = new BarConfig(activity);\n return config.getStatusBarHeight();\n }\n\n @TargetApi(14)\n public static int getStatusBarHeight(@NonNull Fragment fragment) {\n if (fragment.getActivity() == null) {\n return 0;\n }\n return getStatusBarHeight(fragment.getActivity());\n }\n\n @TargetApi(14)\n public static int getStatusBarHeight(@NonNull android.app.Fragment fragment) {\n if (fragment.getActivity() == null) {\n return 0;\n }\n return getStatusBarHeight(fragment.getActivity());\n }\n\n @TargetApi(14)\n public static int getStatusBarHeight(@NonNull Context context) {\n return BarConfig.getInternalDimensionSize(context, Constants.IMMERSION_STATUS_BAR_HEIGHT);\n }\n\n /**\n * Gets action bar height.\n * 或得ActionBar得高度\n *\n * @param activity the activity\n * @return the action bar height\n */\n @TargetApi(14)\n public static int getActionBarHeight(@NonNull Activity activity) {\n BarConfig config = new BarConfig(activity);\n return config.getActionBarHeight();\n }\n\n @TargetApi(14)\n public static int getActionBarHeight(@NonNull Fragment fragment) {\n if (fragment.getActivity() == null) {\n return 0;\n }\n return getActionBarHeight(fragment.getActivity());\n }\n\n @TargetApi(14)\n public static int getActionBarHeight(@NonNull android.app.Fragment fragment) {\n if (fragment.getActivity() == null) {\n return 0;\n }\n return getActionBarHeight(fragment.getActivity());\n }\n\n /**\n * 是否是刘海屏\n * Has notch screen boolean.\n * e.g:getWindow().getDecorView().post(() -> ImmersionBar.hasNotchScreen(this));\n *\n * @param activity the activity\n * @return the boolean\n */\n public static boolean hasNotchScreen(@NonNull Activity activity) {\n return NotchUtils.hasNotchScreen(activity);\n }\n\n public static boolean hasNotchScreen(@NonNull Fragment fragment) {\n if (fragment.getActivity() == null) {\n return false;\n }\n return hasNotchScreen(fragment.getActivity());\n }\n\n public static boolean hasNotchScreen(@NonNull android.app.Fragment fragment) {\n if (fragment.getActivity() == null) {\n return false;\n }\n return hasNotchScreen(fragment.getActivity());\n }\n\n /**\n * 是否是刘海屏\n * Has notch screen boolean.\n *\n * @param view the view\n * @return the boolean\n */\n public static boolean hasNotchScreen(@NonNull View view) {\n return NotchUtils.hasNotchScreen(view);\n }\n\n /**\n * 刘海屏高度\n * Notch height int.\n * e.g: getWindow().getDecorView().post(() -> ImmersionBar.getNotchHeight(this));\n *\n * @param activity the activity\n * @return the int\n */\n public static int getNotchHeight(@NonNull Activity activity) {\n return NotchUtils.getNotchHeight(activity);\n }\n\n public static int getNotchHeight(@NonNull Fragment fragment) {\n if (fragment.getActivity() == null) {\n return 0;\n }\n return getNotchHeight(fragment.getActivity());\n }\n\n public static int getNotchHeight(@NonNull android.app.Fragment fragment) {\n if (fragment.getActivity() == null) {\n return 0;\n }\n return getNotchHeight(fragment.getActivity());\n }\n\n public static void getNotchHeight(@NonNull Activity activity, NotchCallback callback) {\n NotchUtils.getNotchHeight(activity, callback);\n }\n\n public static void getNotchHeight(@NonNull Fragment fragment, NotchCallback callback) {\n if (fragment.getActivity() == null) {\n return;\n }\n getNotchHeight(fragment.getActivity(), callback);\n }\n\n public static void getNotchHeight(@NonNull android.app.Fragment fragment, NotchCallback callback) {\n if (fragment.getActivity() == null) {\n return;\n }\n getNotchHeight(fragment.getActivity(), callback);\n }\n\n /**\n * 隐藏状态栏\n * Hide status bar.\n *\n * @param window the window\n */\n public static void hideStatusBar(@NonNull Window window) {\n window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,\n WindowManager.LayoutParams.FLAG_FULLSCREEN);\n }\n\n /**\n * 显示状态栏\n * Show status bar.\n *\n * @param window the window\n */\n public static void showStatusBar(@NonNull Window window) {\n window.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);\n }\n\n /**\n * 是否是手势\n *\n * @param context Context\n * @return the boolean\n */\n public static boolean isGesture(Context context) {\n return GestureUtils.getGestureBean(context).isGesture;\n }\n\n /**\n * 是否是手势\n *\n * @param fragment Fragment\n * @return the boolean\n */\n public static boolean isGesture(Fragment fragment) {\n Context context = fragment.getContext();\n if (context == null) return false;\n return isGesture(context);\n }\n\n /**\n * 是否是手势\n *\n * @param fragment android.app.Fragment\n * @return the boolean\n */\n public static boolean isGesture(android.app.Fragment fragment) {\n Context context = null;\n if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {\n context = fragment.getContext();\n }\n if (context == null) return false;\n return isGesture(context);\n }\n\n /**\n * 在Activity里初始化\n * Instantiates a new Immersion bar.\n *\n * @param activity the activity\n */\n ImmersionBar(Activity activity) {\n mActivity = activity;\n initCommonParameter(mActivity.getWindow());\n }\n\n /**\n * 在Fragment里初始化\n * Instantiates a new Immersion bar.\n *\n * @param fragment the fragment\n */\n ImmersionBar(Fragment fragment) {\n mIsFragment = true;\n mActivity = fragment.getActivity();\n mSupportFragment = fragment;\n checkInitWithActivity();\n initCommonParameter(mActivity.getWindow());\n }\n\n /**\n * 在Fragment里初始化\n * Instantiates a new Immersion bar.\n *\n * @param fragment the fragment\n */\n ImmersionBar(android.app.Fragment fragment) {\n mIsFragment = true;\n mActivity = fragment.getActivity();\n mFragment = fragment;\n checkInitWithActivity();\n initCommonParameter(mActivity.getWindow());\n }\n\n /**\n * 在dialogFragment里使用\n * Instantiates a new Immersion bar.\n *\n * @param dialogFragment the dialog fragment\n */\n ImmersionBar(DialogFragment dialogFragment) {\n mIsDialog = true;\n mIsDialogFragment = true;\n mActivity = dialogFragment.getActivity();\n mSupportFragment = dialogFragment;\n mDialog = dialogFragment.getDialog();\n checkInitWithActivity();\n initCommonParameter(mDialog.getWindow());\n }\n\n /**\n * 在dialogFragment里使用\n * Instantiates a new Immersion bar.\n *\n * @param dialogFragment the dialog fragment\n */\n ImmersionBar(android.app.DialogFragment dialogFragment) {\n mIsDialog = true;\n mIsDialogFragment = true;\n mActivity = dialogFragment.getActivity();\n mFragment = dialogFragment;\n mDialog = dialogFragment.getDialog();\n checkInitWithActivity();\n initCommonParameter(mDialog.getWindow());\n }\n\n /**\n * 在Dialog里初始化\n * Instantiates a new Immersion bar.\n *\n * @param activity the activity\n * @param dialog the dialog\n */\n ImmersionBar(Activity activity, Dialog dialog) {\n mIsDialog = true;\n mActivity = activity;\n mDialog = dialog;\n checkInitWithActivity();\n initCommonParameter(mDialog.getWindow());\n }\n\n /**\n * 检查是否已经在Activity中初始化了,未初始化则自动初始化\n */\n private void checkInitWithActivity() {\n if (mParentBar == null) {\n mParentBar = with(mActivity);\n }\n if (mParentBar != null && !mParentBar.mInitialized) {\n mParentBar.init();\n }\n }\n\n /**\n * 初始化共同参数\n *\n * @param window window\n */\n private void initCommonParameter(Window window) {\n mWindow = window;\n mBarParams = new BarParams();\n mDecorView = (ViewGroup) mWindow.getDecorView();\n mContentView = mDecorView.findViewById(android.R.id.content);\n }\n\n /**\n * 透明状态栏,默认透明\n *\n * @return the immersion bar\n */\n public ImmersionBar transparentStatusBar() {\n mBarParams.statusBarColor = Color.TRANSPARENT;\n return this;\n }\n\n /**\n * 透明导航栏,默认黑色\n *\n * @return the immersion bar\n */\n public ImmersionBar transparentNavigationBar() {\n mBarParams.navigationBarColor = Color.TRANSPARENT;\n mBarParams.fullScreen = true;\n return this;\n }\n\n /**\n * 透明状态栏和导航栏\n *\n * @return the immersion bar\n */\n public ImmersionBar transparentBar() {\n mBarParams.statusBarColor = Color.TRANSPARENT;\n mBarParams.navigationBarColor = Color.TRANSPARENT;\n mBarParams.fullScreen = true;\n return this;\n }\n\n /**\n * 状态栏颜色\n *\n * @param statusBarColor 状态栏颜色,资源文件(R.color.xxx)\n * @return the immersion bar\n */\n public ImmersionBar statusBarColor(@ColorRes int statusBarColor) {\n return this.statusBarColorInt(ContextCompat.getColor(mActivity, statusBarColor));\n }\n\n /**\n * 状态栏颜色\n *\n * @param statusBarColor 状态栏颜色,资源文件(R.color.xxx)\n * @param alpha the alpha 透明度\n * @return the immersion bar\n */\n public ImmersionBar statusBarColor(@ColorRes int statusBarColor,\n @FloatRange(from = 0f, to = 1f) float alpha) {\n return this.statusBarColorInt(ContextCompat.getColor(mActivity, statusBarColor), alpha);\n }\n\n /**\n * 状态栏颜色\n *\n * @param statusBarColor 状态栏颜色,资源文件(R.color.xxx)\n * @param statusBarColorTransform the status bar color transform 状态栏变换后的颜色\n * @param alpha the alpha 透明度\n * @return the immersion bar\n */\n public ImmersionBar statusBarColor(@ColorRes int statusBarColor,\n @ColorRes int statusBarColorTransform,\n @FloatRange(from = 0f, to = 1f) float alpha) {\n return this.statusBarColorInt(ContextCompat.getColor(mActivity, statusBarColor),\n ContextCompat.getColor(mActivity, statusBarColorTransform),\n alpha);\n }\n\n /**\n * 状态栏颜色\n * Status bar color int immersion bar.\n *\n * @param statusBarColor the status bar color\n * @return the immersion bar\n */\n public ImmersionBar statusBarColor(String statusBarColor) {\n return this.statusBarColorInt(Color.parseColor(statusBarColor));\n }\n\n /**\n * 状态栏颜色\n *\n * @param statusBarColor 状态栏颜色\n * @param alpha the alpha 透明度\n * @return the immersion bar\n */\n public ImmersionBar statusBarColor(String statusBarColor,\n @FloatRange(from = 0f, to = 1f) float alpha) {\n return this.statusBarColorInt(Color.parseColor(statusBarColor), alpha);\n }\n\n /**\n * 状态栏颜色\n *\n * @param statusBarColor 状态栏颜色\n * @param statusBarColorTransform the status bar color transform 状态栏变换后的颜色\n * @param alpha the alpha 透明度\n * @return the immersion bar\n */\n public ImmersionBar statusBarColor(String statusBarColor,\n String statusBarColorTransform,\n @FloatRange(from = 0f, to = 1f) float alpha) {\n return this.statusBarColorInt(Color.parseColor(statusBarColor),\n Color.parseColor(statusBarColorTransform),\n alpha);\n }\n\n /**\n * 状态栏颜色\n *\n * @param statusBarColor 状态栏颜色,资源文件(R.color.xxx)\n * @return the immersion bar\n */\n public ImmersionBar statusBarColorInt(@ColorInt int statusBarColor) {\n mBarParams.statusBarColor = statusBarColor;\n return this;\n }\n\n /**\n * 状态栏颜色\n *\n * @param statusBarColor 状态栏颜色,资源文件(R.color.xxx)\n * @param alpha the alpha 透明度\n * @return the immersion bar\n */\n public ImmersionBar statusBarColorInt(@ColorInt int statusBarColor,\n @FloatRange(from = 0f, to = 1f) float alpha) {\n mBarParams.statusBarColor = statusBarColor;\n mBarParams.statusBarAlpha = alpha;\n return this;\n }\n\n /**\n * 状态栏颜色\n *\n * @param statusBarColor 状态栏颜色,资源文件(R.color.xxx)\n * @param statusBarColorTransform the status bar color transform 状态栏变换后的颜色\n * @param alpha the alpha 透明度\n * @return the immersion bar\n */\n public ImmersionBar statusBarColorInt(@ColorInt int statusBarColor,\n @ColorInt int statusBarColorTransform,\n @FloatRange(from = 0f, to = 1f) float alpha) {\n mBarParams.statusBarColor = statusBarColor;\n mBarParams.statusBarColorTransform = statusBarColorTransform;\n mBarParams.statusBarAlpha = alpha;\n return this;\n }\n\n /**\n * 导航栏颜色\n *\n * @param navigationBarColor the navigation bar color 导航栏颜色\n * @return the immersion bar\n */\n public ImmersionBar navigationBarColor(@ColorRes int navigationBarColor) {\n return this.navigationBarColorInt(ContextCompat.getColor(mActivity, navigationBarColor));\n }\n\n /**\n * 导航栏颜色\n *\n * @param navigationBarColor the navigation bar color 导航栏颜色\n * @param navigationAlpha the navigation alpha 透明度\n * @return the immersion bar\n */\n public ImmersionBar navigationBarColor(@ColorRes int navigationBarColor,\n @FloatRange(from = 0f, to = 1f) float navigationAlpha) {\n return this.navigationBarColorInt(ContextCompat.getColor(mActivity, navigationBarColor), navigationAlpha);\n }\n\n /**\n * 导航栏颜色\n *\n * @param navigationBarColor the navigation bar color 导航栏颜色\n * @param navigationBarColorTransform the navigation bar color transform 导航栏变色后的颜色\n * @param navigationAlpha the navigation alpha 透明度\n * @return the immersion bar\n */\n public ImmersionBar navigationBarColor(@ColorRes int navigationBarColor,\n @ColorRes int navigationBarColorTransform,\n @FloatRange(from = 0f, to = 1f) float navigationAlpha) {\n return this.navigationBarColorInt(ContextCompat.getColor(mActivity, navigationBarColor),\n ContextCompat.getColor(mActivity, navigationBarColorTransform), navigationAlpha);\n }\n\n /**\n * 导航栏颜色\n *\n * @param navigationBarColor the navigation bar color 导航栏颜色\n * @return the immersion bar\n */\n public ImmersionBar navigationBarColor(String navigationBarColor) {\n return this.navigationBarColorInt(Color.parseColor(navigationBarColor));\n }\n\n /**\n * 导航栏颜色\n *\n * @param navigationBarColor the navigation bar color 导航栏颜色\n * @param navigationAlpha the navigation alpha 透明度\n * @return the immersion bar\n */\n public ImmersionBar navigationBarColor(String navigationBarColor,\n @FloatRange(from = 0f, to = 1f) float navigationAlpha) {\n return this.navigationBarColorInt(Color.parseColor(navigationBarColor), navigationAlpha);\n }\n\n /**\n * 导航栏颜色\n *\n * @param navigationBarColor the navigation bar color 导航栏颜色\n * @param navigationBarColorTransform the navigation bar color transform 导航栏变色后的颜色\n * @param navigationAlpha the navigation alpha 透明度\n * @return the immersion bar\n */\n public ImmersionBar navigationBarColor(String navigationBarColor,\n String navigationBarColorTransform,\n @FloatRange(from = 0f, to = 1f) float navigationAlpha) {\n return this.navigationBarColorInt(Color.parseColor(navigationBarColor),\n Color.parseColor(navigationBarColorTransform), navigationAlpha);\n }\n\n /**\n * 导航栏颜色\n *\n * @param navigationBarColor the navigation bar color 导航栏颜色\n * @return the immersion bar\n */\n public ImmersionBar navigationBarColorInt(@ColorInt int navigationBarColor) {\n mBarParams.navigationBarColor = navigationBarColor;\n return this;\n }\n\n /**\n * 导航栏颜色\n *\n * @param navigationBarColor the navigation bar color 导航栏颜色\n * @param navigationAlpha the navigation alpha 透明度\n * @return the immersion bar\n */\n public ImmersionBar navigationBarColorInt(@ColorInt int navigationBarColor,\n @FloatRange(from = 0f, to = 1f) float navigationAlpha) {\n mBarParams.navigationBarColor = navigationBarColor;\n mBarParams.navigationBarAlpha = navigationAlpha;\n return this;\n }\n\n /**\n * 导航栏颜色\n *\n * @param navigationBarColor the navigation bar color 导航栏颜色\n * @param navigationBarColorTransform the navigation bar color transform 导航栏变色后的颜色\n * @param navigationAlpha the navigation alpha 透明度\n * @return the immersion bar\n */\n public ImmersionBar navigationBarColorInt(@ColorInt int navigationBarColor,\n @ColorInt int navigationBarColorTransform,\n @FloatRange(from = 0f, to = 1f) float navigationAlpha) {\n mBarParams.navigationBarColor = navigationBarColor;\n mBarParams.navigationBarColorTransform = navigationBarColorTransform;\n mBarParams.navigationBarAlpha = navigationAlpha;\n return this;\n }\n\n /**\n * 状态栏和导航栏颜色\n *\n * @param barColor the bar color\n * @return the immersion bar\n */\n public ImmersionBar barColor(@ColorRes int barColor) {\n return this.barColorInt(ContextCompat.getColor(mActivity, barColor));\n }\n\n /**\n * 状态栏和导航栏颜色\n *\n * @param barColor the bar color\n * @param barAlpha the bar alpha\n * @return the immersion bar\n */\n public ImmersionBar barColor(@ColorRes int barColor, @FloatRange(from = 0f, to = 1f) float barAlpha) {\n return this.barColorInt(ContextCompat.getColor(mActivity, barColor), barColor);\n }\n\n /**\n * 状态栏和导航栏颜色\n *\n * @param barColor the bar color\n * @param barColorTransform the bar color transform\n * @param barAlpha the bar alpha\n * @return the immersion bar\n */\n public ImmersionBar barColor(@ColorRes int barColor,\n @ColorRes int barColorTransform,\n @FloatRange(from = 0f, to = 1f) float barAlpha) {\n return this.barColorInt(ContextCompat.getColor(mActivity, barColor),\n ContextCompat.getColor(mActivity, barColorTransform), barAlpha);\n }\n\n /**\n * 状态栏和导航栏颜色\n *\n * @param barColor the bar color\n * @return the immersion bar\n */\n public ImmersionBar barColor(String barColor) {\n return this.barColorInt(Color.parseColor(barColor));\n }\n\n /**\n * 状态栏和导航栏颜色\n *\n * @param barColor the bar color\n * @param barAlpha the bar alpha\n * @return the immersion bar\n */\n public ImmersionBar barColor(String barColor, @FloatRange(from = 0f, to = 1f) float barAlpha) {\n return this.barColorInt(Color.parseColor(barColor), barAlpha);\n }\n\n /**\n * 状态栏和导航栏颜色\n *\n * @param barColor the bar color\n * @param barColorTransform the bar color transform\n * @param barAlpha the bar alpha\n * @return the immersion bar\n */\n public ImmersionBar barColor(String barColor,\n String barColorTransform,\n @FloatRange(from = 0f, to = 1f) float barAlpha) {\n return this.barColorInt(Color.parseColor(barColor), Color.parseColor(barColorTransform), barAlpha);\n }\n\n /**\n * 状态栏和导航栏颜色\n *\n * @param barColor the bar color\n * @return the immersion bar\n */\n public ImmersionBar barColorInt(@ColorInt int barColor) {\n mBarParams.statusBarColor = barColor;\n mBarParams.navigationBarColor = barColor;\n return this;\n }\n\n /**\n * 状态栏和导航栏颜色\n *\n * @param barColor the bar color\n * @param barAlpha the bar alpha\n * @return the immersion bar\n */\n public ImmersionBar barColorInt(@ColorInt int barColor, @FloatRange(from = 0f, to = 1f) float barAlpha) {\n mBarParams.statusBarColor = barColor;\n mBarParams.navigationBarColor = barColor;\n mBarParams.statusBarAlpha = barAlpha;\n mBarParams.navigationBarAlpha = barAlpha;\n return this;\n }\n\n /**\n * 状态栏和导航栏颜色\n *\n * @param barColor the bar color\n * @param barColorTransform the bar color transform\n * @param barAlpha the bar alpha\n * @return the immersion bar\n */\n public ImmersionBar barColorInt(@ColorInt int barColor,\n @ColorInt int barColorTransform,\n @FloatRange(from = 0f, to = 1f) float barAlpha) {\n mBarParams.statusBarColor = barColor;\n mBarParams.navigationBarColor = barColor;\n\n mBarParams.statusBarColorTransform = barColorTransform;\n mBarParams.navigationBarColorTransform = barColorTransform;\n\n mBarParams.statusBarAlpha = barAlpha;\n mBarParams.navigationBarAlpha = barAlpha;\n return this;\n }\n\n\n /**\n * 状态栏根据透明度最后变换成的颜色\n *\n * @param statusBarColorTransform the status bar color transform\n * @return the immersion bar\n */\n public ImmersionBar statusBarColorTransform(@ColorRes int statusBarColorTransform) {\n return this.statusBarColorTransformInt(ContextCompat.getColor(mActivity, statusBarColorTransform));\n }\n\n /**\n * 状态栏根据透明度最后变换成的颜色\n *\n * @param statusBarColorTransform the status bar color transform\n * @return the immersion bar\n */\n public ImmersionBar statusBarColorTransform(String statusBarColorTransform) {\n return this.statusBarColorTransformInt(Color.parseColor(statusBarColorTransform));\n }\n\n /**\n * 状态栏根据透明度最后变换成的颜色\n *\n * @param statusBarColorTransform the status bar color transform\n * @return the immersion bar\n */\n public ImmersionBar statusBarColorTransformInt(@ColorInt int statusBarColorTransform) {\n mBarParams.statusBarColorTransform = statusBarColorTransform;\n return this;\n }\n\n /**\n * 导航栏根据透明度最后变换成的颜色\n *\n * @param navigationBarColorTransform the m navigation bar color transform\n * @return the immersion bar\n */\n public ImmersionBar navigationBarColorTransform(@ColorRes int navigationBarColorTransform) {\n return this.navigationBarColorTransformInt(ContextCompat.getColor(mActivity, navigationBarColorTransform));\n }\n\n /**\n * 导航栏根据透明度最后变换成的颜色\n *\n * @param navigationBarColorTransform the m navigation bar color transform\n * @return the immersion bar\n */\n public ImmersionBar navigationBarColorTransform(String navigationBarColorTransform) {\n return this.navigationBarColorTransformInt(Color.parseColor(navigationBarColorTransform));\n }\n\n /**\n * 导航栏根据透明度最后变换成的颜色\n *\n * @param navigationBarColorTransform the m navigation bar color transform\n * @return the immersion bar\n */\n public ImmersionBar navigationBarColorTransformInt(@ColorInt int navigationBarColorTransform) {\n mBarParams.navigationBarColorTransform = navigationBarColorTransform;\n return this;\n }\n\n /**\n * 状态栏和导航栏根据透明度最后变换成的颜色\n *\n * @param barColorTransform the bar color transform\n * @return the immersion bar\n */\n public ImmersionBar barColorTransform(@ColorRes int barColorTransform) {\n return this.barColorTransformInt(ContextCompat.getColor(mActivity, barColorTransform));\n }\n\n /**\n * 状态栏和导航栏根据透明度最后变换成的颜色\n *\n * @param barColorTransform the bar color transform\n * @return the immersion bar\n */\n public ImmersionBar barColorTransform(String barColorTransform) {\n return this.barColorTransformInt(Color.parseColor(barColorTransform));\n }\n\n /**\n * 状态栏和导航栏根据透明度最后变换成的颜色\n *\n * @param barColorTransform the bar color transform\n * @return the immersion bar\n */\n public ImmersionBar barColorTransformInt(@ColorInt int barColorTransform) {\n mBarParams.statusBarColorTransform = barColorTransform;\n mBarParams.navigationBarColorTransform = barColorTransform;\n return this;\n }\n\n /**\n * Add 颜色变换支持View\n *\n * @param view the view\n * @return the immersion bar\n */\n public ImmersionBar addViewSupportTransformColor(View view) {\n return this.addViewSupportTransformColorInt(view, mBarParams.statusBarColorTransform);\n }\n\n /**\n * Add 颜色变换支持View\n *\n * @param view the view\n * @param viewColorAfterTransform the view color after transform\n * @return the immersion bar\n */\n public ImmersionBar addViewSupportTransformColor(View view, @ColorRes int viewColorAfterTransform) {\n return this.addViewSupportTransformColorInt(view, ContextCompat.getColor(mActivity, viewColorAfterTransform));\n }\n\n /**\n * Add 颜色变换支持View\n *\n * @param view the view\n * @param viewColorBeforeTransform the view color before transform\n * @param viewColorAfterTransform the view color after transform\n * @return the immersion bar\n */\n public ImmersionBar addViewSupportTransformColor(View view, @ColorRes int viewColorBeforeTransform,\n @ColorRes int viewColorAfterTransform) {\n return this.addViewSupportTransformColorInt(view,\n ContextCompat.getColor(mActivity, viewColorBeforeTransform),\n ContextCompat.getColor(mActivity, viewColorAfterTransform));\n }\n\n /**\n * Add 颜色变换支持View\n *\n * @param view the view\n * @param viewColorAfterTransform the view color after transform\n * @return the immersion bar\n */\n public ImmersionBar addViewSupportTransformColor(View view, String viewColorAfterTransform) {\n return this.addViewSupportTransformColorInt(view, Color.parseColor(viewColorAfterTransform));\n }\n\n /**\n * Add 颜色变换支持View\n *\n * @param view the view\n * @param viewColorBeforeTransform the view color before transform\n * @param viewColorAfterTransform the view color after transform\n * @return the immersion bar\n */\n public ImmersionBar addViewSupportTransformColor(View view, String viewColorBeforeTransform,\n String viewColorAfterTransform) {\n return this.addViewSupportTransformColorInt(view,\n Color.parseColor(viewColorBeforeTransform),\n Color.parseColor(viewColorAfterTransform));\n }\n\n /**\n * Add 颜色变换支持View\n *\n * @param view the view\n * @param viewColorAfterTransform the view color after transform\n * @return the immersion bar\n */\n public ImmersionBar addViewSupportTransformColorInt(View view, @ColorInt int viewColorAfterTransform) {\n if (view == null) {\n throw new IllegalArgumentException(\"View参数不能为空\");\n }\n Map<Integer, Integer> map = new HashMap<>();\n map.put(mBarParams.statusBarColor, viewColorAfterTransform);\n mBarParams.viewMap.put(view, map);\n return this;\n }\n\n /**\n * Add 颜色变换支持View\n *\n * @param view the view\n * @param viewColorBeforeTransform the view color before transform\n * @param viewColorAfterTransform the view color after transform\n * @return the immersion bar\n */\n public ImmersionBar addViewSupportTransformColorInt(View view, @ColorInt int viewColorBeforeTransform,\n @ColorInt int viewColorAfterTransform) {\n if (view == null) {\n throw new IllegalArgumentException(\"View参数不能为空\");\n }\n Map<Integer, Integer> map = new HashMap<>();\n map.put(viewColorBeforeTransform, viewColorAfterTransform);\n mBarParams.viewMap.put(view, map);\n return this;\n }\n\n /**\n * view透明度\n * View alpha immersion bar.\n *\n * @param viewAlpha the view alpha\n * @return the immersion bar\n */\n public ImmersionBar viewAlpha(@FloatRange(from = 0f, to = 1f) float viewAlpha) {\n mBarParams.viewAlpha = viewAlpha;\n return this;\n }\n\n /**\n * Remove support view immersion bar.\n *\n * @param view the view\n * @return the immersion bar\n */\n public ImmersionBar removeSupportView(View view) {\n if (view == null) {\n throw new IllegalArgumentException(\"View参数不能为空\");\n }\n Map<Integer, Integer> map = mBarParams.viewMap.get(view);\n if (map != null && map.size() != 0) {\n mBarParams.viewMap.remove(view);\n }\n return this;\n }\n\n /**\n * Remove support all view immersion bar.\n *\n * @return the immersion bar\n */\n public ImmersionBar removeSupportAllView() {\n if (mBarParams.viewMap.size() != 0) {\n mBarParams.viewMap.clear();\n }\n return this;\n }\n\n /**\n * 有导航栏的情况下,Activity是否全屏显示\n *\n * @param isFullScreen the is full screen\n * @return the immersion bar\n */\n public ImmersionBar fullScreen(boolean isFullScreen) {\n mBarParams.fullScreen = isFullScreen;\n return this;\n }\n\n /**\n * 状态栏透明度\n *\n * @param statusAlpha the status alpha\n * @return the immersion bar\n */\n public ImmersionBar statusBarAlpha(@FloatRange(from = 0f, to = 1f) float statusAlpha) {\n mBarParams.statusBarAlpha = statusAlpha;\n mBarParams.statusBarTempAlpha = statusAlpha;\n return this;\n }\n\n /**\n * 导航栏透明度\n *\n * @param navigationAlpha the navigation alpha\n * @return the immersion bar\n */\n public ImmersionBar navigationBarAlpha(@FloatRange(from = 0f, to = 1f) float navigationAlpha) {\n mBarParams.navigationBarAlpha = navigationAlpha;\n mBarParams.navigationBarTempAlpha = navigationAlpha;\n return this;\n }\n\n /**\n * 状态栏和导航栏透明度\n *\n * @param barAlpha the bar alpha\n * @return the immersion bar\n */\n public ImmersionBar barAlpha(@FloatRange(from = 0f, to = 1f) float barAlpha) {\n mBarParams.statusBarAlpha = barAlpha;\n mBarParams.statusBarTempAlpha = barAlpha;\n mBarParams.navigationBarAlpha = barAlpha;\n mBarParams.navigationBarTempAlpha = barAlpha;\n return this;\n }\n\n /**\n * 是否启用 自动根据StatusBar和NavigationBar颜色调整深色模式与亮色模式\n *\n * @param isEnable true启用 默认false\n * @return the immersion bar\n */\n public ImmersionBar autoDarkModeEnable(boolean isEnable) {\n return this.autoDarkModeEnable(isEnable, 0.2f);\n }\n\n /**\n * 是否启用自动根据StatusBar和NavigationBar颜色调整深色模式与亮色模式\n * Auto dark mode enable immersion bar.\n *\n * @param isEnable the is enable\n * @param autoDarkModeAlpha the auto dark mode alpha\n * @return the immersion bar\n */\n public ImmersionBar autoDarkModeEnable(boolean isEnable, @FloatRange(from = 0f, to = 1f) float autoDarkModeAlpha) {\n mBarParams.autoStatusBarDarkModeEnable = isEnable;\n mBarParams.autoStatusBarDarkModeAlpha = autoDarkModeAlpha;\n mBarParams.autoNavigationBarDarkModeEnable = isEnable;\n mBarParams.autoNavigationBarDarkModeAlpha = autoDarkModeAlpha;\n return this;\n }\n\n /**\n * 是否启用自动根据StatusBar颜色调整深色模式与亮色模式\n * Auto status bar dark mode enable immersion bar.\n *\n * @param isEnable the is enable\n * @return the immersion bar\n */\n public ImmersionBar autoStatusBarDarkModeEnable(boolean isEnable) {\n return this.autoStatusBarDarkModeEnable(isEnable, 0.2f);\n }\n\n /**\n * 是否启用自动根据StatusBar颜色调整深色模式与亮色模式\n * Auto status bar dark mode enable immersion bar.\n *\n * @param isEnable the is enable\n * @param autoDarkModeAlpha the auto dark mode alpha\n * @return the immersion bar\n */\n public ImmersionBar autoStatusBarDarkModeEnable(boolean isEnable, @FloatRange(from = 0f, to = 1f) float autoDarkModeAlpha) {\n mBarParams.autoStatusBarDarkModeEnable = isEnable;\n mBarParams.autoStatusBarDarkModeAlpha = autoDarkModeAlpha;\n return this;\n }\n\n /**\n * 是否启用自动根据StatusBar颜色调整深色模式与亮色模式\n * Auto navigation bar dark mode enable immersion bar.\n *\n * @param isEnable the is enable\n * @return the immersion bar\n */\n public ImmersionBar autoNavigationBarDarkModeEnable(boolean isEnable) {\n return this.autoNavigationBarDarkModeEnable(isEnable, 0.2f);\n }\n\n /**\n * 是否启用自动根据NavigationBar颜色调整深色模式与亮色模式\n * Auto navigation bar dark mode enable immersion bar.\n *\n * @param isEnable the is enable\n * @param autoDarkModeAlpha the auto dark mode alpha\n * @return the immersion bar\n */\n public ImmersionBar autoNavigationBarDarkModeEnable(boolean isEnable, @FloatRange(from = 0f, to = 1f) float autoDarkModeAlpha) {\n mBarParams.autoNavigationBarDarkModeEnable = isEnable;\n mBarParams.autoNavigationBarDarkModeAlpha = autoDarkModeAlpha;\n return this;\n }\n\n /**\n * 状态栏字体深色或亮色\n *\n * @param isDarkFont true 深色\n * @return the immersion bar\n */\n public ImmersionBar statusBarDarkFont(boolean isDarkFont) {\n return statusBarDarkFont(isDarkFont, 0.2f);\n }\n\n /**\n * 状态栏字体深色或亮色,判断设备支不支持状态栏变色来设置状态栏透明度\n * Status bar dark font immersion bar.\n *\n * @param isDarkFont the is dark font\n * @param statusAlpha the status alpha 如果不支持状态栏字体变色可以使用statusAlpha来指定状态栏透明度,比如白色状态栏的时候可以用到\n * @return the immersion bar\n */\n public ImmersionBar statusBarDarkFont(boolean isDarkFont, @FloatRange(from = 0f, to = 1f) float statusAlpha) {\n mBarParams.statusBarDarkFont = isDarkFont;\n if (isDarkFont && !isSupportStatusBarDarkFont()) {\n mBarParams.statusBarAlpha = statusAlpha;\n } else {\n mBarParams.flymeOSStatusBarFontColor = mBarParams.flymeOSStatusBarFontTempColor;\n mBarParams.statusBarAlpha = mBarParams.statusBarTempAlpha;\n }\n return this;\n }\n\n /**\n * 导航栏图标深色或亮色,只支持android o以上版本\n * Navigation bar dark icon immersion bar.\n *\n * @param isDarkIcon the is dark icon\n * @return the immersion bar\n */\n public ImmersionBar navigationBarDarkIcon(boolean isDarkIcon) {\n return navigationBarDarkIcon(isDarkIcon, 0.2f);\n }\n\n /**\n * 导航栏图标深色或亮色,只支持android o以上版本,判断设备支不支持导航栏图标变色来设置导航栏透明度\n * Navigation bar dark icon immersion bar.\n *\n * @param isDarkIcon the is dark icon\n * @param navigationAlpha the navigation alpha 如果不支持导航栏图标变色可以使用navigationAlpha来指定导航栏透明度,比如白色导航栏的时候可以用到\n * @return the immersion bar\n */\n public ImmersionBar navigationBarDarkIcon(boolean isDarkIcon, @FloatRange(from = 0f, to = 1f) float navigationAlpha) {\n mBarParams.navigationBarDarkIcon = isDarkIcon;\n if (isDarkIcon && !isSupportNavigationIconDark()) {\n mBarParams.navigationBarAlpha = navigationAlpha;\n } else {\n mBarParams.navigationBarAlpha = mBarParams.navigationBarTempAlpha;\n }\n return this;\n }\n\n /**\n * 修改 Flyme OS系统手机状态栏字体颜色,优先级高于statusBarDarkFont(boolean isDarkFont)方法\n * Flyme os status bar font color immersion bar.\n *\n * @param flymeOSStatusBarFontColor the flyme os status bar font color\n * @return the immersion bar\n */\n public ImmersionBar flymeOSStatusBarFontColor(@ColorRes int flymeOSStatusBarFontColor) {\n mBarParams.flymeOSStatusBarFontColor = ContextCompat.getColor(mActivity, flymeOSStatusBarFontColor);\n mBarParams.flymeOSStatusBarFontTempColor = mBarParams.flymeOSStatusBarFontColor;\n return this;\n }\n\n /**\n * 修改 Flyme OS系统手机状态栏字体颜色,优先级高于statusBarDarkFont(boolean isDarkFont)方法\n * Flyme os status bar font color immersion bar.\n *\n * @param flymeOSStatusBarFontColor the flyme os status bar font color\n * @return the immersion bar\n */\n public ImmersionBar flymeOSStatusBarFontColor(String flymeOSStatusBarFontColor) {\n mBarParams.flymeOSStatusBarFontColor = Color.parseColor(flymeOSStatusBarFontColor);\n mBarParams.flymeOSStatusBarFontTempColor = mBarParams.flymeOSStatusBarFontColor;\n return this;\n }\n\n /**\n * 修改 Flyme OS系统手机状态栏字体颜色,优先级高于statusBarDarkFont(boolean isDarkFont)方法\n * Flyme os status bar font color immersion bar.\n *\n * @param flymeOSStatusBarFontColor the flyme os status bar font color\n * @return the immersion bar\n */\n public ImmersionBar flymeOSStatusBarFontColorInt(@ColorInt int flymeOSStatusBarFontColor) {\n mBarParams.flymeOSStatusBarFontColor = flymeOSStatusBarFontColor;\n mBarParams.flymeOSStatusBarFontTempColor = mBarParams.flymeOSStatusBarFontColor;\n return this;\n }\n\n /**\n * 隐藏导航栏或状态栏\n *\n * @param barHide the bar hide\n * @return the immersion bar\n */\n public ImmersionBar hideBar(BarHide barHide) {\n mBarParams.barHide = barHide;\n if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT || OSUtils.isEMUI3_x()) {\n mBarParams.hideNavigationBar = (mBarParams.barHide == BarHide.FLAG_HIDE_NAVIGATION_BAR) ||\n (mBarParams.barHide == BarHide.FLAG_HIDE_BAR);\n }\n return this;\n }\n\n\n /**\n * 解决布局与状态栏重叠问题,该方法将调用系统view的setFitsSystemWindows方法,一旦window已经focus在设置为false将不会生效,\n * 默认不会使用该方法,如果是渐变色状态栏和顶部图片请不要调用此方法或者设置为false\n * Apply system fits immersion bar.\n *\n * @param applySystemFits the apply system fits\n * @return the immersion bar\n */\n public ImmersionBar applySystemFits(boolean applySystemFits) {\n mBarParams.fitsLayoutOverlapEnable = !applySystemFits;\n setFitsSystemWindows(mActivity, applySystemFits);\n return this;\n }\n\n /**\n * 解决布局与状态栏重叠问题\n *\n * @param fits the fits\n * @return the immersion bar\n */\n public ImmersionBar fitsSystemWindows(boolean fits) {\n mBarParams.fits = fits;\n if (mBarParams.fits) {\n if (mFitsStatusBarType == FLAG_FITS_DEFAULT) {\n mFitsStatusBarType = FLAG_FITS_SYSTEM_WINDOWS;\n }\n } else {\n mFitsStatusBarType = FLAG_FITS_DEFAULT;\n }\n return this;\n }\n\n /**\n * 解决布局与状态栏重叠问题,支持侧滑返回\n * Fits system windows immersion bar.\n *\n * @param fits the fits\n * @param contentColor the content color 整体界面背景色\n * @return the immersion bar\n */\n public ImmersionBar fitsSystemWindows(boolean fits, @ColorRes int contentColor) {\n return fitsSystemWindowsInt(fits, ContextCompat.getColor(mActivity, contentColor));\n }\n\n /**\n * 解决布局与状态栏重叠问题,支持侧滑返回\n * Fits system windows immersion bar.\n *\n * @param fits the fits\n * @param contentColor the content color 整体界面背景色\n * @param contentColorTransform the content color transform 整体界面变换后的背景色\n * @param contentAlpha the content alpha 整体界面透明度\n * @return the immersion bar\n */\n public ImmersionBar fitsSystemWindows(boolean fits, @ColorRes int contentColor\n , @ColorRes int contentColorTransform, @FloatRange(from = 0f, to = 1f) float contentAlpha) {\n return fitsSystemWindowsInt(fits, ContextCompat.getColor(mActivity, contentColor),\n ContextCompat.getColor(mActivity, contentColorTransform), contentAlpha);\n }\n\n /**\n * 解决布局与状态栏重叠问题,支持侧滑返回\n * Fits system windows int immersion bar.\n *\n * @param fits the fits\n * @param contentColor the content color 整体界面背景色\n * @return the immersion bar\n */\n public ImmersionBar fitsSystemWindowsInt(boolean fits, @ColorInt int contentColor) {\n return fitsSystemWindowsInt(fits, contentColor, Color.BLACK, 0);\n }\n\n /**\n * 解决布局与状态栏重叠问题,支持侧滑返回\n * Fits system windows int immersion bar.\n *\n * @param fits the fits\n * @param contentColor the content color 整体界面背景色\n * @param contentColorTransform the content color transform 整体界面变换后的背景色\n * @param contentAlpha the content alpha 整体界面透明度\n * @return the immersion bar\n */\n public ImmersionBar fitsSystemWindowsInt(boolean fits, @ColorInt int contentColor\n , @ColorInt int contentColorTransform, @FloatRange(from = 0f, to = 1f) float contentAlpha) {\n mBarParams.fits = fits;\n mBarParams.contentColor = contentColor;\n mBarParams.contentColorTransform = contentColorTransform;\n mBarParams.contentAlpha = contentAlpha;\n if (mBarParams.fits) {\n if (mFitsStatusBarType == FLAG_FITS_DEFAULT) {\n mFitsStatusBarType = FLAG_FITS_SYSTEM_WINDOWS;\n }\n } else {\n mFitsStatusBarType = FLAG_FITS_DEFAULT;\n }\n mContentView.setBackgroundColor(ColorUtils.blendARGB(mBarParams.contentColor,\n mBarParams.contentColorTransform, mBarParams.contentAlpha));\n return this;\n }\n\n /**\n * 是否可以修复状态栏与布局重叠,默认为true,只适合ImmersionBar#statusBarView,ImmersionBar#titleBar,ImmersionBar#titleBarMarginTop\n * Fits layout overlap enable immersion bar.\n *\n * @param fitsLayoutOverlapEnable the fits layout overlap enable\n * @return the immersion bar\n */\n public ImmersionBar fitsLayoutOverlapEnable(boolean fitsLayoutOverlapEnable) {\n mBarParams.fitsLayoutOverlapEnable = fitsLayoutOverlapEnable;\n return this;\n }\n\n /**\n * 通过状态栏高度动态设置状态栏布局\n *\n * @param view the view\n * @return the immersion bar\n */\n public ImmersionBar statusBarView(View view) {\n if (view == null) {\n return this;\n }\n mBarParams.statusBarView = view;\n if (mFitsStatusBarType == FLAG_FITS_DEFAULT) {\n mFitsStatusBarType = FLAG_FITS_STATUS;\n }\n return this;\n }\n\n /**\n * 通过状态栏高度动态设置状态栏布局,只能在Activity中使用\n *\n * @param viewId the view id\n * @return the immersion bar\n */\n public ImmersionBar statusBarView(@IdRes int viewId) {\n return statusBarView(mActivity.findViewById(viewId));\n }\n\n /**\n * 通过状态栏高度动态设置状态栏布局\n * Status bar view immersion bar.\n *\n * @param viewId the view id\n * @param rootView the root view\n * @return the immersion bar\n */\n public ImmersionBar statusBarView(@IdRes int viewId, View rootView) {\n return statusBarView(rootView.findViewById(viewId));\n }\n\n /**\n * 解决状态栏与布局顶部重叠又多了种方法\n * Title bar immersion bar.\n *\n * @param view the view\n * @return the immersion bar\n */\n public ImmersionBar titleBar(View view) {\n if (view == null) {\n return this;\n }\n return titleBar(view, true);\n }\n\n /**\n * 解决状态栏与布局顶部重叠又多了种方法\n * Title bar immersion bar.\n *\n * @param view the view\n * @param statusBarColorTransformEnable the status bar flag 默认为true false表示状态栏不支持变色,true表示状态栏支持变色\n * @return the immersion bar\n */\n public ImmersionBar titleBar(View view, boolean statusBarColorTransformEnable) {\n if (view == null) {\n return this;\n }\n if (mFitsStatusBarType == FLAG_FITS_DEFAULT) {\n mFitsStatusBarType = FLAG_FITS_TITLE;\n }\n mBarParams.titleBarView = view;\n mBarParams.statusBarColorEnabled = statusBarColorTransformEnable;\n return this;\n }\n\n /**\n * 解决状态栏与布局顶部重叠又多了种方法,只支持Activity\n * Title bar immersion bar.\n *\n * @param viewId the view id\n * @return the immersion bar\n */\n public ImmersionBar titleBar(@IdRes int viewId) {\n return titleBar(viewId, true);\n }\n\n /**\n * Title bar immersion bar.\n *\n * @param viewId the view id\n * @param statusBarColorTransformEnable the status bar flag\n * @return the immersion bar\n */\n public ImmersionBar titleBar(@IdRes int viewId, boolean statusBarColorTransformEnable) {\n if (mSupportFragment != null && mSupportFragment.getView() != null) {\n return titleBar(mSupportFragment.getView().findViewById(viewId), statusBarColorTransformEnable);\n } else if (mFragment != null && mFragment.getView() != null) {\n return titleBar(mFragment.getView().findViewById(viewId), statusBarColorTransformEnable);\n } else {\n return titleBar(mActivity.findViewById(viewId), statusBarColorTransformEnable);\n }\n }\n\n /**\n * Title bar immersion bar.\n *\n * @param viewId the view id\n * @param rootView the root view\n * @return the immersion bar\n */\n public ImmersionBar titleBar(@IdRes int viewId, View rootView) {\n return titleBar(rootView.findViewById(viewId), true);\n }\n\n /**\n * 解决状态栏与布局顶部重叠又多了种方法,支持任何view\n * Title bar immersion bar.\n *\n * @param viewId the view id\n * @param rootView the root view\n * @param statusBarColorTransformEnable the status bar flag 默认为true false表示状态栏不支持变色,true表示状态栏支持变色\n * @return the immersion bar\n */\n public ImmersionBar titleBar(@IdRes int viewId, View rootView, boolean statusBarColorTransformEnable) {\n return titleBar(rootView.findViewById(viewId), statusBarColorTransformEnable);\n }\n\n /**\n * 绘制标题栏距离顶部的高度为状态栏的高度\n * Title bar margin top immersion bar.\n *\n * @param viewId the view id 标题栏资源id\n * @return the immersion bar\n */\n public ImmersionBar titleBarMarginTop(@IdRes int viewId) {\n if (mSupportFragment != null && mSupportFragment.getView() != null) {\n return titleBarMarginTop(mSupportFragment.getView().findViewById(viewId));\n } else if (mFragment != null && mFragment.getView() != null) {\n return titleBarMarginTop(mFragment.getView().findViewById(viewId));\n } else {\n return titleBarMarginTop(mActivity.findViewById(viewId));\n }\n }\n\n /**\n * 绘制标题栏距离顶部的高度为状态栏的高度\n * Title bar margin top immersion bar.\n *\n * @param viewId the view id 标题栏资源id\n * @param rootView the root view 布局view\n * @return the immersion bar\n */\n public ImmersionBar titleBarMarginTop(@IdRes int viewId, View rootView) {\n return titleBarMarginTop(rootView.findViewById(viewId));\n }\n\n /**\n * 绘制标题栏距离顶部的高度为状态栏的高度\n * Title bar margin top immersion bar.\n *\n * @param view the view 要改变的标题栏view\n * @return the immersion bar\n */\n public ImmersionBar titleBarMarginTop(View view) {\n if (view == null) {\n return this;\n }\n if (mFitsStatusBarType == FLAG_FITS_DEFAULT) {\n mFitsStatusBarType = FLAG_FITS_TITLE_MARGIN_TOP;\n }\n mBarParams.titleBarView = view;\n return this;\n }\n\n /**\n * 支持有actionBar的界面,调用该方法,布局讲从actionBar下面开始绘制\n * Support action bar immersion bar.\n *\n * @param isSupportActionBar the is support action bar\n * @return the immersion bar\n */\n public ImmersionBar supportActionBar(boolean isSupportActionBar) {\n mBarParams.isSupportActionBar = isSupportActionBar;\n return this;\n }\n\n /**\n * Status bar color transform enable immersion bar.\n *\n * @param statusBarColorTransformEnable the status bar flag\n * @return the immersion bar\n */\n public ImmersionBar statusBarColorTransformEnable(boolean statusBarColorTransformEnable) {\n mBarParams.statusBarColorEnabled = statusBarColorTransformEnable;\n return this;\n }\n\n /**\n * 一键重置所有参数\n * Reset immersion bar.\n *\n * @return the immersion bar\n */\n public ImmersionBar reset() {\n mBarParams = new BarParams();\n mFitsStatusBarType = FLAG_FITS_DEFAULT;\n return this;\n }\n\n /**\n * 给某个页面设置tag来标识这页bar的属性.\n * Add tag bar tag.\n *\n * @param tag the tag\n * @return the bar tag\n */\n public ImmersionBar addTag(String tag) {\n if (isEmpty(tag)) {\n throw new IllegalArgumentException(\"tag不能为空\");\n }\n BarParams barParams = mBarParams.clone();\n mTagMap.put(tag, barParams);\n return this;\n }\n\n /**\n * 根据tag恢复到某次调用时的参数\n * Recover immersion bar.\n *\n * @param tag the tag\n * @return the immersion bar\n */\n public ImmersionBar getTag(String tag) {\n if (isEmpty(tag)) {\n throw new IllegalArgumentException(\"tag不能为空\");\n }\n BarParams barParams = mTagMap.get(tag);\n if (barParams != null) {\n mBarParams = barParams.clone();\n }\n return this;\n }\n\n /**\n * 解决软键盘与底部输入框冲突问题 ,默认是false\n * Keyboard enable immersion bar.\n *\n * @param enable the enable\n * @return the immersion bar\n */\n public ImmersionBar keyboardEnable(boolean enable) {\n return keyboardEnable(enable, mBarParams.keyboardMode);\n }\n\n /**\n * 解决软键盘与底部输入框冲突问题 ,默认是false\n *\n * @param enable the enable\n * @param keyboardMode the keyboard mode\n * @return the immersion bar\n */\n public ImmersionBar keyboardEnable(boolean enable, int keyboardMode) {\n mBarParams.keyboardEnable = enable;\n mBarParams.keyboardMode = keyboardMode;\n mKeyboardTempEnable = enable;\n return this;\n }\n\n /**\n * 修改键盘模式\n * Keyboard mode immersion bar.\n *\n * @param keyboardMode the keyboard mode\n * @return the immersion bar\n */\n public ImmersionBar keyboardMode(int keyboardMode) {\n mBarParams.keyboardMode = keyboardMode;\n return this;\n }\n\n /**\n * 软键盘弹出关闭的回调监听\n * Sets on keyboard listener.\n *\n * @param onKeyboardListener the on keyboard listener\n * @return the on keyboard listener\n */\n public ImmersionBar setOnKeyboardListener(@Nullable OnKeyboardListener onKeyboardListener) {\n if (mBarParams.onKeyboardListener == null) {\n mBarParams.onKeyboardListener = onKeyboardListener;\n }\n return this;\n }\n\n /**\n * 导航栏显示隐藏监听器\n * Sets on navigation bar listener.\n *\n * @param onNavigationBarListener the on navigation bar listener\n * @return the on navigation bar listener\n */\n public ImmersionBar setOnNavigationBarListener(OnNavigationBarListener onNavigationBarListener) {\n if (onNavigationBarListener != null) {\n if (mBarParams.onNavigationBarListener == null) {\n mBarParams.onNavigationBarListener = onNavigationBarListener;\n NavigationBarObserver.getInstance().addOnNavigationBarListener(mBarParams.onNavigationBarListener);\n }\n } else {\n if (mBarParams.onNavigationBarListener != null) {\n NavigationBarObserver.getInstance().removeOnNavigationBarListener(mBarParams.onNavigationBarListener);\n mBarParams.onNavigationBarListener = null;\n }\n }\n return this;\n }\n\n\n /**\n * Bar监听,第一次调用和横竖屏切换都会触发此方法,比如可以解决横竖屏切换,横屏情况下,刘海屏遮挡布局的问题\n * Sets on bar listener.\n *\n * @param onBarListener the on bar listener\n * @return the on bar listener\n */\n public ImmersionBar setOnBarListener(OnBarListener onBarListener) {\n if (onBarListener != null) {\n if (mBarParams.onBarListener == null) {\n mBarParams.onBarListener = onBarListener;\n }\n } else {\n if (mBarParams.onBarListener != null) {\n mBarParams.onBarListener = null;\n }\n }\n return this;\n }\n\n /**\n * 是否可以修改导航栏颜色,默认为true\n * 优先级 navigationBarEnable > navigationBarWithKitkatEnable > navigationBarWithEMUI3Enable\n * Navigation bar enable immersion bar.\n *\n * @param navigationBarEnable the enable\n * @return the immersion bar\n */\n public ImmersionBar navigationBarEnable(boolean navigationBarEnable) {\n mBarParams.navigationBarEnable = navigationBarEnable;\n return this;\n }\n\n /**\n * 是否可以修改4.4设备导航栏颜色,默认为true\n * 优先级 navigationBarEnable > navigationBarWithKitkatEnable > navigationBarWithEMUI3Enable\n *\n * @param navigationBarWithKitkatEnable the navigation bar with kitkat enable\n * @return the immersion bar\n */\n public ImmersionBar navigationBarWithKitkatEnable(boolean navigationBarWithKitkatEnable) {\n mBarParams.navigationBarWithKitkatEnable = navigationBarWithKitkatEnable;\n return this;\n }\n\n /**\n * 是否能修改华为emui3.1导航栏颜色,默认为true,\n * 优先级 navigationBarEnable > navigationBarWithKitkatEnable > navigationBarWithEMUI3Enable\n * Navigation bar with emui 3 enable immersion bar.\n *\n * @param navigationBarWithEMUI3Enable the navigation bar with emui 3 1 enable\n * @return the immersion bar\n */\n public ImmersionBar navigationBarWithEMUI3Enable(boolean navigationBarWithEMUI3Enable) {\n //是否可以修改emui3系列手机导航栏\n if (OSUtils.isEMUI3_x()) {\n mBarParams.navigationBarWithEMUI3Enable = navigationBarWithEMUI3Enable;\n mBarParams.navigationBarWithKitkatEnable = navigationBarWithEMUI3Enable;\n }\n return this;\n }\n\n /**\n * 是否可以使用沉浸式,如果已经是true了,在改为false,之前沉浸式效果不会消失,之后设置的沉浸式效果也不会生效\n * Bar enable immersion bar.\n *\n * @param barEnable the bar enable\n * @return the immersion bar\n */\n public ImmersionBar barEnable(boolean barEnable) {\n mBarParams.barEnable = barEnable;\n return this;\n }\n\n private static RequestManagerRetriever getRetriever() {\n return RequestManagerRetriever.getInstance();\n }\n\n private static boolean isEmpty(String str) {\n return str == null || str.trim().length() == 0;\n }\n}",
"public class AppManager {\n\n private Stack<Activity> mActivities = new Stack<>();\n\n private static class Holder {\n private static final AppManager INSTANCE = new AppManager();\n }\n\n public static AppManager getInstance() {\n return Holder.INSTANCE;\n }\n\n public void addActivity(Activity activity) {\n mActivities.add(activity);\n }\n\n public void removeActivity(Activity activity) {\n hideSoftKeyBoard(activity);\n activity.finish();\n mActivities.remove(activity);\n }\n\n public void removeAllActivity() {\n for (Activity activity : mActivities) {\n hideSoftKeyBoard(activity);\n activity.finish();\n }\n mActivities.clear();\n }\n\n public <T extends Activity> boolean hasActivity(Class<T> tClass) {\n for (Activity activity : mActivities) {\n if (tClass.getName().equals(activity.getClass().getName())) {\n return !activity.isDestroyed() || !activity.isFinishing();\n }\n }\n return false;\n }\n\n public void hideSoftKeyBoard(Activity activity) {\n View localView = activity.getCurrentFocus();\n InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);\n if (localView != null && imm != null) {\n imm.hideSoftInputFromWindow(localView.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);\n }\n }\n}",
"public class BottomDialogFragment extends BaseDialogFragment {\n\n @Override\n public void onStart() {\n super.onStart();\n mWindow.setGravity(Gravity.BOTTOM);\n mWindow.setWindowAnimations(R.style.BottomAnimation);\n mWindow.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, mWidthAndHeight[1] / 2);\n }\n\n @Override\n protected int setLayoutId() {\n return R.layout.dialog;\n }\n\n @Override\n protected void initImmersionBar() {\n super.initImmersionBar();\n ImmersionBar.with(this).navigationBarColor(R.color.cool_green_normal).init();\n }\n\n @Override\n public void onConfigurationChanged(Configuration newConfig) {\n super.onConfigurationChanged(newConfig);\n mWindow.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, mWidthAndHeight[1] / 2);\n }\n}",
"public class FullDialogFragment extends BaseDialogFragment {\n\n @BindView(R.id.toolbar)\n Toolbar toolbar;\n\n @Override\n public void onStart() {\n super.onStart();\n mWindow.setWindowAnimations(R.style.RightAnimation);\n }\n\n @Override\n protected int setLayoutId() {\n return R.layout.dialog;\n }\n\n @Override\n protected void initImmersionBar() {\n super.initImmersionBar();\n ImmersionBar.with(this)\n .titleBar(toolbar)\n .statusBarDarkFont(true)\n .navigationBarColor(R.color.btn3)\n .keyboardEnable(true)\n .init();\n }\n}",
"public class LeftDialogFragment extends BaseDialogFragment {\n\n @BindView(R.id.toolbar)\n Toolbar toolbar;\n\n @Override\n public void onStart() {\n super.onStart();\n mWindow.setGravity(Gravity.TOP | Gravity.START);\n mWindow.setWindowAnimations(R.style.LeftAnimation);\n mWindow.setLayout(mWidthAndHeight[0] / 2, ViewGroup.LayoutParams.MATCH_PARENT);\n }\n\n @Override\n protected int setLayoutId() {\n return R.layout.dialog;\n }\n\n @Override\n protected void initImmersionBar() {\n super.initImmersionBar();\n ImmersionBar.with(this).titleBar(toolbar)\n .navigationBarColor(R.color.btn11)\n .keyboardEnable(true)\n .navigationBarWithKitkatEnable(getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)\n .init();\n }\n\n @Override\n public void onConfigurationChanged(Configuration newConfig) {\n super.onConfigurationChanged(newConfig);\n mWindow.setLayout(mWidthAndHeight[0] / 2, ViewGroup.LayoutParams.MATCH_PARENT);\n ImmersionBar.with(this)\n .navigationBarWithKitkatEnable(newConfig.orientation == Configuration.ORIENTATION_PORTRAIT)\n .init();\n }\n}",
"public class RightDialogFragment extends BaseDialogFragment {\n\n @BindView(R.id.toolbar)\n Toolbar toolbar;\n\n @Override\n public void onStart() {\n super.onStart();\n mWindow.setGravity(Gravity.TOP | Gravity.END);\n mWindow.setWindowAnimations(R.style.RightAnimation);\n mWindow.setLayout(mWidthAndHeight[0] / 2, ViewGroup.LayoutParams.MATCH_PARENT);\n }\n\n @Override\n protected int setLayoutId() {\n return R.layout.dialog;\n }\n\n @Override\n protected void initImmersionBar() {\n super.initImmersionBar();\n ImmersionBar.with(this).titleBar(toolbar)\n .navigationBarColor(R.color.btn8)\n .keyboardEnable(true)\n .init();\n }\n\n @Override\n public void onConfigurationChanged(Configuration newConfig) {\n super.onConfigurationChanged(newConfig);\n mWindow.setLayout(mWidthAndHeight[0] / 2, ViewGroup.LayoutParams.MATCH_PARENT);\n }\n}",
"public class TopDialogFragment extends BaseDialogFragment {\n\n @BindView(R.id.toolbar)\n Toolbar toolbar;\n\n @Override\n public void onStart() {\n super.onStart();\n mWindow.setGravity(Gravity.TOP);\n mWindow.setWindowAnimations(R.style.TopAnimation);\n mWindow.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, mWidthAndHeight[1] / 2);\n }\n\n @Override\n protected int setLayoutId() {\n return R.layout.dialog;\n }\n\n @Override\n protected void initImmersionBar() {\n super.initImmersionBar();\n ImmersionBar.with(this)\n .titleBar(toolbar)\n .navigationBarColor(R.color.btn4)\n .navigationBarWithKitkatEnable(getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)\n .init();\n }\n\n @Override\n public void onConfigurationChanged(Configuration newConfig) {\n super.onConfigurationChanged(newConfig);\n mWindow.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, mWidthAndHeight[1] / 2);\n ImmersionBar.with(this)\n .navigationBarWithKitkatEnable(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE)\n .init();\n }\n}",
"public class Utils {\n\n public static Integer[] getWidthAndHeight(Window window) {\n if (window == null) {\n return null;\n }\n Integer[] integer = new Integer[2];\n DisplayMetrics dm = new DisplayMetrics();\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {\n window.getWindowManager().getDefaultDisplay().getRealMetrics(dm);\n } else {\n window.getWindowManager().getDefaultDisplay().getMetrics(dm);\n }\n integer[0] = dm.widthPixels;\n integer[1] = dm.heightPixels;\n return integer;\n }\n\n\n public static String getPic() {\n Random random = new Random();\n return \"http://106.14.135.179/ImmersionBar/\" + random.nextInt(40) + \".jpg\";\n }\n\n public static ArrayList<String> getPics() {\n return getPics(4);\n }\n\n public static ArrayList<String> getPics(int num) {\n ArrayList<String> pics = new ArrayList<>();\n Random random = new Random();\n\n do {\n String s = \"http://106.14.135.179/ImmersionBar/\" + random.nextInt(40) + \".jpg\";\n if (!pics.contains(s)) {\n pics.add(s);\n }\n } while (pics.size() < num);\n return pics;\n }\n\n public static String getFullPic() {\n Random random = new Random();\n return \"http://106.14.135.179/ImmersionBar/phone/\" + random.nextInt(40) + \".jpeg\";\n }\n\n public static int getFlowerIcon() {\n Random random = new Random();\n int i = random.nextInt(99);\n if (i < 33) {\n return R.mipmap.icon_flower_1;\n } else if (i < 66) {\n return R.mipmap.icon_flower_2;\n } else {\n return R.mipmap.icon_flower_3;\n }\n }\n\n public static boolean isNetworkConnected(Context context) {\n if (context != null) {\n ConnectivityManager manager = (ConnectivityManager) context\n .getSystemService(Context.CONNECTIVITY_SERVICE);\n NetworkInfo mNetworkInfo = manager.getActiveNetworkInfo();\n if (mNetworkInfo != null) {\n return mNetworkInfo.isAvailable();\n }\n }\n return false;\n }\n\n}"
] | import android.content.DialogInterface;
import android.content.res.Configuration;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.Toolbar;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.gyf.immersionbar.ImmersionBar;
import com.gyf.immersionbar.sample.AppManager;
import com.gyf.immersionbar.sample.R;
import com.gyf.immersionbar.sample.fragment.dialog.BottomDialogFragment;
import com.gyf.immersionbar.sample.fragment.dialog.FullDialogFragment;
import com.gyf.immersionbar.sample.fragment.dialog.LeftDialogFragment;
import com.gyf.immersionbar.sample.fragment.dialog.RightDialogFragment;
import com.gyf.immersionbar.sample.fragment.dialog.TopDialogFragment;
import com.gyf.immersionbar.sample.utils.Utils;
import butterknife.BindView;
import butterknife.OnClick; | package com.gyf.immersionbar.sample.activity;
/**
* @author geyifeng
* @date 2017/7/31
*/
public class DialogActivity extends BaseActivity implements DialogInterface.OnDismissListener {
@BindView(R.id.btn_full_fragment)
Button btnFullFragment;
@BindView(R.id.btn_top_fragment)
Button btnTopFragment;
@BindView(R.id.btn_bottom_fragment)
Button btnBottomFragment;
@BindView(R.id.btn_left_fragment)
Button btnLeftFragment;
@BindView(R.id.btn_right_fragment)
Button btnRightFragment;
private AlertDialog mAlertDialog;
private Window mDialogWindow;
private int mId = 0;
@Override
protected int getLayoutId() {
return R.layout.activity_dialog;
}
@Override
protected void initImmersionBar() {
super.initImmersionBar();
ImmersionBar.with(this).titleBar(R.id.toolbar).keyboardEnable(true).init();
}
@Override
protected void setListener() {
btnFullFragment.setOnClickListener(v -> {
FullDialogFragment fullDialogFragment = new FullDialogFragment();
fullDialogFragment.show(getSupportFragmentManager(), FullDialogFragment.class.getSimpleName());
});
btnTopFragment.setOnClickListener(v -> { | TopDialogFragment fullDialogFragment = new TopDialogFragment(); | 6 |
reelyactive/ble-android-sdk | library/src/main/java/com/reelyactive/blesdk/application/ReelyAwareApplicationCallback.java | [
"public class BleService extends Service {\n public static final String KEY_FILTER = \"filter\";\n public static final String KEY_EVENT_DATA = \"event_data\";\n final ScanCallback callback = new ScanCallback();\n final ScanSettings lowPowerScan = new ScanSettings.Builder() //\n .setCallbackType(ScanSettings.CALLBACK_TYPE_FIRST_MATCH | ScanSettings.CALLBACK_TYPE_MATCH_LOST) //\n .setScanMode(ScanSettings.SCAN_MODE_BALANCED) //\n .setScanResultType(ScanSettings.SCAN_RESULT_TYPE_FULL) //\n .build();\n final ScanSettings higPowerScan = new ScanSettings.Builder() //\n .setCallbackType(ScanSettings.CALLBACK_TYPE_FIRST_MATCH | ScanSettings.CALLBACK_TYPE_MATCH_LOST) //\n .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY) //\n .setScanResultType(ScanSettings.SCAN_RESULT_TYPE_FULL) //\n .build();\n private final IBinder binder = new LocalBinder();\n /**\n * Keeps track of all current registered clients.\n */\n ArrayList<BleServiceCallback> mClients = new ArrayList<BleServiceCallback>();\n private BluetoothLeScannerCompat scanner;\n private ScanSettings currentSettings;\n private ScanSettings nextSettings;\n private ScanFilter currentFilter;\n private ScanFilter nextFilter;\n\n @Override\n public void onCreate() {\n scanner = BluetoothLeScannerCompatProvider.getBluetoothLeScannerCompat(getApplicationContext());\n }\n\n @Override\n public void onDestroy() {\n // TODO make it possible to kill the scanner.\n }\n\n /**\n * When binding to the service, we return an interface to our messenger\n * for sending messages to the service.\n */\n @Override\n public IBinder onBind(Intent intent) {\n return binder;\n }\n\n public void registerClient(BleServiceCallback client) {\n mClients.add(client);\n }\n\n public void unregisterClient(BleServiceCallback client) {\n mClients.remove(client);\n }\n\n public void startScan() {\n nextSettings = nextSettings == null ? lowPowerScan : nextSettings;\n nextFilter = nextFilter == null ? (currentFilter == null ? new ScanFilter.Builder().build() : currentFilter) : nextFilter;\n if (currentSettings != nextSettings || nextFilter != currentFilter) {\n stopScan();\n notifyEvent(Event.SCAN_STARTED);\n scanner.startScan(Collections.singletonList(nextFilter), nextSettings, callback); // TODO make it possible to scan using more filters\n }\n currentSettings = nextSettings;\n currentFilter = nextFilter;\n }\n\n public void stopScan() {\n currentFilter = null;\n currentSettings = null;\n scanner.stopScan(callback);\n notifyEvent(Event.SCAN_STOPPED);\n }\n\n public void setScanType(ScanType scanType) {\n nextSettings = ScanType.ACTIVE == scanType ? higPowerScan : lowPowerScan;\n }\n\n public void setScanFilter(ScanFilter scanFilter) {\n nextFilter = scanFilter;\n }\n\n public List<ScanResult> getMatchingRecentResults(List<ScanFilter> filters) {\n return scanner.getMatchingRecords(filters);\n }\n\n private void notifyEvent(Event event, Parcelable... data) {\n ScanResult result = null;\n if (data != null && data.length == 1) {\n result = (ScanResult) data[0];\n }\n for (int i = mClients.size() - 1; i >= 0; i--) {\n mClients.get(i).onBleEvent(event, result);\n }\n }\n\n public static enum Event {\n SCAN_STARTED,\n SCAN_STOPPED,\n IN_REGION,\n OUT_REGION,\n CYCLE_COMPLETED,\n UNKNOWN;\n private static Event[] allValues = values();\n\n public static Event fromOrdinal(int n) {\n if (n >= 0 || n < UNKNOWN.ordinal()) {\n return allValues[n];\n }\n return UNKNOWN;\n }\n }\n\n public static enum ScanType {\n LOW_POWER,\n ACTIVE;\n private static ScanType[] allValues = values();\n\n public static ScanType fromOrdinal(int n) throws IllegalArgumentException {\n if (n < 0 || n >= allValues.length) {\n return LOW_POWER;\n }\n return allValues[n];\n }\n }\n\n /**\n * Class used for the client Binder. Because we know this service always\n * runs in the same process as its clients, we don't need to deal with IPC.\n */\n public class LocalBinder extends Binder {\n public BleService getService() {\n // Return this instance of LocalService so clients can call public methods\n return BleService.this;\n }\n }\n\n class ScanCallback extends com.reelyactive.blesdk.support.ble.ScanCallback {\n @Override\n public void onScanResult(int callbackType, ScanResult result) {\n notifyEvent(callbackType != ScanSettings.CALLBACK_TYPE_MATCH_LOST ? Event.IN_REGION : Event.OUT_REGION, result);\n }\n\n @Override\n public void onScanCycleCompleted() {\n notifyEvent(Event.CYCLE_COMPLETED);\n }\n }\n}",
"public interface BleServiceCallback {\n public boolean onBleEvent(BleService.Event event, Object data);\n}",
"public final class ScanFilter implements Parcelable {\n\n @Nullable\n private final String mDeviceName;\n\n @Nullable\n private final String mDeviceAddress;\n\n @Nullable\n private final ParcelUuid mServiceUuid;\n @Nullable\n private final ParcelUuid mServiceUuidMask;\n\n @Nullable\n private final ParcelUuid mServiceDataUuid;\n @Nullable\n private final byte[] mServiceData;\n @Nullable\n private final byte[] mServiceDataMask;\n\n private final int mManufacturerId;\n @Nullable\n private final byte[] mManufacturerData;\n @Nullable\n private final byte[] mManufacturerDataMask;\n\n private ScanFilter(String name, String deviceAddress, ParcelUuid uuid,\n ParcelUuid uuidMask, ParcelUuid serviceDataUuid,\n byte[] serviceData, byte[] serviceDataMask,\n int manufacturerId, byte[] manufacturerData, byte[] manufacturerDataMask) {\n mDeviceName = name;\n mServiceUuid = uuid;\n mServiceUuidMask = uuidMask;\n mDeviceAddress = deviceAddress;\n mServiceDataUuid = serviceDataUuid;\n mServiceData = serviceData;\n mServiceDataMask = serviceDataMask;\n mManufacturerId = manufacturerId;\n mManufacturerData = manufacturerData;\n mManufacturerDataMask = manufacturerDataMask;\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n dest.writeInt(mDeviceName == null ? 0 : 1);\n if (mDeviceName != null) {\n dest.writeString(mDeviceName);\n }\n dest.writeInt(mDeviceAddress == null ? 0 : 1);\n if (mDeviceAddress != null) {\n dest.writeString(mDeviceAddress);\n }\n dest.writeInt(mServiceUuid == null ? 0 : 1);\n if (mServiceUuid != null) {\n dest.writeParcelable(mServiceUuid, flags);\n dest.writeInt(mServiceUuidMask == null ? 0 : 1);\n if (mServiceUuidMask != null) {\n dest.writeParcelable(mServiceUuidMask, flags);\n }\n }\n dest.writeInt(mServiceDataUuid == null ? 0 : 1);\n if (mServiceDataUuid != null) {\n dest.writeParcelable(mServiceDataUuid, flags);\n dest.writeInt(mServiceData == null ? 0 : 1);\n if (mServiceData != null) {\n dest.writeInt(mServiceData.length);\n dest.writeByteArray(mServiceData);\n\n dest.writeInt(mServiceDataMask == null ? 0 : 1);\n if (mServiceDataMask != null) {\n dest.writeInt(mServiceDataMask.length);\n dest.writeByteArray(mServiceDataMask);\n }\n }\n }\n dest.writeInt(mManufacturerId);\n dest.writeInt(mManufacturerData == null ? 0 : 1);\n if (mManufacturerData != null) {\n dest.writeInt(mManufacturerData.length);\n dest.writeByteArray(mManufacturerData);\n\n dest.writeInt(mManufacturerDataMask == null ? 0 : 1);\n if (mManufacturerDataMask != null) {\n dest.writeInt(mManufacturerDataMask.length);\n dest.writeByteArray(mManufacturerDataMask);\n }\n }\n }\n\n /**\n * A {@link android.os.Parcelable.Creator} to create {@link ScanFilter} from parcel.\n *\n * @hide\n */\n public static final Creator<ScanFilter>\n CREATOR = new Creator<ScanFilter>() {\n\n @Override\n public ScanFilter[] newArray(int size) {\n return new ScanFilter[size];\n }\n\n @Override\n public ScanFilter createFromParcel(Parcel in) {\n Builder builder = new Builder();\n if (in.readInt() == 1) {\n builder.setDeviceName(in.readString());\n }\n if (in.readInt() == 1) {\n builder.setDeviceAddress(in.readString());\n }\n if (in.readInt() == 1) {\n ParcelUuid uuid = in.readParcelable(ParcelUuid.class.getClassLoader());\n builder.setServiceUuid(uuid);\n if (in.readInt() == 1) {\n ParcelUuid uuidMask = in.readParcelable(\n ParcelUuid.class.getClassLoader());\n builder.setServiceUuid(uuid, uuidMask);\n }\n }\n if (in.readInt() == 1) {\n ParcelUuid serviceDataUuid =\n in.readParcelable(ParcelUuid.class.getClassLoader());\n if (in.readInt() == 1) {\n int serviceDataLength = in.readInt();\n byte[] serviceData = new byte[serviceDataLength];\n in.readByteArray(serviceData);\n if (in.readInt() == 0) {\n builder.setServiceData(serviceDataUuid, serviceData);\n } else {\n int serviceDataMaskLength = in.readInt();\n byte[] serviceDataMask = new byte[serviceDataMaskLength];\n in.readByteArray(serviceDataMask);\n builder.setServiceData(\n serviceDataUuid, serviceData, serviceDataMask);\n }\n }\n }\n\n int manufacturerId = in.readInt();\n if (in.readInt() == 1) {\n int manufacturerDataLength = in.readInt();\n byte[] manufacturerData = new byte[manufacturerDataLength];\n in.readByteArray(manufacturerData);\n if (in.readInt() == 0) {\n builder.setManufacturerData(manufacturerId, manufacturerData);\n } else {\n int manufacturerDataMaskLength = in.readInt();\n byte[] manufacturerDataMask = new byte[manufacturerDataMaskLength];\n in.readByteArray(manufacturerDataMask);\n builder.setManufacturerData(manufacturerId, manufacturerData,\n manufacturerDataMask);\n }\n }\n\n return builder.build();\n }\n };\n\n /**\n * Returns the filter set on the device name field of Bluetooth advertisement data.\n */\n @Nullable\n public String getDeviceName() {\n return mDeviceName;\n }\n\n /**\n * Returns the filter set on the service uuid.\n */\n @Nullable\n public ParcelUuid getServiceUuid() {\n return mServiceUuid;\n }\n\n @Nullable\n public ParcelUuid getServiceUuidMask() {\n return mServiceUuidMask;\n }\n\n @Nullable\n public String getDeviceAddress() {\n return mDeviceAddress;\n }\n\n @Nullable\n public byte[] getServiceData() {\n return mServiceData;\n }\n\n @Nullable\n public byte[] getServiceDataMask() {\n return mServiceDataMask;\n }\n\n @Nullable\n public ParcelUuid getServiceDataUuid() {\n return mServiceDataUuid;\n }\n\n /**\n * Returns the manufacturer id. -1 if the manufacturer filter is not set.\n */\n public int getManufacturerId() {\n return mManufacturerId;\n }\n\n @Nullable\n public byte[] getManufacturerData() {\n return mManufacturerData;\n }\n\n @Nullable\n public byte[] getManufacturerDataMask() {\n return mManufacturerDataMask;\n }\n\n /**\n * Check if the scan filter matches a {@code scanResult}. A scan result is considered as a match\n * if it matches all the field filters.\n */\n public boolean matches(ScanResult scanResult) {\n if (scanResult == null) {\n return false;\n }\n BluetoothDevice device = scanResult.getDevice();\n // Device match.\n if (mDeviceAddress != null\n && (device == null || !mDeviceAddress.equals(device.getAddress()))) {\n return false;\n }\n\n ScanRecord scanRecord = scanResult.getScanRecord();\n\n // Scan record is null but there exist filters on it.\n if (scanRecord == null\n && (mDeviceName != null || mServiceUuid != null || mManufacturerData != null\n || mServiceData != null)) {\n return false;\n }\n\n // Local name match.\n if (mDeviceName != null && !mDeviceName.equals(scanRecord.getDeviceName())) {\n return false;\n }\n\n // UUID match.\n if (mServiceUuid != null && !matchesServiceUuids(mServiceUuid, mServiceUuidMask,\n scanRecord.getServiceUuids())) {\n return false;\n }\n\n // Service data match\n if (mServiceDataUuid != null) {\n if (!matchesPartialData(mServiceData, mServiceDataMask,\n scanRecord.getServiceData(mServiceDataUuid))) {\n return false;\n }\n }\n\n // Manufacturer data match.\n if (mManufacturerId >= 0) {\n if (!matchesPartialData(mManufacturerData, mManufacturerDataMask,\n scanRecord.getManufacturerSpecificData(mManufacturerId))) {\n return false;\n }\n }\n // All filters match.\n return true;\n }\n\n // Check if the uuid pattern is contained in a list of parcel uuids.\n private boolean matchesServiceUuids(ParcelUuid uuid, ParcelUuid parcelUuidMask,\n List<ParcelUuid> uuids) {\n if (uuid == null) {\n return true;\n }\n if (uuids == null) {\n return false;\n }\n\n for (ParcelUuid parcelUuid : uuids) {\n UUID uuidMask = parcelUuidMask == null ? null : parcelUuidMask.getUuid();\n if (matchesServiceUuid(uuid.getUuid(), uuidMask, parcelUuid.getUuid())) {\n return true;\n }\n }\n return false;\n }\n\n // Check if the uuid pattern matches the particular service uuid.\n private boolean matchesServiceUuid(UUID uuid, UUID mask, UUID data) {\n if (mask == null) {\n return uuid.equals(data);\n }\n if ((uuid.getLeastSignificantBits() & mask.getLeastSignificantBits())\n != (data.getLeastSignificantBits() & mask.getLeastSignificantBits())) {\n return false;\n }\n return ((uuid.getMostSignificantBits() & mask.getMostSignificantBits())\n == (data.getMostSignificantBits() & mask.getMostSignificantBits()));\n }\n\n /**\n * Check whether the data pattern matches the parsed data.\n * @VisibleForTesting\n */\n static boolean matchesPartialData(byte[] data, byte[] dataMask, byte[] parsedData) {\n if (parsedData == null || parsedData.length < data.length) {\n return false;\n }\n if (dataMask == null) {\n for (int i = 0; i < data.length; ++i) {\n if (parsedData[i] != data[i]) {\n return false;\n }\n }\n return true;\n }\n for (int i = 0; i < data.length; ++i) {\n if ((dataMask[i] & parsedData[i]) != (dataMask[i] & data[i])) {\n return false;\n }\n }\n return true;\n }\n\n @Override\n public String toString() {\n return \"BluetoothLeScanFilter [mDeviceName=\" + mDeviceName + \", mDeviceAddress=\"\n + mDeviceAddress\n + \", mUuid=\" + mServiceUuid + \", mUuidMask=\" + mServiceUuidMask\n + \", mServiceDataUuid=\" + Objects.toString(mServiceDataUuid) + \", mServiceData=\"\n + Arrays.toString(mServiceData) + \", mServiceDataMask=\"\n + Arrays.toString(mServiceDataMask) + \", mManufacturerId=\" + mManufacturerId\n + \", mManufacturerData=\" + Arrays.toString(mManufacturerData)\n + \", mManufacturerDataMask=\" + Arrays.toString(mManufacturerDataMask) + \"]\";\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(mDeviceName, mDeviceAddress, mManufacturerId, mManufacturerData,\n mManufacturerDataMask, mServiceDataUuid, mServiceData, mServiceDataMask,\n mServiceUuid, mServiceUuidMask);\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n if (obj == null || getClass() != obj.getClass()) {\n return false;\n }\n ScanFilter other = (ScanFilter) obj;\n return Objects.equals(mDeviceName, other.mDeviceName)\n && Objects.equals(mDeviceAddress, other.mDeviceAddress)\n && mManufacturerId == other.mManufacturerId\n && Objects.deepEquals(mManufacturerData, other.mManufacturerData)\n && Objects.deepEquals(mManufacturerDataMask, other.mManufacturerDataMask)\n && Objects.equals(mServiceDataUuid, other.mServiceDataUuid)\n && Objects.deepEquals(mServiceData, other.mServiceData)\n && Objects.deepEquals(mServiceDataMask, other.mServiceDataMask)\n && Objects.equals(mServiceUuid, other.mServiceUuid)\n && Objects.equals(mServiceUuidMask, other.mServiceUuidMask);\n }\n\n /**\n * Builder class for {@link ScanFilter}.\n */\n public static final class Builder {\n\n private String mDeviceName;\n private String mDeviceAddress;\n\n private ParcelUuid mServiceUuid;\n private ParcelUuid mUuidMask;\n\n private ParcelUuid mServiceDataUuid;\n private byte[] mServiceData;\n private byte[] mServiceDataMask;\n\n private int mManufacturerId = -1;\n private byte[] mManufacturerData;\n private byte[] mManufacturerDataMask;\n\n /**\n * Set filter on device name.\n */\n public Builder setDeviceName(String deviceName) {\n mDeviceName = deviceName;\n return this;\n }\n\n /**\n * Set filter on device address.\n *\n * @param deviceAddress The device Bluetooth address for the filter. It needs to be in the\n * format of \"01:02:03:AB:CD:EF\". The device address can be validated using\n * {@link android.bluetooth.BluetoothAdapter#checkBluetoothAddress}.\n * @throws IllegalArgumentException If the {@code deviceAddress} is invalid.\n */\n public Builder setDeviceAddress(String deviceAddress) {\n if (deviceAddress != null && !BluetoothAdapter.checkBluetoothAddress(deviceAddress)) {\n throw new IllegalArgumentException(\"invalid device address \" + deviceAddress);\n }\n mDeviceAddress = deviceAddress;\n return this;\n }\n\n /**\n * Set filter on service uuid.\n */\n public Builder setServiceUuid(ParcelUuid serviceUuid) {\n mServiceUuid = serviceUuid;\n mUuidMask = null; // clear uuid mask\n return this;\n }\n\n /**\n * Set filter on partial service uuid. The {@code uuidMask} is the bit mask for the\n * {@code serviceUuid}. Set any bit in the mask to 1 to indicate a match is needed for the\n * bit in {@code serviceUuid}, and 0 to ignore that bit.\n *\n * @throws IllegalArgumentException If {@code serviceUuid} is {@code null} but\n * {@code uuidMask} is not {@code null}.\n */\n public Builder setServiceUuid(ParcelUuid serviceUuid, ParcelUuid uuidMask) {\n if (mUuidMask != null && mServiceUuid == null) {\n throw new IllegalArgumentException(\"uuid is null while uuidMask is not null!\");\n }\n mServiceUuid = serviceUuid;\n mUuidMask = uuidMask;\n return this;\n }\n\n /**\n * Set filtering on service data.\n *\n * @throws IllegalArgumentException If {@code serviceDataUuid} is null.\n */\n public Builder setServiceData(ParcelUuid serviceDataUuid, byte[] serviceData) {\n if (serviceDataUuid == null) {\n throw new IllegalArgumentException(\"serviceDataUuid is null\");\n }\n mServiceDataUuid = serviceDataUuid;\n mServiceData = serviceData;\n mServiceDataMask = null; // clear service data mask\n return this;\n }\n\n /**\n * Set partial filter on service data. For any bit in the mask, set it to 1 if it needs to\n * match the one in service data, otherwise set it to 0 to ignore that bit.\n * <p>\n * The {@code serviceDataMask} must have the same length of the {@code serviceData}.\n *\n * @throws IllegalArgumentException If {@code serviceDataUuid} is null or\n * {@code serviceDataMask} is {@code null} while {@code serviceData} is not or\n * {@code serviceDataMask} and {@code serviceData} has different length.\n */\n public Builder setServiceData(ParcelUuid serviceDataUuid,\n byte[] serviceData, byte[] serviceDataMask) {\n if (serviceDataUuid == null) {\n throw new IllegalArgumentException(\"serviceDataUuid is null\");\n }\n if (mServiceDataMask != null) {\n if (mServiceData == null) {\n throw new IllegalArgumentException(\n \"serviceData is null while serviceDataMask is not null\");\n }\n // Since the mServiceDataMask is a bit mask for mServiceData, the lengths of the two\n // byte array need to be the same.\n if (mServiceData.length != mServiceDataMask.length) {\n throw new IllegalArgumentException(\n \"size mismatch for service data and service data mask\");\n }\n }\n mServiceDataUuid = serviceDataUuid;\n mServiceData = serviceData;\n mServiceDataMask = serviceDataMask;\n return this;\n }\n\n /**\n * Set filter on on manufacturerData. A negative manufacturerId is considered as invalid id.\n * <p>\n * Note the first two bytes of the {@code manufacturerData} is the manufacturerId.\n *\n * @throws IllegalArgumentException If the {@code manufacturerId} is invalid.\n */\n public Builder setManufacturerData(int manufacturerId, byte[] manufacturerData) {\n if (manufacturerData != null && manufacturerId < 0) {\n throw new IllegalArgumentException(\"invalid manufacture id\");\n }\n mManufacturerId = manufacturerId;\n mManufacturerData = manufacturerData;\n mManufacturerDataMask = null; // clear manufacturer data mask\n return this;\n }\n\n /**\n * Set filter on partial manufacture data. For any bit in the mask, set it to 1 if it needs\n * to match the one in manufacturer data, otherwise set it to 0.\n * <p>\n * The {@code manufacturerDataMask} must have the same length of {@code manufacturerData}.\n *\n * @throws IllegalArgumentException If the {@code manufacturerId} is invalid, or\n * {@code manufacturerData} is null while {@code manufacturerDataMask} is not,\n * or {@code manufacturerData} and {@code manufacturerDataMask} have different\n * length.\n */\n public Builder setManufacturerData(int manufacturerId, byte[] manufacturerData,\n byte[] manufacturerDataMask) {\n if (manufacturerData != null && manufacturerId < 0) {\n throw new IllegalArgumentException(\"invalid manufacture id\");\n }\n if (mManufacturerDataMask != null) {\n if (mManufacturerData == null) {\n throw new IllegalArgumentException(\n \"manufacturerData is null while manufacturerDataMask is not null\");\n }\n // Since the mManufacturerDataMask is a bit mask for mManufacturerData, the lengths\n // of the two byte array need to be the same.\n if (mManufacturerData.length != mManufacturerDataMask.length) {\n throw new IllegalArgumentException(\n \"size mismatch for manufacturerData and manufacturerDataMask\");\n }\n }\n mManufacturerId = manufacturerId;\n mManufacturerData = manufacturerData;\n mManufacturerDataMask = manufacturerDataMask;\n return this;\n }\n\n /**\n * Build {@link ScanFilter}.\n *\n * @throws IllegalArgumentException If the filter cannot be built.\n */\n public ScanFilter build() {\n return new ScanFilter(mDeviceName, mDeviceAddress,\n mServiceUuid, mUuidMask,\n mServiceDataUuid, mServiceData, mServiceDataMask,\n mManufacturerId, mManufacturerData, mManufacturerDataMask);\n }\n }\n}",
"public final class ScanResult implements Parcelable {\n // Remote bluetooth device.\n private BluetoothDevice mDevice;\n\n // Scan record, including advertising data and scan response data.\n @Nullable\n private ScanRecord mScanRecord;\n\n // Received signal strength.\n private int mRssi;\n\n // Device timestamp when the result was last seen.\n private long mTimestampNanos;\n\n /**\n * Constructor of scan result.\n *\n * @param device Remote bluetooth device that is found.\n * @param scanRecord Scan record including both advertising data and scan response data.\n * @param rssi Received signal strength.\n * @param timestampNanos Device timestamp when the scan result was observed.\n */\n public ScanResult(BluetoothDevice device, ScanRecord scanRecord, int rssi,\n long timestampNanos) {\n mDevice = device;\n mScanRecord = scanRecord;\n mRssi = rssi;\n mTimestampNanos = timestampNanos;\n }\n\n private ScanResult(Parcel in) {\n readFromParcel(in);\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n if (mDevice != null) {\n dest.writeInt(1);\n mDevice.writeToParcel(dest, flags);\n } else {\n dest.writeInt(0);\n }\n if (mScanRecord != null) {\n dest.writeInt(1);\n dest.writeByteArray(mScanRecord.getBytes());\n } else {\n dest.writeInt(0);\n }\n dest.writeInt(mRssi);\n dest.writeLong(mTimestampNanos);\n }\n\n private void readFromParcel(Parcel in) {\n if (in.readInt() == 1) {\n mDevice = BluetoothDevice.CREATOR.createFromParcel(in);\n }\n if (in.readInt() == 1) {\n mScanRecord = ScanRecord.parseFromBytes(in.createByteArray());\n }\n mRssi = in.readInt();\n mTimestampNanos = in.readLong();\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n /**\n * Returns the remote bluetooth device identified by the bluetooth device address.\n */\n public BluetoothDevice getDevice() {\n return mDevice;\n }\n\n /**\n * Returns the scan record, which is a combination of advertisement and scan response.\n */\n @Nullable\n public ScanRecord getScanRecord() {\n return mScanRecord;\n }\n\n /**\n * Returns the received signal strength in dBm. The valid range is [-127, 127].\n */\n public int getRssi() {\n return mRssi;\n }\n\n /**\n * Returns timestamp since boot when the scan record was observed.\n */\n public long getTimestampNanos() {\n return mTimestampNanos;\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(mDevice, mRssi, mScanRecord, mTimestampNanos);\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n if (obj == null || getClass() != obj.getClass()) {\n return false;\n }\n ScanResult other = (ScanResult) obj;\n return Objects.equals(mDevice, other.mDevice) && (mRssi == other.mRssi)\n && Objects.equals(mScanRecord, other.mScanRecord)\n && (mTimestampNanos == other.mTimestampNanos);\n }\n\n @Override\n public String toString() {\n return \"com.reelyactive.blesdk.support.ble.ScanResult{\" + \"mDevice=\" + mDevice + \", mScanRecord=\"\n + Objects.toString(mScanRecord) + \", mRssi=\" + mRssi + \", mTimestampNanos=\"\n + mTimestampNanos + '}';\n }\n\n /**\n * @hide\n */\n public static final Creator<ScanResult> CREATOR = new Creator<ScanResult>() {\n @Override\n public ScanResult createFromParcel(Parcel source) {\n return new ScanResult(source);\n }\n\n @Override\n public ScanResult[] newArray(int size) {\n return new ScanResult[size];\n }\n };\n\n}",
"public class Logger {\n\n public static final String TAG = \"BleScanCompatLib\";\n\n public static void logVerbose(String message) {\n if (Log.isLoggable(TAG, Log.VERBOSE)) {\n Log.v(TAG, message);\n }\n }\n\n public static void logWarning(String message) {\n if (Log.isLoggable(TAG, Log.WARN)) {\n Log.w(TAG, message);\n }\n }\n\n public static void logDebug(String message) {\n if (Log.isLoggable(TAG, Log.DEBUG)) {\n Log.d(TAG, message);\n }\n }\n\n public static void logInfo(String message) {\n if (Log.isLoggable(TAG, Log.INFO)) {\n Log.i(TAG, message);\n }\n }\n\n public static void logError(String message, Exception... e) {\n if (Log.isLoggable(TAG, Log.ERROR)) {\n if (e == null || e.length == 0) {\n Log.e(TAG, message);\n } else {\n Log.e(TAG, message, e[0]);\n }\n }\n }\n}"
] | import android.Manifest;
import android.app.Activity;
import android.app.Application;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.IBinder;
import android.os.ParcelUuid;
import android.support.v4.content.ContextCompat;
import com.reelyactive.blesdk.service.BleService;
import com.reelyactive.blesdk.service.BleServiceCallback;
import com.reelyactive.blesdk.support.ble.ScanFilter;
import com.reelyactive.blesdk.support.ble.ScanResult;
import com.reelyactive.blesdk.support.ble.util.Logger;
import java.util.concurrent.atomic.AtomicInteger; | package com.reelyactive.blesdk.application;
/**
* This class provides a convenient way to make your application aware of any Reelceivers.
* <p>
* Register it using {@link android.app.Application#registerActivityLifecycleCallbacks(Application.ActivityLifecycleCallbacks)}<br/>
* <p>
* Extend it to customize the behaviour of your application.
* <p>
* The default behaviour is to bind to the {@link BleService} as soon as the app is created.
*
* @see android.app.Application.ActivityLifecycleCallbacks
*/
@SuppressWarnings("unused")
public abstract class ReelyAwareApplicationCallback implements Application.ActivityLifecycleCallbacks, BleServiceCallback {
private static final String TAG = ReelyAwareApplicationCallback.class.getSimpleName();
private final Context context;
private final ServiceConnection serviceConnection;
private final AtomicInteger activityCount = new AtomicInteger();
private boolean bound = false;
private Activity current;
private BleService service;
/**
* As soon as the component is created, we bindBleService to the {@link BleService}
*
* @param context The application's {@link Context}
*/
public ReelyAwareApplicationCallback(Context context) {
this.context = context;
this.serviceConnection = new BleServiceConnection();
bindBleService();
}
/**
* Find out if an {@link Activity} implements {@link ReelyAwareActivity}
*
* @param activity The {@link Activity}
* @return true if the {@link Activity} implements {@link ReelyAwareActivity}, false if not.
*/
protected static boolean isReelyAware(Activity activity) {
return activity != null && ReelyAwareActivity.class.isInstance(activity);
}
/**
* The default behaviour is to check if a {@link ReelyAwareActivity} is running, and call a scan if so.<br/>
* See {@link #startScan()} and {@link #getScanType()}
*
* @param activity The resumed {@link Activity}
*/
@Override
public void onActivityResumed(Activity activity) {
current = activity;
activityCount.incrementAndGet();
if (!startScan()) {
stopScan();
}
}
/**
* The default behaviour is to check if any {@link ReelyAwareActivity} is still running, and call a scan if so.<br/>
* See {@link #startScan()} and {@link #getScanType()}
*
* @param activity The resumed {@link Activity}.
*/
@Override
public void onActivityPaused(Activity activity) {
current = null;
activityCount.decrementAndGet();
if (!startScan()) {
stopScan();
}
}
/**
* This method sends a scan request to the {@link BleService}.
*
* @return True if the service has started, false otherwise.
*/
protected boolean startScan() {
if (isBound() && hasScanPermissions() && shouldStartScan()) {
updateScanType(getScanType());
updateScanFilter(getScanFilter());
getBleService().startScan();
return true;
}
return false;
}
/**
* This method requests the {@link BleService} to stop scanning.
*/
protected void stopScan() {
if (isBound()) {
getBleService().stopScan();
}
}
/**
* This method sets the scan type of the {@link BleService}.
*
* @param scanType The {@link BleService.ScanType scan type}
*/
protected void updateScanType(BleService.ScanType scanType) {
Logger.logInfo("Updating scan type to " + scanType);
getBleService().setScanType(scanType);
}
/**
* This method sets the scan filter of the {@link BleService}.
*
* @param scanFilter The {@link ScanFilter scan filter}
*/
protected void updateScanFilter(ScanFilter scanFilter) {
getBleService().setScanFilter(scanFilter);
}
/**
* Override this in order to chose which scan filter is to be used before {@link #startScan} is called when the service starts.
*
* @return The {@link ScanFilter} to be used in the current application state.
*/
protected ScanFilter getScanFilter() {
return new ScanFilter.Builder().setServiceUuid(ParcelUuid.fromString("7265656C-7941-6374-6976-652055554944")).build();
}
/**
* Override this in order to chose which kind of scan is to be used before {@link #startScan} is called when the service starts.
*
* @return The {@link BleService.ScanType} to be used in the current application state.
*/
protected BleService.ScanType getScanType() {
return getActivityCount() == 0 ? BleService.ScanType.LOW_POWER : BleService.ScanType.ACTIVE;
}
/**
* Called by the class in order to check if a scan should be started.<br>
* Override this method if you need to change the behaviour of the scan.
*
* @return true if the conditions for a scan are present, false otherwise.
*/
protected boolean shouldStartScan() {
return isReelyAware(getCurrentActivity());
}
protected boolean hasScanPermissions() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (
ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
) {
return false; // Don't start scanning if we are not allowed to use the location.
}
}
return true;
}
/**
* This method is called when a {@link BleService.Event} is received.<br/>
* Its default behaviour is to notify the currently running {@link ReelyAwareActivity} (if any).<br/>
* Override this and you can customize the behaviour of the application.
*
* @param event The {@link BleService.Event} received from the {@link BleService}.
* @return true if the event was processed, false otherwise;
*/
@Override
public boolean onBleEvent(BleService.Event event, Object data) {
boolean processed = isReelyAware(getCurrentActivity());
switch (event) {
case IN_REGION:
if (processed) { | ((ReelyAwareActivity) getCurrentActivity()).onEnterRegion((ScanResult) data); | 3 |
syvaidya/openstego | src/main/java/com/openstego/desktop/plugin/dwtdugad/DWTDugadPlugin.java | [
"public class OpenStegoException extends Exception {\n private static final long serialVersionUID = 668241029491685413L;\n\n /**\n * Error Code - Unhandled exception\n */\n static final int UNHANDLED_EXCEPTION = 0;\n\n /**\n * Map to store error code to message key mapping\n */\n private static final Map<String, String> errMsgKeyMap = new HashMap<>();\n\n /**\n * Error code for the exception\n */\n private final int errorCode;\n\n /**\n * Namespace for the exception\n */\n private final String namespace;\n\n /**\n * Constructor using default namespace for unhandled exceptions\n *\n * @param cause Original exception which caused this exception to be raised\n */\n public OpenStegoException(Throwable cause) {\n this(cause, OpenStego.NAMESPACE, UNHANDLED_EXCEPTION, (Object[]) null);\n }\n\n /**\n * Default constructor\n *\n * @param cause Original exception which caused this exception to be raised\n * @param namespace Namespace of the error\n * @param errorCode Error code for the exception\n */\n public OpenStegoException(Throwable cause, String namespace, int errorCode) {\n this(cause, namespace, errorCode, (Object[]) null);\n }\n\n /**\n * Constructor with a single parameter for the message\n *\n * @param cause Original exception which caused this exception to be raised\n * @param namespace Namespace of the error\n * @param errorCode Error code for the exception\n * @param param Parameter for exception message\n */\n public OpenStegoException(Throwable cause, String namespace, int errorCode, String param) {\n this(cause, namespace, errorCode, new Object[]{param});\n }\n\n /**\n * Constructor which takes object array for parameters for the message\n *\n * @param cause Original exception which caused this exception to be raised\n * @param namespace Namespace of the error\n * @param errorCode Error code for the exception\n * @param params Parameters for exception message\n */\n public OpenStegoException(Throwable cause, String namespace, int errorCode, Object... params) {\n super((OpenStego.NAMESPACE.equals(namespace) && errorCode == UNHANDLED_EXCEPTION) ? cause.toString()\n : LabelUtil.getInstance(namespace).getString(errMsgKeyMap.get(namespace + errorCode), params), cause);\n\n this.namespace = namespace;\n this.errorCode = errorCode;\n }\n\n /**\n * Get method for errorCode\n *\n * @return errorCode\n */\n public int getErrorCode() {\n return this.errorCode;\n }\n\n /**\n * Get method for namespace\n *\n * @return namespace\n */\n public String getNamespace() {\n return this.namespace;\n }\n\n /**\n * Method to add new error codes to the namespace\n *\n * @param namespace Namespace for the error\n * @param errorCode Error code of the error\n * @param labelKey Key of the label for the error\n */\n public static void addErrorCode(String namespace, int errorCode, String labelKey) {\n errMsgKeyMap.put(namespace + errorCode, labelKey);\n }\n}",
"public abstract class WMImagePluginTemplate extends WatermarkingPlugin<OpenStegoConfig> {\n /**\n * Static list of supported read formats\n */\n protected static List<String> readFormats = null;\n\n /**\n * Static list of supported write formats\n */\n protected static List<String> writeFormats = null;\n\n /**\n * Method to get difference between original cover file and the stegged file\n *\n * @param stegoData Stego data containing the embedded data\n * @param stegoFileName Name of the stego file\n * @param coverData Original cover data\n * @param coverFileName Name of the cover file\n * @param diffFileName Name of the output difference file\n * @return Difference data\n * @throws OpenStegoException Processing issues\n */\n @Override\n public final byte[] getDiff(byte[] stegoData, String stegoFileName, byte[] coverData, String coverFileName, String diffFileName)\n throws OpenStegoException {\n ImageHolder stegoImage;\n ImageHolder coverImage;\n ImageHolder diffImage;\n\n stegoImage = ImageUtil.byteArrayToImage(stegoData, stegoFileName);\n coverImage = ImageUtil.byteArrayToImage(coverData, coverFileName);\n diffImage = ImageUtil.getDiffImage(stegoImage, coverImage);\n\n return ImageUtil.imageToByteArray(diffImage, diffFileName, this);\n }\n\n /**\n * Method to get the list of supported file extensions for reading\n *\n * @return List of supported file extensions for reading\n */\n @Override\n public List<String> getReadableFileExtensions() {\n if (readFormats != null) {\n return readFormats;\n }\n\n String format;\n String[] formats;\n readFormats = new ArrayList<>();\n\n formats = ImageIO.getReaderFormatNames();\n for (String s : formats) {\n format = s.toLowerCase();\n if (format.contains(\"jpeg\") && format.contains(\"2000\")) {\n format = \"jp2\";\n }\n if (!readFormats.contains(format)) {\n readFormats.add(format);\n }\n }\n\n Collections.sort(readFormats);\n return readFormats;\n }\n\n /**\n * Method to get the list of supported file extensions for writing\n *\n * @return List of supported file extensions for writing\n * @throws OpenStegoException Processing issues\n */\n @Override\n public List<String> getWritableFileExtensions() throws OpenStegoException {\n if (writeFormats != null) {\n return writeFormats;\n }\n\n String format;\n String[] formats;\n writeFormats = new ArrayList<>();\n\n formats = ImageIO.getWriterFormatNames();\n for (String s : formats) {\n format = s.toLowerCase();\n if (format.contains(\"jpeg\") && format.contains(\"2000\")) {\n format = \"jp2\";\n }\n if (!writeFormats.contains(format)) {\n writeFormats.add(format);\n }\n }\n\n Collections.sort(writeFormats);\n return writeFormats;\n }\n\n /**\n * Method to populate the standard command-line options used by this plugin\n *\n * @param options Existing command-line options. Plugin-specific options will get added to this list\n */\n @Override\n public void populateStdCmdLineOptions(CmdLineOptions options) {\n }\n\n /**\n * Method to create default configuration data (specific to this plugin)\n *\n * @return Configuration data\n */\n @Override\n protected OpenStegoConfig createConfig() {\n return new OpenStegoConfig();\n }\n\n /**\n * Method to create configuration data (specific to this plugin) based on the command-line options\n *\n * @param options Command-line options\n * @return Configuration data\n * @throws OpenStegoException Processing issues\n */\n @Override\n protected OpenStegoConfig createConfig(CmdLineOptions options) throws OpenStegoException {\n OpenStegoConfig config = new OpenStegoConfig();\n config.initialize(options);\n return config;\n }\n}",
"public class ImageHolder {\n private BufferedImage image;\n private IIOMetadata metadata;\n\n /**\n * Default constructor\n *\n * @param image Image\n * @param metadata Metadata\n */\n public ImageHolder(BufferedImage image, IIOMetadata metadata) {\n this.image = image;\n this.metadata = metadata;\n }\n\n /**\n * Getter method for image\n *\n * @return image\n */\n public BufferedImage getImage() {\n return this.image;\n }\n\n /**\n * Setter method for image\n *\n * @param image Value for image to be set\n */\n public void setImage(BufferedImage image) {\n this.image = image;\n }\n\n /**\n * Getter method for metadata\n *\n * @return metadata\n */\n public IIOMetadata getMetadata() {\n return this.metadata;\n }\n\n /**\n * Setter method for metadata\n *\n * @param metadata Value for metadata to be set\n */\n @SuppressWarnings(\"unused\")\n public void setMetadata(IIOMetadata metadata) {\n this.metadata = metadata;\n }\n}",
"public class ImageUtil {\n\n /**\n * Constructor is private so that this class is not instantiated\n */\n private ImageUtil() {\n }\n\n /**\n * Default image type in case not provided\n */\n public static final String DEFAULT_IMAGE_TYPE = \"png\";\n\n /**\n * Method to generate a random image filled with noise.\n *\n * @param numOfPixels Number of pixels required in the image\n * @return Random image filled with noise\n * @throws OpenStegoException Processing issues\n */\n public static ImageHolder generateRandomImage(int numOfPixels) throws OpenStegoException {\n final double ASPECT_RATIO = 4.0 / 3.0;\n int width;\n int height;\n byte[] rgbValue = new byte[3];\n BufferedImage image;\n SecureRandom random;\n\n try {\n random = SecureRandom.getInstance(\"SHA1PRNG\");\n\n width = (int) Math.ceil(Math.sqrt(numOfPixels * ASPECT_RATIO));\n height = (int) Math.ceil(numOfPixels / (double) width);\n\n image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);\n for (int x = 0; x < width; x++) {\n for (int y = 0; y < height; y++) {\n random.nextBytes(rgbValue);\n image.setRGB(x, y, CommonUtil.byteToInt(rgbValue[0]) +\n (CommonUtil.byteToInt(rgbValue[1]) << 8) +\n (CommonUtil.byteToInt(rgbValue[2]) << 16));\n }\n }\n\n return new ImageHolder(image, null);\n } catch (NoSuchAlgorithmException nsaEx) {\n throw new OpenStegoException(nsaEx);\n }\n }\n\n /**\n * Method to convert BufferedImage to byte array\n *\n * @param image Image data\n * @param imageFileName Name of the image file\n * @param plugin Reference to the plugin\n * @return Image data as byte array\n * @throws OpenStegoException Processing issues\n */\n public static byte[] imageToByteArray(ImageHolder image, String imageFileName, OpenStegoPlugin<?> plugin) throws OpenStegoException {\n ByteArrayOutputStream barrOS = new ByteArrayOutputStream();\n String imageType;\n\n if (imageFileName != null) {\n imageType = imageFileName.substring(imageFileName.lastIndexOf('.') + 1).toLowerCase();\n if (!plugin.getWritableFileExtensions().contains(imageType)) {\n throw new OpenStegoException(null, OpenStego.NAMESPACE, OpenStegoErrors.IMAGE_TYPE_INVALID, imageType);\n }\n if (imageType.equals(\"jp2\")) {\n imageType = \"jpeg 2000\";\n }\n writeImage(image, imageType, barrOS);\n } else {\n writeImage(image, DEFAULT_IMAGE_TYPE, barrOS);\n }\n return barrOS.toByteArray();\n }\n\n /**\n * Method to convert byte array to image\n *\n * @param imageData Image data as byte array\n * @param imgFileName Name of the image file\n * @return Buffered image\n * @throws OpenStegoException Processing issues\n */\n public static ImageHolder byteArrayToImage(byte[] imageData, String imgFileName) throws OpenStegoException {\n if (imageData == null) {\n return null;\n }\n\n ImageHolder image = readImage(new ByteArrayInputStream(imageData));\n if (image == null) {\n throw new OpenStegoException(null, OpenStego.NAMESPACE, OpenStegoErrors.IMAGE_FILE_INVALID, imgFileName);\n }\n return image;\n }\n\n /**\n * Get RGB data array from given image\n *\n * @param image Image\n * @return List with three elements of two-dimensional int's - R, G and B\n */\n @SuppressWarnings(\"unused\")\n public static List<int[][]> getRgbFromImage(BufferedImage image) {\n List<int[][]> rgb = new ArrayList<>();\n int[][] r;\n int[][] g;\n int[][] b;\n int width;\n int height;\n\n width = image.getWidth();\n height = image.getHeight();\n\n r = new int[height][width];\n g = new int[height][width];\n b = new int[height][width];\n\n for (int i = 0; i < height; i++) {\n for (int j = 0; j < width; j++) {\n r[i][j] = (image.getRGB(j, i) >> 16) & 0xFF;\n g[i][j] = (image.getRGB(j, i) >> 8) & 0xFF;\n b[i][j] = (image.getRGB(j, i)) & 0xFF;\n }\n }\n\n rgb.add(r);\n rgb.add(g);\n rgb.add(b);\n\n return rgb;\n }\n\n /**\n * Get YUV data from given image's RGB data\n *\n * @param image Image\n * @return List with three elements of two-dimensional int's - Y, U and V\n */\n public static List<int[][]> getYuvFromImage(BufferedImage image) {\n List<int[][]> yuv = new ArrayList<>();\n int[][] y;\n int[][] u;\n int[][] v;\n int[][] aa;\n int a;\n int r;\n int g;\n int b;\n int width;\n int height;\n\n width = image.getWidth();\n height = image.getHeight();\n\n y = new int[height][width];\n u = new int[height][width];\n v = new int[height][width];\n aa = new int[height][width];\n\n for (int i = 0; i < height; i++) {\n for (int j = 0; j < width; j++) {\n a = (image.getRGB(j, i) >> 24) & 0xFF;\n r = (image.getRGB(j, i) >> 16) & 0xFF;\n g = (image.getRGB(j, i) >> 8) & 0xFF;\n b = (image.getRGB(j, i)) & 0xFF;\n\n // Convert RGB to YUV colorspace\n y[i][j] = (int) ((0.299 * r) + (0.587 * g) + (0.114 * b));\n u[i][j] = (int) ((-0.147 * r) - (0.289 * g) + (0.436 * b));\n v[i][j] = (int) ((0.615 * r) - (0.515 * g) - (0.100 * b));\n aa[i][j] = a;\n }\n }\n\n yuv.add(y);\n yuv.add(u);\n yuv.add(v);\n yuv.add(aa);\n\n return yuv;\n }\n\n /**\n * Get image from given RGB data\n *\n * @param rgb List with three elements of two-dimensional int's - R, G and B\n * @return Image\n */\n @SuppressWarnings(\"unused\")\n public static BufferedImage getImageFromRgb(List<int[][]> rgb) {\n BufferedImage image;\n int width;\n int height;\n int[][] r;\n int[][] g;\n int[][] b;\n\n r = rgb.get(0);\n g = rgb.get(1);\n b = rgb.get(2);\n\n height = r.length;\n width = r[0].length;\n image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);\n\n for (int i = 0; i < height; i++) {\n for (int j = 0; j < width; j++) {\n image.setRGB(j, i, (r[i][j] << 16) + (g[i][j] << 8) + b[i][j]);\n }\n }\n\n return image;\n }\n\n /**\n * Get image (with RGB data) from given YUV data\n *\n * @param yuv List with three elements of two-dimensional int's - Y, U and V\n * @param imgType Type of image (e.g. BufferedImage.TYPE_INT_RGB)\n * @return Image\n */\n public static BufferedImage getImageFromYuv(List<int[][]> yuv, int imgType) {\n BufferedImage image;\n int width;\n int height;\n int a;\n int r;\n int g;\n int b;\n int[][] y;\n int[][] u;\n int[][] v;\n int[][] aa;\n\n y = yuv.get(0);\n u = yuv.get(1);\n v = yuv.get(2);\n aa = yuv.get(3);\n\n height = y.length;\n width = y[0].length;\n image = new BufferedImage(width, height, (imgType == 0 ? BufferedImage.TYPE_INT_RGB : imgType));\n\n for (int i = 0; i < height; i++) {\n for (int j = 0; j < width; j++) {\n // Convert YUV back to RGB\n r = pixelRange(y[i][j] + 1.140 * v[i][j]);\n g = pixelRange(y[i][j] - 0.395 * u[i][j] - 0.581 * v[i][j]);\n b = pixelRange(y[i][j] + 2.032 * u[i][j]);\n a = aa[i][j];\n\n image.setRGB(j, i, (a << 24) + (r << 16) + (g << 8) + b);\n }\n }\n\n return image;\n }\n\n /**\n * Utility method to limit the value within [0,255] range\n *\n * @param p Input value\n * @return Limited value\n */\n public static int pixelRange(int p) {\n return ((p > 255) ? 255 : Math.max(p, 0));\n }\n\n /**\n * Utility method to limit the value within [0,255] range\n *\n * @param p Input value\n * @return Limited value\n */\n public static int pixelRange(double p) {\n return ((p > 255) ? 255 : (p < 0) ? 0 : (int) p);\n }\n\n /**\n * Method to pad an image such that it becomes perfect square. The padding uses black color\n *\n * @param image Input image\n */\n public static void makeImageSquare(ImageHolder image) {\n int max;\n\n max = Math.max(image.getImage().getWidth(), image.getImage().getHeight());\n cropImage(image, max, max);\n }\n\n /**\n * Method crop an image to the given dimensions. If dimensions are more than the input image size, then the image\n * gets padded with black color\n *\n * @param image Input image\n * @param cropWidth Width required for cropped image\n * @param cropHeight Height required for cropped image\n */\n public static void cropImage(ImageHolder image, int cropWidth, int cropHeight) {\n BufferedImage retImg;\n int width;\n int height;\n\n width = image.getImage().getWidth();\n height = image.getImage().getHeight();\n\n retImg = new BufferedImage(cropWidth, cropHeight, BufferedImage.TYPE_INT_RGB);\n\n for (int i = 0; i < cropWidth; i++) {\n for (int j = 0; j < cropHeight; j++) {\n if (i < width && j < height) {\n retImg.setRGB(i, j, image.getImage().getRGB(i, j));\n } else {\n retImg.setRGB(i, j, 0);\n }\n }\n }\n\n image.setImage(retImg);\n }\n\n /**\n * Method generate difference image between two given images\n *\n * @param leftImage Left input image\n * @param rightImage Right input image\n * @return Difference image\n * @throws OpenStegoException Processing issues\n */\n public static ImageHolder getDiffImage(ImageHolder leftImage, ImageHolder rightImage) throws OpenStegoException {\n int leftW;\n int leftH;\n int rightW;\n int rightH;\n int min;\n int max;\n int diff;\n BufferedImage diffImage;\n\n leftW = leftImage.getImage().getWidth();\n leftH = leftImage.getImage().getHeight();\n rightW = rightImage.getImage().getWidth();\n rightH = rightImage.getImage().getHeight();\n if (leftW != rightW || leftH != rightH) {\n throw new OpenStegoException(null, OpenStego.NAMESPACE, OpenStegoErrors.IMAGE_FILE_INVALID);\n }\n diffImage = new BufferedImage(leftW, leftH, BufferedImage.TYPE_INT_RGB);\n\n min = Math.abs(leftImage.getImage().getRGB(0, 0) - rightImage.getImage().getRGB(0, 0));\n max = min;\n\n for (int i = 0; i < leftW; i++) {\n for (int j = 0; j < leftH; j++) {\n diff = Math.abs(leftImage.getImage().getRGB(i, j) - rightImage.getImage().getRGB(i, j));\n // error += diff * diff;\n if (diff < min) {\n min = diff;\n }\n if (diff > max) {\n max = diff;\n }\n }\n }\n\n for (int i = 0; i < leftW; i++) {\n for (int j = 0; j < leftH; j++) {\n diff = Math.abs(leftImage.getImage().getRGB(i, j) - rightImage.getImage().getRGB(i, j));\n diffImage.setRGB(i, j, pixelRange((double) (diff - min) / (double) (max - min) * Math.pow(2, 32)));\n // TODO\n }\n }\n\n return new ImageHolder(diffImage, null);\n }\n\n private static void writeImage(ImageHolder image, String imageType, OutputStream os) throws OpenStegoException {\n if (\"jpeg\".equals(imageType) || \"jpg\".equals(imageType)) {\n writeJpegImage(image, os);\n } else {\n try {\n ImageWriter writer = ImageIO.getImageWritersByFormatName(imageType).next();\n writer.setOutput(ImageIO.createImageOutputStream(os));\n writer.write(null, new IIOImage(image.getImage(), null, image.getMetadata()), null);\n } catch (IOException e) {\n throw new OpenStegoException(e);\n }\n }\n }\n\n private static void writeJpegImage(ImageHolder image, OutputStream os) throws OpenStegoException {\n try {\n JPEGImageWriteParam jpegParams = new JPEGImageWriteParam(null);\n jpegParams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);\n jpegParams.setOptimizeHuffmanTables(true);\n Float qual = UserPreferences.getFloat(\"image.writer.jpeg.quality\");\n if (qual == null) {\n qual = 0.75f;\n }\n jpegParams.setCompressionQuality(qual);\n\n ImageWriter writer = ImageIO.getImageWritersByFormatName(\"jpg\").next();\n writer.setOutput(ImageIO.createImageOutputStream(os));\n writer.write(null, new IIOImage(image.getImage(), null, image.getMetadata()), jpegParams);\n } catch (IOException e) {\n throw new OpenStegoException(e);\n }\n }\n\n private static ImageHolder readImage(InputStream is) throws OpenStegoException {\n try {\n ImageInputStream imageIS = ImageIO.createImageInputStream(is);\n Iterator<ImageReader> readers = ImageIO.getImageReaders(imageIS);\n if (!readers.hasNext()) {\n return null;\n }\n\n ImageReader reader = readers.next();\n reader.setInput(imageIS);\n BufferedImage image = reader.read(0);\n IIOMetadata metadata = reader.getImageMetadata(0);\n return new ImageHolder(image, metadata);\n } catch (IOException e) {\n throw new OpenStegoException(e);\n }\n }\n\n}",
"public class LabelUtil {\n /**\n * Static variable to hold the map of labels loaded from resource files\n */\n private static final Map<String, ResourceBundle> map = new HashMap<>();\n\n /**\n * Static variable to store the namespace map\n */\n private static final Map<String, LabelUtil> namespaceMap = new HashMap<>();\n\n /**\n * Method to add new namespace using resource bundle\n *\n * @param namespace Namespace for the labels\n * @param bundle Resource bundle name\n */\n public static void addNamespace(String namespace, String bundle) {\n map.put(namespace, ResourceBundle.getBundle(bundle, Locale.getDefault()));\n }\n\n /**\n * Method to get instance of LabelUtil based on the namespace\n *\n * @param namespace Namespace for the labels\n * @return Instance of LabelUtil\n */\n public static LabelUtil getInstance(String namespace) {\n LabelUtil util;\n\n util = namespaceMap.get(namespace);\n if (util == null) {\n util = new LabelUtil(namespace);\n namespaceMap.put(namespace, util);\n }\n\n return util;\n }\n\n /**\n * Variable to store the current namespace\n */\n private final String namespace;\n\n /**\n * Constructor is protected\n *\n * @param namespace Namespace for the label\n */\n protected LabelUtil(String namespace) {\n this.namespace = namespace;\n }\n\n /**\n * Method to get label value for the given label key\n *\n * @param key Key for the label\n * @return Display value for the label\n */\n public String getString(String key) {\n return (map.get(this.namespace)).getString(key);\n }\n\n /**\n * Method to get label value for the given label key (using optional parameters)\n *\n * @param key Key for the label\n * @param parameters Parameters to pass for a parameterized label\n * @return Display value for the label\n */\n public String getString(String key, Object... parameters) {\n return MessageFormat.format(getString(key), parameters);\n }\n}",
"public class StringUtil {\n /**\n * Constructor is private so that this class is not instantiated\n */\n private StringUtil() {\n }\n\n /**\n * Method to convert byte array to hexadecimal string\n *\n * @param raw Raw byte array\n * @return Hex string\n */\n public static String getHexString(byte[] raw) {\n BigInteger bigInteger = new BigInteger(1, raw);\n return String.format(\"%0\" + (raw.length << 1) + \"x\", bigInteger);\n }\n\n /**\n * Method to get the long hash from the password. This is used for seeding the random number generator\n *\n * @param password Password to hash\n * @return Long hash of the password\n */\n public static long passwordHash(String password) throws OpenStegoException {\n final long DEFAULT_HASH = 98234782; // Default to a random (but constant) seed\n byte[] byteHash;\n String hexString;\n\n if (password == null || password.equals(\"\")) {\n return DEFAULT_HASH;\n }\n\n try {\n byteHash = MessageDigest.getInstance(\"MD5\").digest(password.getBytes(StandardCharsets.UTF_8));\n hexString = getHexString(byteHash);\n\n // Hex string will be 32 bytes long whereas parsing to long can handle only 16 bytes, so trim it\n hexString = hexString.substring(0, 15);\n return Long.parseLong(hexString, 16);\n } catch (NoSuchAlgorithmException nsaEx) {\n throw new OpenStegoException(nsaEx);\n }\n }\n\n /**\n * Method to tokenize a string by line breaks\n *\n * @param input Input string\n * @return List of strings tokenized by line breaks\n * @throws OpenStegoException Processing issues\n */\n public static List<String> getStringLines(String input) throws OpenStegoException {\n String str;\n List<String> stringList = new ArrayList<>();\n BufferedReader reader;\n\n try {\n reader = new BufferedReader(new StringReader(input));\n while ((str = reader.readLine()) != null) {\n str = str.trim();\n if (str.equals(\"\") || str.startsWith(\"#\")) {\n continue;\n }\n stringList.add(str.trim());\n }\n } catch (IOException ioEx) {\n throw new OpenStegoException(ioEx);\n }\n\n return stringList;\n }\n}",
"public class DWT {\n /**\n * Master map of filters\n */\n private static Map<Integer, FilterGH> filterGHMap = null;\n\n /**\n * URI for the filter file\n */\n private static final String FILTER_FILE = \"/dwt/filters.xml\";\n\n /**\n * List of loaded filters\n */\n private final FilterGH[] filters;\n\n /**\n * Wavelet filtering method\n */\n private final int method;\n\n /**\n * No. of columns in the image\n */\n private final int cols;\n\n /**\n * No. of rows in the image\n */\n private final int rows;\n\n /**\n * Wavelet decomposition level\n */\n private final int level;\n\n /**\n * Default constructor\n *\n * @param cols Image width\n * @param rows Image height\n * @param filterID Filter ID to use\n * @param level Decomposition level\n * @param method Wavelet filtering method\n */\n public DWT(int cols, int rows, int filterID, int level, int method) {\n // Read the master filter file if it is not already loaded\n if (filterGHMap == null) {\n filterGHMap = FilterXMLReader.parse(FILTER_FILE);\n }\n\n this.filters = new FilterGH[level + 1];\n for (int i = 0; i <= level; i++) {\n this.filters[i] = filterGHMap.get(filterID);\n }\n\n this.level = level;\n this.method = method;\n this.cols = cols;\n this.rows = rows;\n }\n\n /**\n * Method to perform forward DWT on the pixel data\n *\n * @param pixels Image pixel data\n * @return Image tree data after DWT\n */\n public ImageTree forwardDWT(int[][] pixels) {\n Image image;\n ImageTree tree;\n\n image = new Image(this.cols, this.rows);\n\n for (int i = 0; i < this.rows; i++) {\n for (int j = 0; j < this.cols; j++) {\n DWTUtil.setPixel(image, j, i, pixels[i][j]);\n }\n }\n\n tree = DWTUtil.waveletTransform(image, this.level, this.filters, this.method);\n return tree;\n }\n\n /**\n * Method to perform inverse DWT to get back the pixel data\n *\n * @param dwts DWT data as image tree\n * @param pixels Image pixel data\n */\n public void inverseDWT(ImageTree dwts, int[][] pixels) {\n Image image;\n\n image = DWTUtil.inverseTransform(dwts, this.filters, this.method + 1);\n\n for (int i = 0; i < this.rows; i++) {\n for (int j = 0; j < this.cols; j++) {\n pixels[i][j] = ImageUtil.pixelRange((int) (DWTUtil.getPixel(image, j, i) + 0.5));\n }\n }\n }\n}",
"public class Image {\n /**\n * Image data\n */\n private double[] data;\n\n /**\n * Image width\n */\n int width;\n\n /**\n * Image height\n */\n int height;\n\n /**\n * Default constructor\n *\n * @param width Width of the image\n * @param height Height of the image\n */\n public Image(int width, int height) {\n this.data = new double[width * height];\n this.width = width;\n this.height = height;\n }\n\n /**\n * Get method for data\n *\n * @return data\n */\n public double[] getData() {\n return this.data;\n }\n\n /**\n * Set method for data\n *\n * @param data Value to be set\n */\n public void setData(double[] data) {\n this.data = data;\n }\n\n /**\n * Get method for width\n *\n * @return width\n */\n public int getWidth() {\n return this.width;\n }\n\n /**\n * Set method for width\n *\n * @param width Value to be set\n */\n public void setWidth(int width) {\n this.width = width;\n }\n\n /**\n * Get method for height\n *\n * @return height\n */\n public int getHeight() {\n return this.height;\n }\n\n /**\n * Set method for height\n *\n * @param height Value to be set\n */\n public void setHeight(int height) {\n this.height = height;\n }\n}",
"public class ImageTree {\n private ImageTree coarse = null;\n\n private ImageTree horizontal = null;\n\n private ImageTree vertical = null;\n\n private ImageTree diagonal = null;\n\n private Image image = null;\n\n private int level = 0;\n\n private int flag = 0;\n\n /**\n * Get method for coarse\n *\n * @return coarse\n */\n public ImageTree getCoarse() {\n return this.coarse;\n }\n\n /**\n * Set method for coarse\n *\n * @param coarse Value to be set\n */\n public void setCoarse(ImageTree coarse) {\n this.coarse = coarse;\n }\n\n /**\n * Get method for horizontal\n *\n * @return horizontal\n */\n public ImageTree getHorizontal() {\n return this.horizontal;\n }\n\n /**\n * Set method for horizontal\n *\n * @param horizontal Value to be set\n */\n public void setHorizontal(ImageTree horizontal) {\n this.horizontal = horizontal;\n }\n\n /**\n * Get method for vertical\n *\n * @return vertical\n */\n public ImageTree getVertical() {\n return this.vertical;\n }\n\n /**\n * Set method for vertical\n *\n * @param vertical Value to be set\n */\n public void setVertical(ImageTree vertical) {\n this.vertical = vertical;\n }\n\n /**\n * Get method for diagonal\n *\n * @return diagonal\n */\n public ImageTree getDiagonal() {\n return this.diagonal;\n }\n\n /**\n * Set method for diagonal\n *\n * @param diagonal Value to be set\n */\n public void setDiagonal(ImageTree diagonal) {\n this.diagonal = diagonal;\n }\n\n /**\n * Get method for image\n *\n * @return image\n */\n public Image getImage() {\n return this.image;\n }\n\n /**\n * Set method for image\n *\n * @param image Value to be set\n */\n public void setImage(Image image) {\n this.image = image;\n }\n\n /**\n * Get method for level\n *\n * @return level\n */\n public int getLevel() {\n return this.level;\n }\n\n /**\n * Set method for level\n *\n * @param level Value to be set\n */\n public void setLevel(int level) {\n this.level = level;\n }\n\n /**\n * Get method for flag\n *\n * @return flag\n */\n public int getFlag() {\n return this.flag;\n }\n\n /**\n * Set method for flag\n *\n * @param flag Value to be set\n */\n public void setFlag(int flag) {\n this.flag = flag;\n }\n}"
] | import com.openstego.desktop.OpenStegoException;
import com.openstego.desktop.plugin.template.image.WMImagePluginTemplate;
import com.openstego.desktop.util.ImageHolder;
import com.openstego.desktop.util.ImageUtil;
import com.openstego.desktop.util.LabelUtil;
import com.openstego.desktop.util.StringUtil;
import com.openstego.desktop.util.dwt.DWT;
import com.openstego.desktop.util.dwt.Image;
import com.openstego.desktop.util.dwt.ImageTree;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Random; | /*
* Steganography utility to hide messages into cover files
* Author: Samir Vaidya (mailto:syvaidya@gmail.com)
* Copyright (c) Samir Vaidya
*/
package com.openstego.desktop.plugin.dwtdugad;
/**
* Plugin for OpenStego which implements the DWT based algorithm by Dugad.
* <p>
* This class is based on the code provided by Peter Meerwald at: <a
* href="http://www.cosy.sbg.ac.at/~pmeerw/Watermarking/">http://www.cosy.sbg.ac.at/~pmeerw/Watermarking/</a>
* <p>
* Refer to his thesis on watermarking: Peter Meerwald, Digital Image Watermarking in the Wavelet Transfer Domain,
* Master's Thesis, Department of Scientific Computing, University of Salzburg, Austria, January 2001.
*/
public class DWTDugadPlugin extends WMImagePluginTemplate {
/**
* LabelUtil instance to retrieve labels
*/
private static final LabelUtil labelUtil = LabelUtil.getInstance(DWTDugadPlugin.NAMESPACE);
/**
* Constant for Namespace to use for this plugin
*/
public final static String NAMESPACE = "DWTDUGAD";
private static final String SIG_MARKER = "DGSG";
private static final String WM_MARKER = "DGWM";
/**
* Default constructor
*/
public DWTDugadPlugin() {
LabelUtil.addNamespace(NAMESPACE, "i18n.DWTDugadPluginLabels");
DWTDugadErrors.init(); // Initialize error codes
}
/**
* Gives the name of the plugin
*
* @return Name of the plugin
*/
@Override
public String getName() {
return "DWTDugad";
}
/**
* Gives a short description of the plugin
*
* @return Short description of the plugin
*/
@Override
public String getDescription() {
return labelUtil.getString("plugin.description");
}
/**
* Method to embed the message into the cover data
*
* @param msg Message to be embedded
* @param msgFileName Name of the message file. If this value is provided, then the filename should be embedded in
* the cover data
* @param cover Cover data into which message needs to be embedded
* @param coverFileName Name of the cover file
* @param stegoFileName Name of the output stego file
* @return Stego data containing the message
* @throws OpenStegoException Processing issues
*/
@Override
public byte[] embedData(byte[] msg, String msgFileName, byte[] cover, String coverFileName, String stegoFileName) throws OpenStegoException { | ImageHolder image; | 2 |
comtel2000/mokka7 | mokka7-samples/src/main/java/org/comtel2000/mokka7/clone/HearbeatSample2.java | [
"public abstract class ClientRunner {\n\n protected static byte[] buffer = new byte[1024];\n\n protected static final Logger logger = LoggerFactory.getLogger(ClientRunner.class);\n\n private static final String host = \"127.0.0.1\";\n private static final int rack = 0;\n private static final int slot = 2;\n\n public ClientRunner() {\n this(host, rack, slot);\n }\n\n public ClientRunner(String host, int rack, int slot) {\n MonitoredS7Client client = new MonitoredS7Client();\n client.start(Duration.ofSeconds(10));\n long time = System.currentTimeMillis();\n try {\n if (client.connect(host, rack, slot)) {\n logger.info(\"connected in {}ms\", System.currentTimeMillis() - time);\n S7OrderCode orderCode = client.getOrderCode();\n if (orderCode != null) {\n logger.debug(\"Order Code\\t: {}\", orderCode.getCode());\n logger.debug(\"Firmware\\t: {}\", orderCode.getFirmware());\n }\n\n S7CpInfo cpInfo = client.getCpInfo();\n if (cpInfo != null) {\n logger.debug(\"Max PDU Length\\t: {}\", cpInfo.maxPduLength);\n logger.debug(\"Max connections\\t: {}\", cpInfo.maxConnections);\n logger.debug(\"Max MPI (bps)\\t: {}\", cpInfo.maxMpiRate);\n logger.debug(\"Max Bus (bps)\\t: {}\", cpInfo.maxBusRate);\n }\n time = System.currentTimeMillis();\n call(client);\n }\n } catch (Exception e) {\n logger.error(e.getMessage(), e);\n } finally {\n logger.info(\"finished after {}ms\", (System.currentTimeMillis() - time));\n client.report();\n client.disconnect();\n client.close();\n }\n }\n\n public abstract void call(S7Client client) throws Exception;\n\n protected void checkResult(int result) {\n if (result != 0) {\n logger.error(\"(0x{}) {}\", Integer.toHexString(result), ReturnCode.getErrorText(result));\n }\n }\n\n protected static void bitSet(byte b) {\n String hex = Integer.toHexString(b & 0x0FF).toUpperCase();\n System.out.println((hex.length() == 1 ? \"0\" + hex : hex) + \":\\t\" + BitSet.valueOf(new byte[] { b }));\n }\n\n}",
"public class S7Client implements Client, ReturnCode {\n\n private static final Logger logger = LoggerFactory.getLogger(S7Client.class);\n\n private int pduLength = 0;\n\n private boolean connected = false;\n\n private S7Config config;\n\n private Socket tcpSocket;\n private BufferedInputStream inStream;\n private OutputStream outStream;\n\n private byte lastPDUType;\n\n private final byte[] pdu = new byte[2048];\n\n private int recvTimeout = RECV_TIMEOUT;\n\n private final static int MAX_INC_COUNT = 0xffff;\n\n private final AtomicInteger counter = new AtomicInteger(-1);\n\n public S7Client() {\n this(new S7Config());\n }\n\n public S7Client(S7Config config) {\n Arrays.fill(buffer, (byte) 0);\n this.setConfig(config);\n }\n\n public S7Config getConfig() {\n return config;\n }\n\n public void setConfig(S7Config config) {\n this.config = Objects.requireNonNull(config);\n }\n\n private void resetCounter() {\n counter.set(-1);\n }\n\n private int incrementAndGet() {\n if (counter.compareAndSet(MAX_INC_COUNT, 0)) {\n return 0;\n }\n return counter.incrementAndGet();\n }\n\n @Override\n public boolean clearSessionPassword() throws S7Exception {\n if (sendPacket(S7_CLR_PWD)) {\n int length = recvIsoPacket();\n if (length < 31) {\n throw buildException(ISO_INVALID_PDU);\n }\n if (S7.getWordAt(pdu, 27) != 0) {\n throw buildException(S7_FUNCTION_ERROR);\n }\n return true;\n }\n return false;\n }\n\n @Override\n public boolean connect() throws S7Exception {\n logger.debug(\"try to connect to {}:{}\", config.getHost(), config.getPort());\n if (connected) {\n disconnect();\n }\n try {\n openTcpConnect(5000);\n openIsoConnect();\n updateNegotiatePduLength();\n } catch (S7Exception e) {\n disconnect();\n throw e;\n }\n return connected = true;\n }\n\n @Override\n public boolean connect(String address, int rack, int slot) throws S7Exception {\n config.setHost(address);\n config.setRack(rack);\n config.setSlot(slot);\n config.setRemoteTSAP((config.getType().getValue() << 8) + (rack * 0x20) + slot);\n return connect();\n }\n\n @Override\n public boolean isConnected() {\n return connected;\n }\n\n public int getRecvTimeout() {\n return recvTimeout;\n }\n\n public void setRecvTimeout(int recvTimeout) {\n this.recvTimeout = recvTimeout;\n }\n\n @Override\n public int dbGet(int db, byte[] buffer) throws S7Exception {\n S7BlockInfo block = getAgBlockInfo(BlockType.DB, db);\n if (block != null) {\n int sizeToRead = block.mc7Size;\n // Checks the room\n if (sizeToRead > buffer.length) {\n logger.error(\"buffer size to small ({}/{})\", sizeToRead, buffer.length);\n throw buildException(S7_BUFFER_TOO_SMALL);\n }\n if (readArea(AreaType.DB, db, 0, sizeToRead, DataType.BYTE, buffer) > 0) {\n return sizeToRead;\n }\n }\n throw buildException(S7_FUNCTION_ERROR);\n }\n\n @Override\n public int dbFill(int db, byte fill) throws S7Exception {\n S7BlockInfo block = getAgBlockInfo(BlockType.DB, db);\n if (block != null) {\n byte[] buffer = new byte[block.mc7Size];\n Arrays.fill(buffer, fill);\n if (writeArea(AreaType.DB, db, 0, buffer.length, DataType.BYTE, buffer)) {\n return buffer.length;\n }\n }\n throw buildException(S7_FUNCTION_ERROR);\n }\n\n @Override\n public void disconnect() {\n logger.debug(\"disconnecting..\");\n closeSilently(inStream);\n closeSilently(outStream);\n closeSilently(tcpSocket);\n connected = false;\n pduLength = 0;\n }\n\n @Override\n public S7BlockInfo getAgBlockInfo(BlockType blockType, int blockNumber) throws S7Exception {\n // Block Type\n S7_BI[30] = blockType.getValue();\n // Block Number\n S7_BI[31] = (byte) ((blockNumber / 10000) + 0x30);\n blockNumber = blockNumber % 10000;\n S7_BI[32] = (byte) ((blockNumber / 1000) + 0x30);\n blockNumber = blockNumber % 1000;\n S7_BI[33] = (byte) ((blockNumber / 100) + 0x30);\n blockNumber = blockNumber % 100;\n S7_BI[34] = (byte) ((blockNumber / 10) + 0x30);\n blockNumber = blockNumber % 10;\n S7_BI[35] = (byte) ((blockNumber) + 0x30);\n\n if (sendPacket(S7_BI)) {\n int length = recvIsoPacket();\n if (length < 28) {\n throw buildException(ISO_INVALID_PDU);\n }\n if (S7.getWordAt(pdu, 27) != 0) {\n throw buildException(S7.getWordAt(pdu, 27));\n }\n return S7BlockInfo.of(pdu, 42);\n }\n throw buildException(S7_FUNCTION_ERROR);\n }\n\n @Override\n public S7BlockList getS7BlockList() throws S7Exception {\n\n S7.setWordAt(S7_BL, 11, incrementAndGet());\n if (sendPacket(S7_BL)) {\n int length = recvIsoPacket();\n if (length < 28) {\n throw buildException(ISO_INVALID_PDU);\n }\n if (S7.getWordAt(pdu, 27) != 0) {\n throw buildException(S7.getWordAt(pdu, 27));\n }\n return S7BlockList.of(pdu, 33);\n }\n throw buildException(S7_FUNCTION_ERROR);\n }\n\n @Override\n public S7CpInfo getCpInfo() throws S7Exception {\n S7Szl szl = getSzl(0x0131, 0x0001, 1024);\n return S7CpInfo.of(szl.data, 0);\n }\n\n @Override\n public S7CpuInfo getCpuInfo() throws S7Exception {\n S7Szl szl = getSzl(0x001C, 0x0000, 1024);\n return S7CpuInfo.of(szl.data, 0);\n }\n\n @Override\n public S7OrderCode getOrderCode() throws S7Exception {\n S7Szl szl = getSzl(0x0011, 0x0000, 1024);\n return S7OrderCode.of(szl.data, 0, szl.dataSize);\n }\n\n @Override\n public LocalDateTime getPlcDateTime() throws S7Exception {\n if (sendPacket(S7_GET_DT)) {\n int length = recvIsoPacket();\n if (length < 31) {\n throw buildException(ISO_INVALID_PDU);\n }\n\n if (S7.getWordAt(pdu, 27) != 0) {\n throw buildException(S7.getWordAt(pdu, 27));\n }\n\n if (pdu[29] == (byte) 0xff) {\n return S7.getDateTimeAt(pdu, 35);\n }\n }\n throw buildException(S7_FUNCTION_ERROR);\n }\n\n @Override\n public PlcCpuStatus getPlcStatus() throws S7Exception {\n if (sendPacket(S7_GET_STAT)) {\n int length = recvIsoPacket();\n if (length < 31) {\n throw buildException(ISO_INVALID_PDU);\n }\n if (S7.getWordAt(pdu, 27) != 0) {\n throw buildException(S7.getWordAt(pdu, 27));\n }\n return PlcCpuStatus.valueOf(pdu[44]);\n }\n throw buildException(S7_FUNCTION_ERROR);\n }\n\n @Override\n public S7Protection getProtection() throws S7Exception {\n S7Szl szl = getSzl(0x0232, 0x0004, 256);\n return S7Protection.of(szl.data);\n }\n\n private void openTcpConnect(int timeout) throws S7Exception {\n try {\n tcpSocket = new Socket();\n tcpSocket.connect(new InetSocketAddress(config.getHost(), config.getPort()), timeout);\n tcpSocket.setTcpNoDelay(true);\n tcpSocket.setSoTimeout(recvTimeout);\n inStream = new BufferedInputStream(tcpSocket.getInputStream());\n outStream = new BufferedOutputStream(tcpSocket.getOutputStream());\n } catch (IOException e) {\n throw buildException(TCP_CONNECTION_FAILED, e);\n }\n }\n\n private void openIsoConnect() throws S7Exception {\n\n int locTSAP = config.getLocalTSAP() & 0x0000FFFF;\n int remTSAP = config.getRemoteTSAP() & 0x0000FFFF;\n\n ISO_CR[16] = (byte) (locTSAP >> 8);\n ISO_CR[17] = (byte) (locTSAP & 0x00FF);\n ISO_CR[20] = (byte) (remTSAP >> 8);\n ISO_CR[21] = (byte) (remTSAP & 0x00FF);\n\n if (sendPacket(ISO_CR)) {\n int length = recvIsoPacket();\n if (length != 22) {\n logger.warn(\"invalid PDU length: {} ({})\", length, 22);\n if (length == 33) {\n return;\n }\n throw buildException(ISO_INVALID_PDU);\n }\n if (lastPDUType == (byte) 0xd0) {\n return;\n }\n }\n throw buildException(ISO_CONNECTION_FAILED);\n }\n\n private boolean updateNegotiatePduLength() throws S7Exception {\n resetCounter();\n // Set PDU Size Requested\n S7.setWordAt(S7_PN, 23, DEFAULT_PDU_SIZE_REQUESTED);\n if (sendPacket(S7_PN)) {\n int length = recvIsoPacket();\n if (length != 27) {\n throw buildException(ISO_NEGOTIATING_PDU);\n }\n // check S7 Error: 20 = size of Negotiate Answer\n if (pdu[17] != (byte) 0x00 || pdu[18] != (byte) 0x00) {\n throw buildException(ISO_NEGOTIATING_PDU);\n }\n pduLength = S7.getWordAt(pdu, 25);\n logger.debug(\"PDU negotiated length: {} bytes\", pduLength);\n if (pduLength < 1) {\n throw buildException(ISO_NEGOTIATING_PDU);\n }\n return true;\n }\n return false;\n }\n\n @Override\n public int getPduLength() {\n return pduLength;\n }\n\n @Override\n public boolean setPlcColdStart() throws S7Exception {\n if (sendPacket(S7_COLD_START)) {\n int length = recvIsoPacket();\n if (length < 19) {\n throw buildException(ISO_INVALID_PDU);\n }\n if (S7.getWordAt(pdu, 17) != 0) {\n throw buildException(S7_FUNCTION_ERROR);\n }\n return true;\n }\n return false;\n }\n\n @Override\n public boolean setPlcHotStart() throws S7Exception {\n if (sendPacket(S7_HOT_START)) {\n int length = recvIsoPacket();\n if (length < 19) {\n throw buildException(ISO_INVALID_PDU);\n }\n if (S7.getWordAt(pdu, 17) != 0) {\n throw buildException(S7_FUNCTION_ERROR);\n }\n return true;\n }\n return false;\n }\n\n @Override\n public boolean setPlcStop() throws S7Exception {\n if (sendPacket(S7_STOP)) {\n int length = recvIsoPacket();\n if (length < 19) {\n throw buildException(ISO_INVALID_PDU);\n }\n if (S7.getWordAt(pdu, 17) != 0) {\n throw buildException(S7_FUNCTION_ERROR);\n }\n return true;\n }\n return false;\n }\n\n @Override\n public boolean readMultiVars(S7DataItem[] items, int itemsCount) throws S7Exception {\n int offset;\n int length;\n int itemSize;\n byte[] s7Item = new byte[12];\n byte[] s7ItemRead = new byte[1024];\n\n // Checks items\n if (itemsCount > MAX_VARS) {\n throw buildException(ERR_TOO_MANY_ITEMS);\n }\n\n S7.setWordAt(S7_MRD_HEADER, 11, incrementAndGet());\n // Fills Header\n System.arraycopy(S7_MRD_HEADER, 0, pdu, 0, S7_MRD_HEADER.length);\n S7.setWordAt(pdu, 13, (itemsCount * s7Item.length + 2));\n pdu[18] = (byte) itemsCount;\n offset = 19;\n for (int c = 0; c < itemsCount; c++) {\n System.arraycopy(S7_MRD_ITEM, 0, s7Item, 0, s7Item.length);\n s7Item[3] = items[c].type.getValue();\n S7.setWordAt(s7Item, 4, items[c].amount);\n if (items[c].area == AreaType.DB) {\n S7.setWordAt(s7Item, 6, items[c].db);\n }\n s7Item[8] = items[c].area.getValue();\n\n // address into the PLC\n int address = items[c].start;\n s7Item[11] = (byte) (address & 0xff);\n s7Item[10] = (byte) (address >> 8 & 0xff);\n s7Item[9] = (byte) (address >> 16 & 0xff);\n\n System.arraycopy(s7Item, 0, pdu, offset, s7Item.length);\n offset += s7Item.length;\n }\n\n if (offset > pduLength) {\n logger.error(\"PDU length < offset ({}/{})\", pduLength, offset);\n throw buildException(ERR_SIZE_OVER_PDU);\n }\n\n S7.setWordAt(pdu, 2, offset); // Whole size\n\n if (!sendPacket(pdu, offset)) {\n throw buildException(ERR_ISO_INVALID_PDU);\n }\n // get Answer\n length = recvIsoPacket();\n\n // Check ISO length\n if (length < 22) {\n throw buildException(ERR_ISO_INVALID_PDU);\n }\n // Check Global Operation Result\n int globalResult = S7.getWordAt(pdu, 17);\n if (globalResult != 0) {\n throw buildException(ReturnCode.getCpuError(globalResult));\n }\n\n // get true itemsCount\n int itemsRead = S7.getByteAt(pdu, 20);\n if ((itemsRead != itemsCount) || (itemsRead > MAX_VARS)) {\n throw buildException(ERR_INVALID_PLC_ANSWER);\n }\n // get Data\n offset = 21;\n for (int c = 0; c < itemsCount; c++) {\n // get the Item\n System.arraycopy(pdu, offset, s7ItemRead, 0, length - offset);\n if (s7ItemRead[0] == (byte) 0xff) {\n itemSize = S7.getWordAt(s7ItemRead, 2);\n if ((s7ItemRead[1] != TS_RESOCTET) && (s7ItemRead[1] != TS_RESREAL) && (s7ItemRead[1] != TS_RESBIT)) {\n itemSize = itemSize >> 3;\n }\n System.arraycopy(s7ItemRead, 4, items[c].data, 0, Math.min(items[c].data.length, itemSize));\n // Marshal.Copy(s7ItemRead, 4, items[c].pData, itemSize);\n items[c].result = 0;\n if (itemSize % 2 != 0) {\n itemSize++; // Odd size are rounded\n }\n offset = offset + 4 + itemSize;\n } else {\n items[c].result = ReturnCode.getCpuError(s7ItemRead[0]);\n offset += 4; // Skip the Item header\n }\n }\n\n return true;\n }\n\n @Override\n public boolean writeMultiVars(S7DataItem[] items, int itemsCount) throws S7Exception {\n int offset;\n int parLength;\n int dataLength;\n int itemDataSize;\n byte[] s7ParItem = new byte[S7_MWR_PARAM.length];\n byte[] dataItem = new byte[1024];\n\n // Checks items\n if (itemsCount > MAX_VARS) {\n throw buildException(ERR_TOO_MANY_ITEMS);\n }\n\n S7.setWordAt(S7_MRD_HEADER, 11, incrementAndGet());\n\n // Fills Header\n System.arraycopy(S7_MWR_HEADER, 0, pdu, 0, S7_MWR_HEADER.length);\n parLength = itemsCount * S7_MWR_PARAM.length + 2;\n S7.setWordAt(pdu, 13, parLength);\n pdu[18] = (byte) itemsCount;\n // Fills Params\n offset = S7_MWR_HEADER.length;\n for (int c = 0; c < itemsCount; c++) {\n System.arraycopy(S7_MWR_PARAM, 0, s7ParItem, 0, S7_MWR_PARAM.length);\n s7ParItem[3] = items[c].type.getValue();\n s7ParItem[8] = items[c].area.getValue();\n S7.setWordAt(s7ParItem, 4, items[c].amount);\n S7.setWordAt(s7ParItem, 6, items[c].db);\n // address into the PLC\n int address = items[c].start;\n s7ParItem[11] = (byte) (address & 0xff);\n s7ParItem[10] = (byte) (address >> 8 & 0xff);\n s7ParItem[9] = (byte) (address >> 16 & 0xff);\n\n System.arraycopy(s7ParItem, 0, pdu, offset, s7ParItem.length);\n offset += S7_MWR_PARAM.length;\n }\n // Fills Data\n dataLength = 0;\n for (int c = 0; c < itemsCount; c++) {\n dataItem[0] = 0x00;\n switch (items[c].type) {\n case BIT:\n dataItem[1] = TS_RESBIT;\n break;\n case COUNTER:\n case TIMER:\n dataItem[1] = TS_RESOCTET;\n break;\n default:\n dataItem[1] = TS_RESBYTE; // byte/word/dword etc.\n break;\n }\n if ((items[c].type == DataType.TIMER) || (items[c].type == DataType.COUNTER)) {\n itemDataSize = items[c].amount * 2;\n } else {\n itemDataSize = items[c].amount;\n }\n\n if ((dataItem[1] != TS_RESOCTET) && (dataItem[1] != TS_RESBIT)) {\n S7.setWordAt(dataItem, 2, (itemDataSize * 8));\n } else {\n S7.setWordAt(dataItem, 2, itemDataSize);\n }\n\n System.arraycopy(items[c].data, 0, dataItem, 4, itemDataSize);\n if (itemDataSize % 2 != 0) {\n dataItem[itemDataSize + 4] = (byte) 0x00;\n itemDataSize++;\n }\n System.arraycopy(dataItem, 0, pdu, offset, itemDataSize + 4);\n offset = offset + itemDataSize + 4;\n dataLength = dataLength + itemDataSize + 4;\n }\n\n // Checks the size\n if (offset > pduLength) {\n throw buildException(ERR_SIZE_OVER_PDU);\n }\n\n S7.setWordAt(pdu, 2, offset); // Whole size\n S7.setWordAt(pdu, 15, dataLength); // Whole size\n sendPacket(pdu, offset);\n\n recvIsoPacket();\n // Check Global Operation Result\n int globalResult = S7.getWordAt(pdu, 17);\n if (globalResult != 0) {\n throw buildException(ReturnCode.getCpuError(globalResult));\n }\n // get true itemsCount\n int itemsWritten = S7.getByteAt(pdu, 20);\n if ((itemsWritten != itemsCount) || (itemsWritten > MAX_VARS)) {\n throw buildException(ERR_INVALID_PLC_ANSWER);\n }\n\n for (int c = 0; c < itemsCount; c++) {\n if (pdu[c + 21] == (byte) 0xff) {\n items[c].result = 0;\n } else {\n items[c].result = ReturnCode.getCpuError(pdu[c + 21]);\n }\n }\n return true;\n }\n\n @Override\n public int readArea(final AreaType area, final int db, final int start, final int amount, final DataType type, final byte[] buffer) throws S7Exception {\n int _amount = amount;\n DataType _type;\n switch (area) {\n case CT_INPUTS:\n case CT_OUTPUTS:\n _type = DataType.COUNTER;\n break;\n case TM:\n _type = DataType.TIMER;\n break;\n default:\n _type = type;\n break;\n }\n int wordSize = DataType.getByteLength(_type);\n if (wordSize == 0) {\n throw buildException(ERR_INVALID_WORD_LEN);\n }\n switch (_type) {\n case BIT:\n _amount = 1;\n break;\n case COUNTER:\n case TIMER:\n break;\n default:\n _amount = _amount * wordSize;\n wordSize = 1;\n _type = DataType.BYTE;\n break;\n }\n return readInternalArea(area, db, start, _amount, _type, wordSize, buffer);\n }\n\n private int readInternalArea(final AreaType area, final int db, final int start, final int amount, final DataType type, final int wordSize, final byte[] buffer) throws S7Exception {\n int sizeRequested;\n int offset = 0;\n // 18 = Reply telegram header\n int maxElements = (pduLength - 18) / wordSize;\n int totElements = amount;\n int position = start;\n\n while (totElements > 0) {\n int numElements = totElements;\n if (numElements > maxElements) {\n numElements = maxElements;\n }\n\n sizeRequested = numElements * wordSize;\n\n S7.setWordAt(S7_RW, 11, incrementAndGet());\n // Setup the telegram\n System.arraycopy(S7_RW, 0, pdu, 0, SIZE_RD);\n\n // Set DB Number\n pdu[27] = area.getValue();\n // Set area\n if (area == AreaType.DB) {\n S7.setWordAt(pdu, 25, db);\n }\n\n int address;\n switch (type) {\n case BIT:\n case COUNTER:\n case TIMER:\n address = position;\n pdu[22] = type.getValue();\n break;\n default:\n address = position << 3;\n break;\n }\n\n // Num elements\n S7.setWordAt(pdu, 23, numElements);\n\n // address into the PLC (only 3 bytes)\n pdu[30] = (byte) (address & 0xff);\n pdu[29] = (byte) (address >> 8 & 0xff);\n pdu[28] = (byte) (address >> 16 & 0xff);\n\n if (sendPacket(pdu, SIZE_RD)) {\n int length = recvIsoPacket();\n if (length < 25) {\n throw buildException(ERR_ISO_INVALID_DATA_SIZE);\n }\n if (pdu[21] != (byte) 0xff) {\n throw buildException(ReturnCode.getCpuError(pdu[21]));\n }\n System.arraycopy(pdu, 25, buffer, offset, sizeRequested);\n offset += sizeRequested;\n }\n totElements -= numElements;\n position += numElements * wordSize;\n }\n return offset;\n }\n\n @Override\n public S7Szl getSzl(int id, int index, int bufferSize) throws S7Exception {\n final S7Szl szl = new S7Szl(bufferSize);\n int length;\n int dataSZL;\n int offset = 0;\n boolean done = false;\n boolean first = true;\n byte seq_in = 0x00;\n\n szl.dataSize = 0;\n do {\n if (first) {\n S7.setWordAt(S7_SZL_FIRST, 11, incrementAndGet());\n S7.setWordAt(S7_SZL_FIRST, 29, id);\n S7.setWordAt(S7_SZL_FIRST, 31, index);\n sendPacket(S7_SZL_FIRST);\n } else {\n S7.setWordAt(S7_SZL_NEXT, 11, incrementAndGet());\n pdu[24] = seq_in;\n sendPacket(S7_SZL_NEXT);\n }\n\n length = recvIsoPacket();\n if (length < 33) {\n throw buildException(ISO_INVALID_PDU);\n }\n if (S7.getWordAt(pdu, 27) != 0) {\n throw buildException(S7.getWordAt(pdu, 27));\n }\n if (pdu[29] != (byte) 0xff) {\n throw buildException(S7_FUNCTION_ERROR);\n }\n if (first) {\n // gets amount of this slice\n // Skips extra params (ID, Index ...)\n dataSZL = S7.getWordAt(pdu, 31) - 8;\n done = pdu[26] == (byte) 0x00;\n seq_in = pdu[24]; // Slice sequence\n\n szl.lenthdr = S7.getWordAt(pdu, 37);\n szl.n_dr = S7.getWordAt(pdu, 39);\n szl.copy(pdu, 41, offset, dataSZL);\n offset += dataSZL;\n szl.dataSize += dataSZL;\n } else {\n // gets amount of this slice\n dataSZL = S7.getWordAt(pdu, 31);\n done = pdu[26] == (byte) 0x00;\n seq_in = pdu[24]; // Slice sequence\n szl.copy(pdu, 37, offset, dataSZL);\n offset += dataSZL;\n szl.dataSize += dataSZL;\n }\n first = false;\n } while (!done);\n\n return szl;\n }\n\n private int recvIsoPacket() throws S7Exception {\n boolean done = false;\n int size = 0;\n while (!done) {\n // get TPKT (4 bytes)\n recvPacket(pdu, 0, 4);\n size = S7.getWordAt(pdu, 2);\n // Check 0 bytes Data Packet (only TPKT+COTP = 7 bytes)\n if (size == ISO_HEADER_SIZE) {\n recvPacket(pdu, 4, 3); // Skip remaining 3 bytes and Done is still false\n } else {\n if (size > MAX_PDU_SIZE || size < MIN_PDU_SIZE) {\n throw buildException(ISO_INVALID_PDU);\n }\n done = true; // a valid length !=7 && >16 && <247\n }\n }\n\n // Skip remaining 3 COTP bytes\n recvPacket(pdu, 4, 3);\n // Stores PDU Type, we need it\n lastPDUType = pdu[5];\n // Receives the S7 Payload\n recvPacket(pdu, 7, size - ISO_HEADER_SIZE);\n\n return size;\n }\n\n protected int recvPacket(byte[] buffer, int start, int size) throws S7Exception {\n int bytesRead = 0;\n try {\n int offset = start, timeout = 0;\n while (timeout < recvTimeout) {\n bytesRead += inStream.read(buffer, offset, size);\n if (bytesRead == size) {\n return bytesRead;\n }\n offset += bytesRead;\n Thread.sleep(1);\n timeout++;\n }\n if (bytesRead == 0) {\n throw buildException(TCP_CONNECTION_RESET);\n }\n logger.error(\"cleanup the buffer: {}\", inStream.available());\n inStream.read(pdu);\n\n } catch (InterruptedException e) {\n logger.debug(\"recv packet interrupted\");\n } catch (IOException e) {\n throw buildException(TCP_DATA_RECV, e);\n }\n return bytesRead;\n }\n\n private boolean sendPacket(byte[] buffer) throws S7Exception {\n return sendPacket(buffer, buffer.length);\n }\n\n protected boolean sendPacket(byte[] buffer, int len) throws S7Exception {\n try {\n outStream.write(buffer, 0, len);\n outStream.flush();\n return true;\n } catch (Exception e) {\n throw buildException(TCP_DATA_SEND, e);\n }\n }\n\n @Override\n public boolean setPlcDateTime(LocalDateTime dateTime) throws S7Exception {\n S7.setDateTimeAt(S7_SET_DT, 31, dateTime);\n if (sendPacket(S7_SET_DT)) {\n int length = recvIsoPacket();\n if (length < 31) {\n throw buildException(ISO_INVALID_PDU);\n }\n\n if (S7.getWordAt(pdu, 27) != 0) {\n throw buildException(S7.getWordAt(pdu, 27));\n }\n return true;\n }\n throw buildException(S7_FUNCTION_ERROR);\n }\n\n @Override\n public boolean setPlcDateTime() throws S7Exception {\n return setPlcDateTime(LocalDateTime.now());\n }\n\n @Override\n public boolean setSessionPassword(String password) throws S7Exception {\n // Adjusts the Password length to 8\n if (password.length() > 8) {\n password = password.substring(0, 8);\n } else {\n while (password.length() < 8) {\n password = password + \" \";\n }\n }\n byte[] pwd = password.getBytes(StandardCharsets.UTF_8);\n\n // Encodes the password\n pwd[0] = (byte) (pwd[0] ^ 0x55);\n pwd[1] = (byte) (pwd[1] ^ 0x55);\n for (int c = 2; c < 8; c++) {\n pwd[c] = (byte) (pwd[c] ^ 0x55 ^ pwd[c - 2]);\n }\n System.arraycopy(pwd, 0, S7_SET_PWD, 29, 8);\n if (sendPacket(S7_SET_PWD)) {\n int length = recvIsoPacket();\n if (length < 33) {\n throw buildException(ISO_INVALID_PDU);\n }\n\n if (S7.getWordAt(pdu, 27) != 0) {\n throw buildException(S7.getWordAt(pdu, 27));\n }\n return true;\n }\n throw buildException(S7_FUNCTION_ERROR);\n }\n\n @Override\n public boolean writeArea(final AreaType area, final int db, final int start, final int amount, final DataType type, final byte[] buffer)\n throws S7Exception {\n int _amount = amount;\n DataType _type;\n switch (area) {\n case CT_INPUTS:\n case CT_OUTPUTS:\n _type = DataType.COUNTER;\n break;\n case TM:\n _type = DataType.TIMER;\n break;\n default:\n _type = type;\n break;\n }\n int wordSize = DataType.getByteLength(_type);\n if (wordSize == 0) {\n throw buildException(ERR_INVALID_WORD_LEN);\n }\n switch (_type) {\n case BIT:\n _amount = 1;\n break;\n case COUNTER:\n case TIMER:\n break;\n default:\n _amount = _amount * wordSize;\n wordSize = 1;\n _type = DataType.BYTE;\n break;\n }\n return writeInternalArea(area, db, start, _amount, _type, wordSize, buffer);\n }\n\n private boolean writeInternalArea(final AreaType area, final int db, final int start, final int amount, final DataType type, final int wordSize,\n final byte[] buffer) throws S7Exception {\n int maxElements = (pduLength - 35) / wordSize; // 35 = Reply telegram header\n int totElements = amount;\n int offset = 0;\n int position = start;\n while (totElements > 0) {\n int numElements = totElements;\n if (numElements > maxElements) {\n numElements = maxElements;\n }\n\n int dataSize = numElements * wordSize;\n int isoSize = SIZE_WR + dataSize;\n\n S7.setWordAt(S7_RW, 11, incrementAndGet());\n // setup the telegram\n System.arraycopy(S7_RW, 0, pdu, 0, SIZE_WR);\n // Whole telegram Size\n S7.setWordAt(pdu, 2, isoSize);\n // Data length\n int length = dataSize + 4;\n S7.setWordAt(pdu, 15, length);\n // Function\n pdu[17] = (byte) 0x05;\n // set DB Number\n pdu[27] = area.getValue();\n if (area == AreaType.DB) {\n S7.setWordAt(pdu, 25, db);\n }\n\n // Adjusts start and word length\n int address;\n switch (type) {\n case BIT:\n case COUNTER:\n case TIMER:\n address = position;\n length = dataSize;\n pdu[22] = type.getValue();\n break;\n default:\n address = position << 3;\n length = dataSize << 3;\n break;\n }\n\n // Num elements\n S7.setWordAt(pdu, 23, numElements);\n // address into the PLC\n pdu[30] = (byte) (address & 0xff);\n pdu[29] = (byte) (address >> 8 & 0xff);\n pdu[28] = (byte) (address >> 16 & 0xff);\n\n // Transport Size\n switch (type) {\n case BIT:\n pdu[32] = TS_RESBIT;\n break;\n case COUNTER:\n case TIMER:\n pdu[32] = TS_RESOCTET;\n break;\n default:\n // byte/word/dword/real/char converted to byte[] etc.\n pdu[32] = TS_RESBYTE;\n break;\n }\n // length\n S7.setWordAt(pdu, 33, length);\n\n // Copies the Data\n System.arraycopy(buffer, offset, pdu, 35, dataSize);\n\n if (sendPacket(pdu, isoSize)) {\n length = recvIsoPacket();\n if (length != 22) {\n throw buildException(ERR_ISO_INVALID_PDU);\n }\n\n if (pdu[21] != (byte) 0xff) {\n throw buildException(ReturnCode.getCpuError(pdu[21]));\n }\n\n }\n offset += dataSize;\n totElements -= numElements;\n position += numElements * wordSize;\n }\n return true;\n }\n\n @Override\n public int getIsoExchangeBuffer(byte[] buffer) throws S7Exception {\n int size = 0;\n System.arraycopy(TPKT_ISO, 0, pdu, 0, TPKT_ISO.length);\n S7.setWordAt(pdu, 2, (size + TPKT_ISO.length));\n try {\n System.arraycopy(buffer, 0, pdu, TPKT_ISO.length, size);\n } catch (Exception e) {\n throw buildException(ERR_ISO_INVALID_PDU, e);\n }\n if (sendPacket(pdu, TPKT_ISO.length + size)) {\n int length = recvIsoPacket();\n if (length < 1) {\n throw buildException(ISO_INVALID_PDU);\n }\n\n System.arraycopy(pdu, TPKT_ISO.length, buffer, 0, length - TPKT_ISO.length);\n size = length - TPKT_ISO.length;\n }\n return size;\n }\n\n private S7Exception buildException(int code) {\n return buildException(code, null);\n }\n\n protected S7Exception buildException(int code, Throwable e) {\n return e == null ? new S7Exception(code, ReturnCode.getErrorText(code)) : new S7Exception(code, ReturnCode.getErrorText(code), e);\n }\n\n private static void closeSilently(Closeable c) {\n try {\n if (c != null) {\n c.close();\n }\n } catch (IOException e) {\n }\n }\n}",
"public enum AreaType {\n /** System Information (caller) */\n SYS_INFO(0x03),\n\n /** S7 counters */\n SYSTEM_FLAGS(0x05),\n\n /** Analog Inputs - System info (200 family) */\n ANALOG_INPUTS(0x06),\n\n /** Analog Outputs - System flags (200 family) */\n ANALOG_OUTPUTS(0x07),\n\n /** Analog Counter Input area (200 family) */\n CT_INPUTS(0x1C),\n\n /** S7 Timer area */\n TM(0x1D),\n\n /** Analog Counter Output area (200 family) */\n CT_OUTPUTS(0x1E),\n\n /** IEC counters (200 family) */\n TM_IEC(0x1F),\n\n /** PE (inputs) instance area */\n PE(0x81),\n\n /** PA (outputs) instance area */\n PA(0x82),\n\n /** Marker (flags) area */\n MK(0x83),\n\n /** DataBlock (Peripheral I/O) area */\n DB(0x84),\n\n /** DataBlock area */\n DI(0x85),\n\n /** DataBlock (local) area */\n DB_LOCAL(0x86),\n\n /** IEC timers (200 family) */\n TM_V(0x87);\n\n private final byte value;\n\n AreaType(int value) {\n this.value = (byte) value;\n }\n\n public byte getValue() {\n return value;\n }\n\n public final static List<AreaType> SUPPORTED = Arrays.asList(MK, DB, TM);\n\n}",
"public enum DataType {\n\n /** Bit, Boolean */\n BIT(0x01),\n\n /** Unsigned Byte */\n BYTE(0x02),\n\n /** Unsigned Byte,Char */\n CHAR(0x03),\n\n /** Unsigned Word, Short, BCD */\n WORD(0x04),\n\n /** Signed Word, Short, BCD */\n INT(0x05),\n\n /** Unsigned Double Word, Long, LBCD, Float */\n DWORD(0x06),\n\n /** Signed Double Word, Long, LBCD, Float */\n DINT(0x07),\n\n /** Float */\n REAL(0x08),\n\n /** Counter type */\n COUNTER(0x1C),\n\n /** Timer type */\n TIMER(0x1D);\n\n private final byte value;\n\n DataType(int value) {\n this.value = (byte) value;\n }\n\n public byte getValue() {\n return value;\n }\n\n /**\n * Type to byte length\n *\n * @param type DataType\n * @return encoded byte[] length\n */\n public static int getByteLength(DataType type) {\n switch (type) {\n case BIT:// S7 sends 1 byte per bit\n case BYTE:\n case CHAR:\n return 1;\n case WORD:\n case INT:\n case COUNTER:\n case TIMER:\n return 2;\n case DWORD:\n case DINT:\n case REAL:\n return 4;\n default:\n return 0;\n }\n }\n}",
"public class S7 {\n\n private static final byte[] BIT_MASK = { (byte) 0x01, (byte) 0x02, (byte) 0x04, (byte) 0x08, (byte) 0x10, (byte) 0x20, (byte) 0x40, (byte) 0x80 };\n\n private final static char EMP_CHAR = '\\u0020', DOT_CHAR = '.';\n private final static char HEX_DIGIT[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };\n\n public static int bcdToByte(byte b) {\n return ((b >> 4) * 10) + (b & 0x0F);\n }\n\n public static byte byteToBCD(int value) {\n return (byte) (((value / 10) << 4) | (value % 10));\n }\n\n\n public static boolean getBitAt(byte b, int bitpos) {\n int value = b & 0x0FF;\n return (value & BIT_MASK[bitpos]) != 0;\n }\n\n public static boolean getBitAt(byte[] buffer, int pos, int bitpos) {\n int value = buffer[pos] & 0x0FF;\n return (value & BIT_MASK[bitpos]) != 0;\n }\n\n public static byte[] getBytesAt(byte[] buffer, int pos, int maxLen) {\n return Arrays.copyOfRange(buffer, pos, pos + maxLen);\n }\n\n public static Date getDateAt(byte[] buffer, int pos) {\n int year, month, day, hour, min, sec;\n Calendar cal = Calendar.getInstance();\n\n year = bcdToByte(buffer[pos]);\n if (year < 90) {\n year += 2000;\n } else {\n year += 1900;\n }\n\n month = bcdToByte(buffer[pos + 1]) - 1;\n day = bcdToByte(buffer[pos + 2]);\n hour = bcdToByte(buffer[pos + 3]);\n min = bcdToByte(buffer[pos + 4]);\n sec = bcdToByte(buffer[pos + 5]);\n\n cal.set(year, month, day, hour, min, sec);\n cal.set(Calendar.MILLISECOND, 0);\n return cal.getTime();\n }\n\n public static LocalDateTime getDateTimeAt(byte[] buffer, int pos) {\n int year, month, day, hour, min, sec;\n year = bcdToByte(buffer[pos]);\n year += year < 90 ? 2000 : 1900;\n month = bcdToByte(buffer[pos + 1]);\n day = bcdToByte(buffer[pos + 2]);\n hour = bcdToByte(buffer[pos + 3]);\n min = bcdToByte(buffer[pos + 4]);\n sec = bcdToByte(buffer[pos + 5]);\n\n // First two digits of miliseconds\n // int msecH = bcdToByte(buffer[pos + 6]) * 10;\n // Last digit of miliseconds\n // int msecL = bcdToByte(buffer[pos + 7]) / 10;\n\n return LocalDateTime.of(year, month, day, hour, min, sec);\n }\n\n // Returns a 32 bit signed value : from 0 to 4294967295 (2^32-1)\n public static int getDIntAt(byte[] buffer, int pos) {\n return ((buffer[pos]) << 24 | (buffer[pos + 1] & 0xFF) << 16 | (buffer[pos + 2] & 0xFF) << 8 | (buffer[pos + 3] & 0xFF));\n }\n\n // Returns a 32 bit unsigned value : from 0 to 4294967295 (2^32-1)\n public static long getDWordAt(byte[] buffer, int pos) {\n return ((buffer[pos]) << 24 | (buffer[pos + 1] & 0xFF) << 16 | (buffer[pos + 2] & 0xFF) << 8 | (buffer[pos + 3] & 0xFF));\n }\n\n // Returns a 32 bit floating point\n public static float getFloatAt(byte[] buffer, int pos) {\n int IntFloat = getDIntAt(buffer, pos);\n return Float.intBitsToFloat(IntFloat);\n }\n\n public static String getPrintableStringAt(byte[] buffer, int pos, int maxLen) {\n StringBuilder sb = new StringBuilder();\n for (int i = pos; i < pos + maxLen; i++) {\n char ch = (char) (buffer[i] & 0xFF);\n if (Character.isISOControl(ch) || Character.isWhitespace(ch)) {\n sb.append(DOT_CHAR);\n continue;\n }\n sb.append(ch);\n }\n return sb.toString();\n }\n\n // Returns a 16 bit signed value : from -32768 to 32767\n public static int getShortAt(byte[] buffer, int pos) {\n int hi = (buffer[pos]);\n int lo = (buffer[pos + 1] & 0x00FF);\n return ((hi << 8) + lo);\n }\n\n public static String getStringAt(byte[] buffer, int pos, int maxLen) {\n return getStringAt(buffer, pos, maxLen, StandardCharsets.UTF_8);\n }\n\n public static String getStringAt(byte[] buffer, int pos, int maxLen, Charset charset) {\n return new String(buffer, pos, maxLen, charset);\n }\n\n public static String getS7StringAt(byte[] buffer, int pos) {\n int length = buffer[pos + 1];\n return new String(buffer, pos + 2, length, StandardCharsets.UTF_8);\n }\n\n public static byte getByteAt(byte[] buffer, int pos) {\n return buffer[pos];\n }\n\n public static int getUnsignedIntAt(byte[] buffer, int pos) {\n return Byte.toUnsignedInt(buffer[pos]);\n }\n\n /**\n * Returns a 16 bit unsigned value : from 0 to 65535 (2^16-1)\n *\n * @param buffer\n * @param pos start position\n * @return\n */\n public static int getWordAt(byte[] buffer, int pos) {\n int hi = (buffer[pos] & 0x00FF);\n int lo = (buffer[pos + 1] & 0x00FF);\n return (hi << 8) + lo;\n }\n\n public static S7Timer getS7TimerAt(byte[] buffer, int pos) {\n return S7Timer.of(buffer, pos);\n }\n\n public static void setBitAt(byte[] buffer, int pos, int bitPos, boolean value) {\n if (bitPos < 0) {\n bitPos = 0;\n } else if (bitPos > 7) {\n bitPos = 7;\n }\n if (value) {\n buffer[pos] = (byte) (buffer[pos] | BIT_MASK[bitPos]);\n } else {\n buffer[pos] = (byte) (buffer[pos] & ~BIT_MASK[bitPos]);\n }\n }\n\n public static void setDateAt(byte[] buffer, int pos, Date date) {\n int year, month, day, hour, min, sec;\n Calendar cal = Calendar.getInstance();\n cal.setTime(date);\n\n year = cal.get(Calendar.YEAR);\n month = cal.get(Calendar.MONTH) + 1;\n day = cal.get(Calendar.DAY_OF_MONTH);\n hour = cal.get(Calendar.HOUR_OF_DAY);\n min = cal.get(Calendar.MINUTE);\n sec = cal.get(Calendar.SECOND);\n // milli = cal.get(Calendar.MILLISECOND);\n // // First two digits of miliseconds\n // int msecH = milli / 10;\n // // Last digit of miliseconds\n // int msecL = milli % 10;\n\n if (year > 1999) {\n year -= 2000;\n }\n buffer[pos] = byteToBCD(year);\n buffer[pos + 1] = byteToBCD(month);\n buffer[pos + 2] = byteToBCD(day);\n buffer[pos + 3] = byteToBCD(hour);\n buffer[pos + 4] = byteToBCD(min);\n buffer[pos + 5] = byteToBCD(sec);\n buffer[pos + 6] = byteToBCD(0);\n buffer[pos + 7] = byteToBCD(0);\n\n }\n\n public static void setDateTimeAt(byte[] buffer, int pos, LocalDateTime dateTime) {\n int year, month, day, hour, min, sec;\n year = dateTime.get(ChronoField.YEAR);\n month = dateTime.get(ChronoField.MONTH_OF_YEAR);\n day = dateTime.get(ChronoField.DAY_OF_MONTH);\n hour = dateTime.get(ChronoField.HOUR_OF_DAY);\n min = dateTime.get(ChronoField.MINUTE_OF_HOUR);\n sec = dateTime.get(ChronoField.SECOND_OF_MINUTE);\n // milli = dateTime.get(ChronoField.MILLI_OF_SECOND);\n // // First two digits of miliseconds\n // int msecH = milli / 10;\n // // Last digit of miliseconds\n // int msecL = milli % 10;\n\n if (year > 1999) {\n year -= 2000;\n }\n buffer[pos] = byteToBCD(year);\n buffer[pos + 1] = byteToBCD(month);\n buffer[pos + 2] = byteToBCD(day);\n buffer[pos + 3] = byteToBCD(hour);\n buffer[pos + 4] = byteToBCD(min);\n buffer[pos + 5] = byteToBCD(sec);\n buffer[pos + 6] = byteToBCD(0);\n buffer[pos + 7] = byteToBCD(0);\n }\n\n public static void setDIntAt(byte[] buffer, int pos, int value) {\n buffer[pos + 3] = (byte) (value & 0xFF);\n buffer[pos + 2] = (byte) ((value >> 8) & 0xFF);\n buffer[pos + 1] = (byte) ((value >> 16) & 0xFF);\n buffer[pos] = (byte) ((value >> 24) & 0xFF);\n }\n\n public static void setDWordAt(byte[] buffer, int pos, long value) {\n buffer[pos + 3] = (byte) (value & 0xFF);\n buffer[pos + 2] = (byte) ((value >> 8) & 0xFF);\n buffer[pos + 1] = (byte) ((value >> 16) & 0xFF);\n buffer[pos] = (byte) ((value >> 24) & 0xFF);\n }\n\n public static void setFloatAt(byte[] buffer, int pos, float value) {\n int DInt = Float.floatToIntBits(value);\n setDIntAt(buffer, pos, DInt);\n }\n\n public static void setShortAt(byte[] buffer, int pos, short value) {\n buffer[pos] = (byte) (value >> 8);\n buffer[pos + 1] = (byte) (value & 0x00FF);\n }\n\n public static void setWordAt(byte[] buffer, int pos, int value) {\n setShortAt(buffer, pos, (short) value);\n }\n\n public static void setSwapWordAt(byte[] buffer, int pos, int value) {\n buffer[pos + 1] = (byte) (value >> 8);\n buffer[pos] = (byte) (value & 0x00FF);\n }\n\n public static void setByteAt(byte[] buffer, int pos, byte b) {\n buffer[pos] = b;\n }\n\n public static void setBytesAt(byte[] buffer, int pos, byte[] bytes) {\n System.arraycopy(bytes, 0, buffer, pos, bytes.length);\n }\n\n public static void setStringAt(byte[] buffer, int pos, String value) {\n setStringAt(buffer, pos, value, StandardCharsets.UTF_8);\n }\n\n public static void setStringAt(byte[] buffer, int pos, String value, Charset charset) {\n setBytesAt(buffer, pos, value.getBytes(charset));\n }\n\n public static void setS7StringAt(byte[] buffer, int pos, int maxLen, String value) {\n byte[] data = value.getBytes(StandardCharsets.UTF_8);\n buffer[pos] = (byte) (maxLen & 0xFF);\n buffer[pos + 1] = (byte) (data.length & 0xFF);\n System.arraycopy(data, 0, buffer, pos + 2, Math.min(data.length, maxLen));\n }\n\n public static void hexDump(byte[] buffer, Consumer<String> c) {\n hexDump(buffer, 128, c);\n }\n\n public static void hexDump(byte[] buffer, int maxlines, Consumer<String> c) {\n hexDump(buffer, maxlines, 0, c);\n }\n\n public static void hexDump(byte[] buffer, int maxlines, int offset, Consumer<String> c) {\n if (buffer == null || buffer.length == 0 || maxlines < 1 || offset < 0) {\n return;\n }\n int length, pos;\n int line = 0;\n StringBuilder sb = new StringBuilder();\n while (line < maxlines && (pos = (line * 16) + offset) < buffer.length) {\n length = Math.min(16, buffer.length - pos);\n if (length < 1) {\n return;\n }\n sb.setLength(0);\n for (int i = 12; i >= 0; i -= 4) {\n sb.append(HEX_DIGIT[0x0F & line >>> i]);\n }\n sb.append('0').append(':').append(EMP_CHAR).append(EMP_CHAR);\n line++;\n for (int i = 0; i < 16; i++) {\n if (i < length) {\n sb.append(HEX_DIGIT[0x0F & buffer[pos + i] >> 4]);\n sb.append(HEX_DIGIT[0x0F & buffer[pos + i]]);\n } else {\n sb.append(EMP_CHAR).append(EMP_CHAR);\n }\n sb.append(EMP_CHAR);\n if (i == 7) {\n sb.append(EMP_CHAR);\n }\n }\n sb.append(EMP_CHAR);\n for (int i = 0; i < 16; i++) {\n if (i >= length) {\n sb.append(EMP_CHAR);\n continue;\n }\n char ch = (char) (buffer[pos + i] & 0xFF);\n if (Character.isISOControl(ch) || Character.isWhitespace(ch)) {\n sb.append(DOT_CHAR);\n continue;\n }\n sb.append(ch);\n }\n c.accept(sb.toString());\n }\n }\n\n public static DataItem buildDataItem(String address) {\n try {\n DataItem item;\n int i0 = address.indexOf('.');\n switch (address.charAt(0)) {\n case 'D':\n if (i0 < 1){\n throw new IllegalArgumentException(String.format(\"invalid DB address: %s\", address));\n }\n\n int i1 = address.indexOf('.', i0 + 1);\n int db = Integer.parseUnsignedInt(address.substring(2, i0));\n DataType type;\n switch (address.charAt(i0 + 3)) {\n case 'X':\n type = DataType.BIT;\n break;\n case 'B':\n type = DataType.BYTE;\n break;\n case 'W':\n type = DataType.WORD;\n break;\n case 'D':\n type = DataType.DWORD;\n break;\n default:\n throw new IllegalArgumentException(String.format(\"invalid DB address: %s\", address));\n }\n int start = Integer.parseUnsignedInt(address.substring(i0 + 4, i1 > 0 ? i1 : address.length()));\n item = new DataItem(AreaType.DB, type, db, start, i1 < 1 ? 0 : Integer.parseUnsignedInt(address.substring(i1 + 1, address.length())));\n break;\n case 'M':\n int startM = Integer.parseUnsignedInt(address.substring(1, i0 > 1 ? i0 : address.length()));\n item = new DataItem(AreaType.MK, i0 > 1 ? DataType.BIT : DataType.BYTE, 0, startM, i0 < 1 ? 0 : Integer.parseUnsignedInt(address.substring(i0 + 1, address.length())));\n break;\n default:\n throw new IllegalArgumentException(String.format(\"invalid Memory address: %s\", address));\n }\n return item;\n } catch (IllegalArgumentException e) {\n throw e;\n } catch (Exception e) {\n throw new IllegalArgumentException(String.format(\"address: %s not parsable\", address), e);\n }\n\n }\n\n\n}"
] | import java.util.Arrays;
import org.comtel2000.mokka7.ClientRunner;
import org.comtel2000.mokka7.S7Client;
import org.comtel2000.mokka7.type.AreaType;
import org.comtel2000.mokka7.type.DataType;
import org.comtel2000.mokka7.util.S7; | /*
* PROJECT Mokka7 (fork of Snap7/Moka7)
*
* Copyright (c) 2017 J.Zimmermann (comtel2000)
*
* All rights reserved. This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Mokka7 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE whatever license you
* decide to adopt.
*
* Contributors: J.Zimmermann - Mokka7 fork
*
*/
package org.comtel2000.mokka7.clone;
/**
* Clone bit of DB200.DBX34.0 to DB200.DBX34.1
*
* @author comtel
*
*/
public class HearbeatSample2 extends ClientRunner {
public HearbeatSample2() {
super();
}
@Override | public void call(S7Client client) throws Exception { | 1 |
nichbar/Aequorea | app/src/main/java/nich/work/aequorea/presenter/SearchPresenter.java | [
"public class FilterUtils {\n public static boolean underSupport(String type) {\n return !((Constants.ARTICLE_TYPE_THEME.equals(type)) || (Constants.ARTICLE_TYPE_MAGAZINE.equals(type)) || (Constants.ARTICLE_TYPE_MAGAZINE_V2.equals(type)) || (Constants.ARTICLE_TYPE_SUBJECT.equals(type)));\n }\n \n public static List<Datum> filterData(List<Datum> data) {\n Iterator<Datum> iterator = data.iterator();\n \n while (iterator.hasNext()) {\n Datum d = iterator.next();\n if (!FilterUtils.underSupport(d.getArticleType()) || !FilterUtils.underSupport(d.getType())) {\n iterator.remove();\n }\n }\n return data;\n }\n \n public static List<SearchDatum> filterSearchData(List<SearchDatum> data) {\n Iterator<SearchDatum> iterator = data.iterator();\n \n while (iterator.hasNext()) {\n Content content = iterator.next().getContent();\n if (!FilterUtils.underSupport(content.getArticleType())) {\n iterator.remove();\n }\n }\n return data;\n }\n}",
"public class NetworkUtils {\n\n public static boolean isNetworkAvailable() {\n Context context = Aequorea.getApp();\n ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);\n \n NetworkInfo info = null;\n if (connectivityManager != null) {\n info = connectivityManager.getActiveNetworkInfo();\n }\n return info != null && info.isAvailable();\n }\n \n public static boolean isWiFiNetwork() {\n Context context = Aequorea.getApp();\n ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);\n \n NetworkInfo info = null;\n if (connectivityManager != null) {\n info = connectivityManager.getActiveNetworkInfo();\n }\n \n return info != null && info.getType() == ConnectivityManager.TYPE_WIFI && info.isAvailable();\n }\n}",
"public class Data {\n\n @SerializedName(\"data\")\n private List<Datum> mData;\n @SerializedName(\"meta\")\n private Meta mMeta;\n\n public List<Datum> getData() {\n return mData;\n }\n\n public void setData(List<Datum> data) {\n mData = data;\n }\n \n public Meta getMeta() {\n return mMeta;\n }\n \n public void setMeta(Meta meta) {\n mMeta = meta;\n }\n}",
"public class Datum {\n\n @SerializedName(\"anonymous_purchase_total_count\")\n private Long mAnonymousPurchaseTotalCount;\n @SerializedName(\"anonymous_purchases\")\n private List<AnonymousPurchase> mAnonymousPurchases;\n @SerializedName(\"anonymous_share_price\")\n private String mAnonymousSharePrice;\n @SerializedName(\"article_type\")\n private String mArticleType;\n @SerializedName(\"authors\")\n private List<Author> mAuthors;\n @SerializedName(\"column\")\n private Column mColumn;\n @SerializedName(\"comment_times\")\n private Long mCommentTimes;\n @SerializedName(\"data\")\n private List<Datum> mData;\n @SerializedName(\"display_time\")\n private String mDisplayTime;\n @SerializedName(\"editor_choice_comments\")\n private List<Object> mEditorChoiceComments;\n @SerializedName(\"is_favorited\")\n private Boolean mIsFavorited;\n @SerializedName(\"is_like\")\n private Boolean mIsLike;\n @SerializedName(\"like_times\")\n private Long mLikeTimes;\n @SerializedName(\"magazine\")\n private Magazine mMagazine;\n @SerializedName(\"read_time\")\n private Long mReadTime;\n @SerializedName(\"share_url\")\n private String mShareUrl;\n @SerializedName(\"share_visit_limit\")\n private Long mShareVisitLimit;\n @SerializedName(\"share_visit_times\")\n private Long mShareVisitTimes;\n @SerializedName(\"summary\")\n private String mSummary;\n @SerializedName(\"title\")\n private String mTitle;\n @SerializedName(\"topics\")\n private List<Topic> mTopics;\n @SerializedName(\"type\")\n private String mType;\n @SerializedName(\"visit_times\")\n private Long mVisitTimes;\n @SerializedName(\"articles_count\")\n private Long mArticlesCount;\n private String mCoverUrl;\n @SerializedName(\"description\")\n private Object mDescription;\n @SerializedName(\"id\")\n private Long mId;\n @SerializedName(\"illustration\")\n private String mIllustration;\n @SerializedName(\"name\")\n private String mName;\n @SerializedName(\"content\")\n private String mContent;\n @SerializedName(\"total_read_times\")\n private Long mTotalReadTimes;\n @SerializedName(\"total_visit_times\")\n private Long mTotalVisitTimes;\n\n public Long getArticlesCount() {\n return mArticlesCount;\n }\n\n public void setArticlesCount(Long articlesCount) {\n mArticlesCount = articlesCount;\n }\n\n\n public Object getDescription() {\n return mDescription;\n }\n\n public void setDescription(Object description) {\n mDescription = description;\n }\n\n public String getIllustration() {\n return mIllustration;\n }\n\n public void setIllustration(String illustration) {\n mIllustration = illustration;\n }\n\n public String getName() {\n return mName;\n }\n\n public void setName(String name) {\n mName = name;\n }\n\n public Long getTotalReadTimes() {\n return mTotalReadTimes;\n }\n\n public void setTotalReadTimes(Long totalReadTimes) {\n mTotalReadTimes = totalReadTimes;\n }\n\n public Long getTotalVisitTimes() {\n return mTotalVisitTimes;\n }\n\n public void setTotalVisitTimes(Long totalVisitTimes) {\n mTotalVisitTimes = totalVisitTimes;\n }\n\n\n public Long getAnonymousPurchaseTotalCount() {\n return mAnonymousPurchaseTotalCount;\n }\n\n public void setAnonymousPurchaseTotalCount(Long anonymousPurchaseTotalCount) {\n mAnonymousPurchaseTotalCount = anonymousPurchaseTotalCount;\n }\n\n public List<AnonymousPurchase> getAnonymousPurchases() {\n return mAnonymousPurchases;\n }\n\n public void setAnonymousPurchases(List<AnonymousPurchase> anonymousPurchases) {\n mAnonymousPurchases = anonymousPurchases;\n }\n\n public String getAnonymousSharePrice() {\n return mAnonymousSharePrice;\n }\n\n public void setAnonymousSharePrice(String anonymousSharePrice) {\n mAnonymousSharePrice = anonymousSharePrice;\n }\n\n public String getArticleType() {\n return mArticleType;\n }\n\n public void setArticleType(String articleType) {\n mArticleType = articleType;\n }\n\n public List<Author> getAuthors() {\n return mAuthors;\n }\n\n public void setAuthors(List<Author> authors) {\n mAuthors = authors;\n }\n\n public Column getColumn() {\n return mColumn;\n }\n\n public void setColumn(Column column) {\n mColumn = column;\n }\n\n public Long getCommentTimes() {\n return mCommentTimes;\n }\n\n public void setCommentTimes(Long commentTimes) {\n mCommentTimes = commentTimes;\n }\n\n public String getCoverUrl() {\n return mCoverUrl;\n }\n\n public void setCoverUrl(String coverUrl) {\n mCoverUrl = coverUrl;\n }\n\n public List<Datum> getData() {\n return mData;\n }\n\n public void setData(List<Datum> data) {\n mData = data;\n }\n\n public String getDisplayTime() {\n return mDisplayTime;\n }\n\n public void setDisplayTime(String displayTime) {\n mDisplayTime = displayTime;\n }\n\n public List<Object> getEditorChoiceComments() {\n return mEditorChoiceComments;\n }\n\n public void setEditorChoiceComments(List<Object> editorChoiceComments) {\n mEditorChoiceComments = editorChoiceComments;\n }\n\n public Long getId() {\n return mId;\n }\n\n public void setId(Long id) {\n mId = id;\n }\n\n public Boolean getIsFavorited() {\n return mIsFavorited;\n }\n\n public void setIsFavorited(Boolean isFavorited) {\n mIsFavorited = isFavorited;\n }\n\n public Boolean getIsLike() {\n return mIsLike;\n }\n\n public void setIsLike(Boolean isLike) {\n mIsLike = isLike;\n }\n\n public Long getLikeTimes() {\n return mLikeTimes;\n }\n\n public void setLikeTimes(Long likeTimes) {\n mLikeTimes = likeTimes;\n }\n\n public Magazine getMagazine() {\n return mMagazine;\n }\n\n public void setMagazine(Magazine magazine) {\n mMagazine = magazine;\n }\n\n public Long getReadTime() {\n return mReadTime;\n }\n\n public void setReadTime(Long readTime) {\n mReadTime = readTime;\n }\n\n public String getShareUrl() {\n return mShareUrl;\n }\n\n public void setShareUrl(String shareUrl) {\n mShareUrl = shareUrl;\n }\n\n public Long getShareVisitLimit() {\n return mShareVisitLimit;\n }\n\n public void setShareVisitLimit(Long shareVisitLimit) {\n mShareVisitLimit = shareVisitLimit;\n }\n\n public Long getShareVisitTimes() {\n return mShareVisitTimes;\n }\n\n public void setShareVisitTimes(Long shareVisitTimes) {\n mShareVisitTimes = shareVisitTimes;\n }\n\n public String getSummary() {\n return mSummary;\n }\n\n public void setSummary(String summary) {\n mSummary = summary;\n }\n\n public String getTitle() {\n return mTitle;\n }\n\n public void setTitle(String title) {\n mTitle = title;\n }\n\n public List<Topic> getTopics() {\n return mTopics;\n }\n\n public void setTopics(List<Topic> topics) {\n mTopics = topics;\n }\n\n public String getType() {\n return mType;\n }\n\n public void setType(String type) {\n mType = type;\n }\n\n public Long getVisitTimes() {\n return mVisitTimes;\n }\n\n public void setVisitTimes(Long visitTimes) {\n mVisitTimes = visitTimes;\n }\n \n public String getContent() {\n return mContent;\n }\n \n public void setContent(String content) {\n mContent = content;\n }\n}",
"public class Content {\n\n @SerializedName(\"article_type\")\n private String mArticleType;\n @SerializedName(\"authors\")\n private List<Author> mAuthors;\n @SerializedName(\"cover_url\")\n private String mCoverUrl;\n @SerializedName(\"id\")\n private Long mId;\n @SerializedName(\"publish_at\")\n private String mPublishAt;\n @SerializedName(\"summary\")\n private String mSummary;\n @SerializedName(\"title\")\n private String mTitle;\n\n public String getArticleType() {\n return mArticleType;\n }\n\n public void setArticleType(String articleType) {\n mArticleType = articleType;\n }\n\n public List<Author> getAuthors() {\n return mAuthors;\n }\n\n public void setAuthors(List<Author> authors) {\n mAuthors = authors;\n }\n\n public String getCoverUrl() {\n return mCoverUrl;\n }\n\n public void setCoverUrl(String coverUrl) {\n mCoverUrl = coverUrl;\n }\n\n public Long getId() {\n return mId;\n }\n\n public void setId(Long id) {\n mId = id;\n }\n\n public String getPublishAt() {\n return mPublishAt;\n }\n\n public void setPublishAt(String publishAt) {\n mPublishAt = publishAt;\n }\n\n public String getSummary() {\n return mSummary;\n }\n\n public void setSummary(String summary) {\n mSummary = summary;\n }\n\n public String getTitle() {\n return mTitle;\n }\n\n public void setTitle(String title) {\n mTitle = title;\n }\n\n}",
"public class SearchData {\n\n @SerializedName(\"data\")\n private List<SearchDatum> mData;\n @SerializedName(\"meta\")\n private Meta mMeta;\n\n public List<SearchDatum> getData() {\n return mData;\n }\n\n public void setData(List<SearchDatum> data) {\n mData = data;\n }\n\n public Meta getMeta() {\n return mMeta;\n }\n\n public void setMeta(Meta meta) {\n mMeta = meta;\n }\n\n}",
"public class SearchDatum {\n\n @SerializedName(\"content\")\n private Content mContent;\n @SerializedName(\"searchable_id\")\n private Long mSearchableId;\n @SerializedName(\"searchable_type\")\n private String mSearchableType;\n\n public Content getContent() {\n return mContent;\n }\n\n public void setContent(Content content) {\n mContent = content;\n }\n\n public Long getSearchableId() {\n return mSearchableId;\n }\n\n public void setSearchableId(Long searchableId) {\n mSearchableId = searchableId;\n }\n\n public String getSearchableType() {\n return mSearchableType;\n }\n\n public void setSearchableType(String searchableType) {\n mSearchableType = searchableType;\n }\n\n}"
] | import java.util.ArrayList;
import java.util.List;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import nich.work.aequorea.R;
import nich.work.aequorea.common.utils.FilterUtils;
import nich.work.aequorea.common.utils.NetworkUtils;
import nich.work.aequorea.model.entity.Data;
import nich.work.aequorea.model.entity.Datum;
import nich.work.aequorea.model.entity.search.Content;
import nich.work.aequorea.model.entity.search.SearchData;
import nich.work.aequorea.model.entity.search.SearchDatum; | package nich.work.aequorea.presenter;
public class SearchPresenter extends SimpleArticleListPresenter {
@Override
public void load() {
if (!NetworkUtils.isNetworkAvailable()) {
onError(new Throwable(getString(R.string.please_connect_to_the_internet)));
return;
}
if (mPage > mTotalPage || mBaseView.getModel().isLoading()) {
return;
}
mBaseView.getModel().setLoading(true);
mComposite.add(mService.getArticleListWithKeyword(mPage, 20, mBaseView.getModel()
.getKey(), false, "article")
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<SearchData>() {
@Override
public void accept(SearchData data) throws Exception {
onSearchDataLoaded(data);
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {
onError(throwable);
}
}));
}
private void onSearchDataLoaded(SearchData searchData) {
Data data = transferSearchDataIntoNormalData(searchData);
super.onDataLoaded(data);
}
// fuck this api designer
private Data transferSearchDataIntoNormalData(SearchData searchData) {
Data data = new Data();
List<SearchDatum> searchDataList = searchData.getData();
int size = searchDataList.size();
if (size != 0) {
List<Datum> dataList = new ArrayList<>();
for (int i = 0; i < size; i++) {
Content content = searchDataList.get(i).getContent(); | if (FilterUtils.underSupport(content.getArticleType())) { | 0 |
grennis/MongoExplorer | app/src/main/java/com/innodroid/mongobrowser/ui/DocumentDetailFragment.java | [
"public class Events {\n public static void postAddConnection() {\n EventBus.getDefault().post(new AddConnection());\n }\n\n public static void postConnectionSelected(long connectionID) {\n EventBus.getDefault().post(new ConnectionSelected(connectionID));\n }\n\n public static void postConnected(long connectionID) {\n EventBus.getDefault().post(new Connected(connectionID));\n }\n\n public static void postConnectionDeleted() {\n EventBus.getDefault().post(new ConnectionDeleted());\n }\n\n public static void postCollectionSelected(long connectionId, int index) {\n EventBus.getDefault().post(new CollectionSelected(connectionId, index));\n }\n\n public static void postAddDocument() {\n EventBus.getDefault().post(new AddDocument());\n }\n\n public static void postDocumentSelected(int index) {\n EventBus.getDefault().post(new DocumentSelected(index));\n }\n\n public static void postDocumentClicked(int index) {\n EventBus.getDefault().post(new DocumentClicked(index));\n }\n\n public static void postCreateCollection(String name) {\n EventBus.getDefault().post(new CreateCollection(name));\n }\n\n public static void postRenameCollection(String name) {\n EventBus.getDefault().post(new RenameCollection(name));\n }\n\n public static void postCollectionRenamed(String name) {\n EventBus.getDefault().post(new CollectionRenamed(name));\n }\n\n public static void postCollectionDropped() {\n EventBus.getDefault().post(new CollectionDropped());\n }\n\n public static void postConnectionAdded(long connectionId) {\n EventBus.getDefault().post(new ConnectionAdded(connectionId));\n }\n\n public static void postConnectionUpdated(long connectionId) {\n EventBus.getDefault().post(new ConnectionUpdated(connectionId));\n }\n\n public static void postEditDocument(int index) {\n EventBus.getDefault().post(new EditDocument(index));\n }\n\n public static void postDocumentEdited(int index) {\n EventBus.getDefault().post(new DocumentEdited(index));\n }\n\n public static void postDocumentCreated(String content) {\n EventBus.getDefault().post(new DocumentCreated(content));\n }\n\n public static void postDocumentDeleted() {\n EventBus.getDefault().post(new DocumentDeleted());\n }\n\n public static void postChangeDatabase(String name) {\n EventBus.getDefault().post(new ChangeDatabase(name));\n }\n\n public static void postQueryNamed(String name) {\n EventBus.getDefault().post(new QueryNamed(name));\n }\n\n public static void postQueryUpdated(String query) {\n EventBus.getDefault().post(new QueryUpdated(query));\n }\n\n public static void postSettingsChanged() {\n EventBus.getDefault().post(new SettingsChanged());\n }\n\n public static class AddConnection {\n }\n\n public static class AddDocument {\n }\n\n public static class DocumentDeleted {\n }\n\n public static class ConnectionSelected {\n public long ConnectionId;\n\n public ConnectionSelected(long connectionId) {\n ConnectionId = connectionId;\n }\n }\n\n public static class ConnectionDeleted {\n }\n\n public static class Connected {\n public long ConnectionId;\n\n public Connected(long connectionId) {\n ConnectionId = connectionId;\n }\n }\n\n public static class CollectionSelected {\n public long ConnectionId;\n public int Index;\n\n public CollectionSelected(long connectionId, int index) {\n ConnectionId = connectionId;\n Index = index;\n }\n }\n\n public static class DocumentSelected {\n public int Index;\n\n public DocumentSelected(int index) {\n Index = index;\n }\n }\n\n public static class DocumentClicked {\n public int Index;\n\n public DocumentClicked(int index) {\n Index = index;\n }\n }\n\n public static class EditDocument {\n public int Index;\n\n public EditDocument(int index) {\n Index = index;\n }\n }\n\n public static class DocumentCreated {\n public String Content;\n\n public DocumentCreated(String content) {\n Content = content;\n }\n }\n\n public static class ChangeDatabase {\n public String Name;\n\n public ChangeDatabase(String name) {\n Name = name;\n }\n }\n\n public static class QueryNamed {\n public String Name;\n\n public QueryNamed(String name) {\n Name = name;\n }\n }\n\n public static class QueryUpdated {\n public String Content;\n\n public QueryUpdated(String content) {\n Content = content;\n }\n }\n\n public static class DocumentEdited {\n public int Index;\n\n public DocumentEdited(int index) {\n Index = index;\n }\n }\n\n public static class CollectionRenamed {\n public String Name;\n\n public CollectionRenamed(String name) {\n Name = name;\n }\n }\n\n public static class RenameCollection {\n public String Name;\n\n public RenameCollection(String name) {\n Name = name;\n }\n }\n\n public static class CreateCollection {\n public String Name;\n\n public CreateCollection(String name) {\n Name = name;\n }\n }\n\n public static class CollectionDropped {\n }\n\n public static class ConnectionAdded {\n public long ConnectionId;\n\n public ConnectionAdded(long connectionId) {\n ConnectionId = connectionId;\n }\n }\n\n public static class ConnectionUpdated {\n public long ConnectionId;\n\n public ConnectionUpdated(long connectionId) {\n ConnectionId = connectionId;\n }\n }\n\n public static class SettingsChanged {\n }\n}",
"public class MongoData {\n public static List<MongoCollectionRef> Collections = new ArrayList<>();\n public static List<MongoDocument> Documents = new ArrayList<>();\n}",
"public class MongoHelper {\n\tprivate static MongoClient Connection;\n\tprivate static MongoDatabase Database;\n\tprivate static String DatabaseName;\n\tprivate static String Server;\n\tprivate static int Port;\n\tprivate static String User;\n\tprivate static String Password;\n\t\n\tpublic static void connect(String server, int port, String dbname, String user, String pass) throws UnknownHostException {\n\t\tdisconnect();\n\n\t\tServerAddress sa = new ServerAddress(server, port);\n\n\t\tif (user != null && user.length() > 0) {\n\t\t\tList<MongoCredential> creds = new ArrayList<>();\n\t\t\tcreds.add(MongoCredential.createScramSha1Credential(user, dbname, pass.toCharArray()));\n\t\t\tConnection = new MongoClient(sa, creds);\n\t\t} else {\n\t\t\tConnection = new MongoClient(sa);\n\t\t}\n\n \tDatabase = Connection.getDatabase(dbname);\n \tServer = server;\n \tPort = port;\n \tDatabaseName = dbname;\n \t\n \tUser = user;\n \tPassword = pass;\n \t\n \tConnection.setWriteConcern(WriteConcern.SAFE);\n\t\tDatabase.listCollectionNames().first();\n\t}\n\t\n private static void disconnect() {\n \ttry {\n\t \tif (Connection != null) {\n\t \t\tConnection.close();\n\t \t\tConnection = null;\n\t \t\tDatabase = null;\n\t \t}\n \t} catch (Exception ex) {\n \t\tex.printStackTrace();\n \t}\n\t}\n \n private static void reconnect() throws UnknownHostException {\n \tdisconnect();\n \tconnect(Server, Port, DatabaseName, User, Password);\n }\n\n public static void changeDatabase(String name) throws UnknownHostException {\n \tLog.i(\"MONGO\", \"Change to database \" + name);\n\t\tdisconnect();\n\t\tconnect(Server, Port, name, User, Password);\n }\n \n\tpublic static List<MongoCollectionRef> getCollectionNames(boolean includeSystemPrefs) {\n\t\tMongoIterable<String> names = Database.listCollectionNames();\n \tArrayList<MongoCollectionRef> list = new ArrayList<>();\n \t\n \tfor (String str : names)\n \t\tif (includeSystemPrefs || !str.startsWith(\"system.\"))\n \t\t\tlist.add(new MongoCollectionRef(str));\n\n\t\treturn list;\n }\n\n\tpublic static ArrayList<String> getDatabaseNames() {\n \tArrayList<String> list = new ArrayList<String>();\n\n \tfor (String str : Connection.getDatabaseNames())\n\t\t\tlist.add(str);\n\n \treturn list;\n }\n\t\n\tpublic static long getCollectionCount(String name) {\n\t\treturn Database.getCollection(name).count();\n\t}\n\t\n\tpublic static void createCollection(String name) throws Exception {\n\t\tDatabase.createCollection(name);\n\t}\n\t\n\tpublic static void renameCollection(String oldName, String newName) throws UnknownHostException {\n\t\treconnect();\n\t\tMongoNamespace ns = new MongoNamespace(Database.getName() + \".\" + newName);\n\t\tDatabase.getCollection(oldName).renameCollection(ns);\n\t}\n\n\tpublic static List<MongoDocument> getPageOfDocuments(String collection, String queryText, int start, int take) {\n\t\tMongoCollection coll = Database.getCollection(collection);\n\t\tFindIterable main = (queryText == null) ? coll.find() : coll.find(Document.parse(queryText));\n\t\tFindIterable items = main.skip(start).limit(take);\n\t\tfinal ArrayList<MongoDocument> results = new ArrayList<>();\n\n\t\titems.forEach(new Block<Document>() {\n\t\t\t@Override\n\t\t\tpublic void apply(final Document document) {\n\t\t\t\tresults.add(new MongoDocument(document.toJson()));\n\t\t\t}\n\t\t});\n\n\t\treturn results;\n\t}\n\n\tpublic static void dropCollection(String name) {\n\t\tDatabase.getCollection(name).drop();\n\t}\n\n\tpublic static String saveDocument(String collectionName, String content) {\n\t\tDocument doc = Document.parse(content);\n\n\t\tif (doc.containsKey(\"_id\")) {\n\t\t\tDocument filter = new Document(\"_id\", doc.get(\"_id\"));\n\t\t\tDatabase.getCollection(collectionName).findOneAndReplace(filter, doc);\n\t\t} else {\n\t\t\tDatabase.getCollection(collectionName).insertOne(doc);\n\t\t}\n\n\t\treturn doc.toJson();\n\t}\n\n\tpublic static void deleteDocument(String collectionName, String content) {\n\t\tDocument doc = Document.parse(content);\n\n\t\tif (doc.containsKey(\"_id\")) {\n\t\t\tDocument filter = new Document(\"_id\", doc.get(\"_id\"));\n\t\t\tDatabase.getCollection(collectionName).findOneAndDelete(filter);\n\t\t}\n\t}\n}",
"public class Constants {\n\tpublic static final String LOG_TAG = \"mongoexp\";\n\n\tpublic static final String ARG_CONNECTION_ID = \"connid\";\n\tpublic static final String ARG_COLLECTION_INDEX = \"collname\";\n\tpublic static final String ARG_ACTIVATE_ON_CLICK = \"actonclick\";\n\tpublic static final String ARG_DOCUMENT_TITLE = \"doctitle\";\n\tpublic static final String ARG_DOCUMENT_INDEX = \"doccontent\";\n\tpublic static final String ARG_CONTENT = \"thecontent\";\n\n\tpublic static final long SLIDE_ANIM_DURATION = 600;\n\t\n\tpublic static final String NEW_DOCUMENT_CONTENT = \"{\\n \\n}\\n\";\n\tpublic static final String NEW_DOCUMENT_CONTENT_PADDED = \"{\\n \\n}\\n\\n\\n\\n\\n\";\n}",
"public class JsonUtils {\n\tprivate static final String TAB = \" \";\n\tprivate static final String TAG = \"JsonUtils\";\n\n\tpublic static String prettyPrint(String json) {\n\t\ttry {\n\t\t\tGson gson = new GsonBuilder().setPrettyPrinting().create();\n\t\t\tJsonParser jp = new JsonParser();\n\t\t\tJsonElement je = jp.parse(json);\n\t\t\treturn gson.toJson(je);\n\t\t} catch (Exception ex) {\n\t\t\tex.printStackTrace();\n\t\t\treturn json;\n\t\t}\n\t}\n\n\tpublic static Spanned prettyPrint2(String json) {\n\t\ttry {\n\t\t\tJsonParser jp = new JsonParser();\n\t\t\tJsonElement je = jp.parse(json);\n\t\t\tStringBuilder sb = new StringBuilder();\n\n\t\t\tLog.i(TAG, \"prettyPrint2\");\n\t\t\tprintElement(\"\", je, sb);\n\n\t\t\treturn Html.fromHtml(sb.toString());\n\t\t} catch (Exception ex) {\n\t\t\tex.printStackTrace();\n\t\t\treturn Html.fromHtml(json);\n\t\t}\n\t}\n\n\tprivate static void printElement(String tab, JsonElement el,\n\t\t\tStringBuilder sb) {\n\t\tif (el.isJsonObject()) {\n\t\t\tJsonObject object = el.getAsJsonObject();\n\t\t\tif (isObjectId(object)) {\n\t\t\t\tsb.append(\"ObjectId(\"\n\t\t\t\t\t\t+ formatObjectString(object.get(\"$oid\").getAsString()) + \")\");\n\t\t\t} else if (isDate(object)) {\n\t\t\t\tsb.append(\"ISODate(\"\n\t\t\t\t\t\t+ formatObjectString(object.get(\"$date\").getAsString()) + \")\");\n\t\t\t} else {\n\t\t\t\tsb.append(\"{<br/>\");\n\t\t\t\tString tab2 = tab + TAB;\n\t\t\t\tfor (Entry<String, JsonElement> entry : object.entrySet()) {\n\t\t\t\t\tLog.i(TAG, entry.getKey());\n\t\t\t\t\tsb.append(tab2 + formatKey(entry.getKey()) + \": \");\n\t\t\t\t\tprintElement(tab2, entry.getValue(), sb);\n\t\t\t\t\tsb.append(\",<br/>\");\n\t\t\t\t}\n\t\t\t\tsb.append(tab + \"}\");\n\t\t\t}\n\t\t} else if (el.isJsonArray()) {\n\t\t\tJsonArray array = el.getAsJsonArray();\n\t\t\tif (array.size() == 0) {\n\t\t\t\tsb.append(\"[ ]\");\n\t\t\t} else {\n\t\t\t\tsb.append(\"[<br/>\");\n\t\t\t\tString tab2 = tab + TAB;\n\t\t\t\tfor (int i = 0; i < array.size(); i++) {\n\t\t\t\t\tsb.append(tab2);\n\t\t\t\t\tprintElement(tab2, array.get(i), sb);\n\t\t\t\t\tif (i + 1 < array.size())\n\t\t\t\t\t\tsb.append(\",<br/>\");\n\n\t\t\t\t}\n\t\t\t\tsb.append(\"<br/>\" + tab + \"]\");\n\t\t\t}\n\t\t} else if (el.isJsonNull()) {\n\t\t\tsb.append(\"null\");\n\t\t} else {\n\t\t\tboolean handled = false;\n\t\t\tString string = el.getAsString();\n\n\t\t\tif (\"true\".equals(string) || \"false\".equals(string)) {\n\t\t\t\thandled = true;\n\t\t\t\tsb.append(formatBoolean(el.getAsString()));\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tLong.parseLong(string);\n\t\t\t\tsb.append(formatNumber(el.getAsString()));\n\t\t\t\thandled = true;\n\t\t\t} catch (NumberFormatException nfe) {\n\t\t\t\t// ignore errors\n\t\t\t}\n\n\t\t\t// fallback to string\n\t\t\tif (!handled) {\n\t\t\t\tsb.append(formatString(el.getAsString()));\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate static String formatKey(String value) {\n\t\treturn \"<font color=\\\"#444444\\\">\" + value + \"</font>\";\n\t}\n\n\tprivate static String formatNumber(String value) {\n\t\treturn \"<font color=\\\"#660000\\\">\" + value + \"</font>\";\n\t}\n\n\tprivate static String formatBoolean(String value) {\n\t\treturn \"<font color=\\\"#660000\\\">\" + value + \"</font>\";\n\t}\n\n\tprivate static String formatString(String value) {\n\t\tif (isUrl(value)) {\n\t\t\tvalue = Html.escapeHtml(value);\n\t\t\tvalue = \"<a href=\\\"\" + value + \"\\\">\" + value + \"</a>\";\n\t\t} else {\n\t\t\tvalue = Html.escapeHtml(value);\n\t\t}\n\t\treturn \"<font color=\\\"#006600\\\">\\\"\" + value + \"\\\"</font>\";\n\t}\n\n\tprivate static String formatObjectString(String value) {\n\t\treturn \"<font color=\\\"#004488\\\">\\\"\" + Html.escapeHtml(value)\n\t\t\t\t+ \"\\\"</font>\";\n\t}\n\n\tprivate static boolean isObjectId(JsonObject object) {\n\t\tif (object.entrySet().size() == 1) {\n\t\t\tif (object.has(\"$oid\"))\n\t\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tprivate static boolean isDate(JsonObject object) {\n\t\tif (object.entrySet().size() == 1) {\n\t\t\tif (object.has(\"$date\"))\n\t\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tprivate static boolean isUrl(String value) {\n\t\tMatcher matcher = Patterns.WEB_URL.matcher(value);\n\t\treturn matcher.matches();\n\t}\n}",
"public abstract class SafeAsyncTask<T, U, V> extends AsyncTask<T, U, V>{\n\tprivate Exception mException;\n\tprivate FragmentActivity mFragmentActivity;\n\tprivate ProgressDialog mDialog;\n\t\n\tprotected abstract V safeDoInBackground(T... params) throws Exception;\n\tprotected abstract void safeOnPostExecute(V result);\n\tprotected abstract String getErrorTitle();\n\t\n\tpublic SafeAsyncTask(FragmentActivity activity) {\t\t\n\t\tmFragmentActivity = activity;\n\t}\n\t\n\t@Override\n\tprotected void onPreExecute() {\n\t\tsuper.onPreExecute();\n\t\t\n\t\tString caption = getProgressMessage();\n\t\t\n\t\tif (caption != null)\n\t\t\tmDialog = ProgressDialog.show(mFragmentActivity, null, caption, true, false);\t\t\n\t}\n\t\n\t@Override\n\tprotected V doInBackground(T... params) {\n\t\tmException = null;\n\n\t\ttry {\n\t\t\treturn safeDoInBackground(params);\n\t\t} catch (Exception ex) {\n\t\t\tex.printStackTrace();\n\t\t\tmException = ex;\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t@Override\n\tprotected void onPostExecute(V result) {\n\t\tsuper.onPostExecute(result);\n\n\t\tif (mDialog != null)\n\t\t\tmDialog.dismiss();\n\n\t\tif (mException == null)\n\t\t\tsafeOnPostExecute(result);\n\t\telse\n\t\t\tExceptionDetailDialogFragment.newInstance(getErrorTitle(), mException).show(mFragmentActivity.getSupportFragmentManager(), null);\n\t}\n\n\tprotected String getProgressMessage() {\n\t\treturn null;\n\t}\n}",
"public class UiUtils {\n\tpublic interface AlertDialogCallbacks {\n\t\tboolean onOK();\n\t\tboolean onNeutralButton();\n\t}\n\t\n\tpublic interface ConfirmCallbacks {\n\t\tboolean onConfirm();\n\t}\n\n\tpublic static AlertDialogCallbacks EmptyAlertCallbacks = new AlertDialogCallbacks() {\n\t\t@Override\n\t\tpublic boolean onOK() {\n\t\t\treturn true;\n\t\t}\t\t\n\n\t\t@Override\n\t\tpublic boolean onNeutralButton() {\n\t\t\treturn true;\n\t\t}\t\t\n\t};\n\t\n\tpublic static Dialog buildAlertDialog(View view, int icon, int title, boolean hasCancel, int middleButtonText, final AlertDialogCallbacks callbacks) {\n\t\treturn buildAlertDialog(view, icon, view.getResources().getString(title), hasCancel, middleButtonText, callbacks);\n\t}\n\t\n\tpublic static Dialog buildAlertDialog(View view, int icon, String title, boolean hasCancel, int middleButtonText, final AlertDialogCallbacks callbacks) {\n AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext())\n\t .setIcon(icon)\n\t .setView(view)\n\t .setTitle(title)\n\t .setPositiveButton(android.R.string.ok,\n\t new DialogInterface.OnClickListener() {\n\t public void onClick(DialogInterface dialog, int whichButton) {\n\t }\n\t }\n\t );\n \n if (hasCancel) {\n\t builder.setCancelable(true).setNegativeButton(android.R.string.cancel,\n\t\t new DialogInterface.OnClickListener() {\n\t\t public void onClick(DialogInterface dialog, int whichButton) {\n\t\t }\n\t\t }\n\t\t ); \t\n }\n\n if (middleButtonText != 0) {\n\t builder.setNeutralButton(middleButtonText,\n\t\t new DialogInterface.OnClickListener() {\n\t\t public void onClick(DialogInterface dialog, int whichButton) {\n\t\t }\n\t\t }\n\t\t ); \t\n }\n\n final AlertDialog dialog = builder.create();\n\n dialog.setOnShowListener(new DialogInterface.OnShowListener() {\n @Override\n public void onShow(DialogInterface di) {\n Button b = dialog.getButton(AlertDialog.BUTTON_POSITIVE);\n b.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n \tif (callbacks.onOK())\n \t\tdialog.dismiss();\n }\n });\n\n b = dialog.getButton(AlertDialog.BUTTON_NEUTRAL);\n b.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n \tif (callbacks.onNeutralButton())\n \t\tdialog.dismiss();\n }\n });\n }\n }); \n \n return dialog;\n\t}\n\t\n\tpublic static Dialog buildAlertDialog(Context context, ListAdapter adapter, OnClickListener listener, int icon, String title) {\n AlertDialog.Builder builder = new AlertDialog.Builder(context)\n\t .setIcon(icon)\n\t .setAdapter(adapter, listener)\n\t .setTitle(title);\n \n builder.setCancelable(true);\n\n final AlertDialog dialog = builder.create();\n\n return dialog;\n\t}\n\n\tpublic static void message(Context context, int title, int message) {\n DialogInterface.OnClickListener onClick = new DialogInterface.OnClickListener() {\n\t\t\tpublic void onClick(DialogInterface dialog, int whichButton) {\n\t\t\t}\n\t\t};\n\n\t\tmessage(context, title, message, onClick);\n\t}\n\n\tpublic static void message(Context context, int title, int message, DialogInterface.OnClickListener onClick) {\n\t\tnew AlertDialog.Builder(context)\n\t\t\t\t.setIcon(R.drawable.ic_info_black)\n\t\t\t\t.setMessage(message)\n\t\t\t\t.setTitle(title)\n\t\t\t\t.setCancelable(true)\n\t\t\t\t.setPositiveButton(android.R.string.ok, onClick)\n\t\t\t\t.create().show();\n\t}\n\n\tpublic static void confirm(Context context, int message, final ConfirmCallbacks callbacks) {\n new AlertDialog.Builder(context)\n\t .setIcon(R.drawable.ic_warning_black)\n\t .setMessage(message)\n\t .setTitle(R.string.title_confirm)\n\t .setCancelable(true)\n\t .setPositiveButton(android.R.string.ok,\n\t\t\t\t\tnew DialogInterface.OnClickListener() {\n\t\t\t\t\t\tpublic void onClick(DialogInterface dialog, int whichButton) {\n\t\t\t\t\t\t\tcallbacks.onConfirm();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t)\n\t .setNegativeButton(android.R.string.cancel,\n\t\t\t\t\tnew DialogInterface.OnClickListener() {\n\t\t\t\t\t\tpublic void onClick(DialogInterface dialog, int whichButton) {\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t)\n\t .create().show();\n\t}\n\n\tpublic static String getAppVersionString(Context context) {\n\t\ttry {\n\t\t\tPackageInfo info = context.getApplicationContext().getPackageManager().getPackageInfo(context.getPackageName(), 0);\n\t\t\treturn \"v\" + info.versionName + \" (Build \" + info.versionCode + \")\";\n\t\t} catch (PackageManager.NameNotFoundException e) {\n\t\t\te.printStackTrace();\n\t\t\treturn \"\";\n\t\t}\n\t}\n}",
"public interface ConfirmCallbacks {\n\tboolean onConfirm();\n}"
] | import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.innodroid.mongobrowser.Events;
import com.innodroid.mongobrowser.data.MongoData;
import com.innodroid.mongobrowser.util.MongoHelper;
import com.innodroid.mongobrowser.Constants;
import com.innodroid.mongobrowser.R;
import com.innodroid.mongobrowser.util.JsonUtils;
import com.innodroid.mongobrowser.util.SafeAsyncTask;
import com.innodroid.mongobrowser.util.UiUtils;
import com.innodroid.mongobrowser.util.UiUtils.ConfirmCallbacks;
import butterknife.Bind; | package com.innodroid.mongobrowser.ui;
public class DocumentDetailFragment extends BaseFragment {
@Bind(R.id.document_detail_content) TextView mContentText;
private String mRawText;
public DocumentDetailFragment() {
}
@NonNull
public static DocumentDetailFragment newInstance(int collectionIndex, int documentIndex) {
Bundle arguments = new Bundle();
DocumentDetailFragment fragment = new DocumentDetailFragment();
arguments.putInt(Constants.ARG_COLLECTION_INDEX, collectionIndex);
arguments.putInt(Constants.ARG_DOCUMENT_INDEX, documentIndex);
fragment.setArguments(arguments);
return fragment;
}
@Override
public int getTitleText() {
return R.string.document;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = super.onCreateView(R.layout.fragment_document_detail, inflater, container, savedInstanceState);
updateContent();
return view;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.document_detail_menu, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_document_detail_edit:
if (mRawText != null) | Events.postEditDocument(getArguments().getInt(Constants.ARG_DOCUMENT_INDEX)); | 0 |
NuVotifier/NuVotifier | common/src/test/java/com/vexsoftware/votifier/net/protocol/VotifierProtocol2DecoderTest.java | [
"public interface VotifierPlugin extends VoteHandler {\n AttributeKey<VotifierPlugin> KEY = AttributeKey.valueOf(\"votifier_plugin\");\n\n Map<String, Key> getTokens();\n\n KeyPair getProtocolV1Key();\n\n LoggingAdapter getPluginLogger();\n\n VotifierScheduler getScheduler();\n\n default boolean isDebug() {\n return false;\n }\n}",
"public class Vote {\n\n /**\n * The name of the vote service.\n */\n private String serviceName;\n\n /**\n * The username of the voter.\n */\n private String username;\n\n /**\n * The address of the voter.\n */\n private String address;\n\n /**\n * The date and time of the vote.\n */\n private String timeStamp;\n\n private byte[] additionalData;\n\n @Deprecated\n public Vote() {\n }\n\n public Vote(String serviceName, String username, String address, String timeStamp) {\n this.serviceName = serviceName;\n this.username = username;\n this.address = address;\n this.timeStamp = timeStamp;\n this.additionalData = null;\n }\n\n public Vote(String serviceName, String username, String address, String timeStamp, byte[] additionalData) {\n this.serviceName = serviceName;\n this.username = username;\n this.address = address;\n this.timeStamp = timeStamp;\n this.additionalData = additionalData == null ? null : additionalData.clone();\n }\n\n public Vote(Vote vote) {\n this(vote.getServiceName(), vote.getUsername(), vote.getAddress(), vote.getTimeStamp(),\n vote.getAdditionalData() == null ? null : vote.getAdditionalData().clone());\n }\n\n private static String getTimestamp(JsonElement object) {\n try {\n return Long.toString(object.getAsLong());\n } catch (Exception e) {\n return object.getAsString();\n }\n }\n\n public Vote(JsonObject jsonObject) {\n this(jsonObject.get(\"serviceName\").getAsString(),\n jsonObject.get(\"username\").getAsString(),\n jsonObject.get(\"address\").getAsString(),\n getTimestamp(jsonObject.get(\"timestamp\")));\n if (jsonObject.has(\"additionalData\"))\n additionalData = Base64.getDecoder().decode(jsonObject.get(\"additionalData\").getAsString());\n }\n\n @Override\n public String toString() {\n String data;\n if (additionalData == null)\n data = \"null\";\n else\n data = Base64.getEncoder().encodeToString(additionalData);\n\n return \"Vote (from:\" + serviceName + \" username:\" + username\n + \" address:\" + address + \" timeStamp:\" + timeStamp\n + \" additionalData:\" + data + \")\";\n }\n\n /**\n * Sets the serviceName.\n *\n * @param serviceName The new serviceName\n */\n @Deprecated\n public void setServiceName(String serviceName) {\n this.serviceName = serviceName;\n }\n\n /**\n * Gets the serviceName.\n *\n * @return The serviceName\n */\n public String getServiceName() {\n return serviceName;\n }\n\n /**\n * Sets the username.\n *\n * @param username The new username\n */\n @Deprecated\n public void setUsername(String username) {\n this.username = username;\n }\n\n /**\n * Gets the username.\n *\n * @return The username\n */\n public String getUsername() {\n return username;\n }\n\n /**\n * Sets the address.\n *\n * @param address The new address\n */\n @Deprecated\n public void setAddress(String address) {\n this.address = address;\n }\n\n /**\n * Gets the address.\n *\n * @return The address\n */\n public String getAddress() {\n return address;\n }\n\n /**\n * Sets the time stamp.\n *\n * @param timeStamp The new time stamp\n */\n @Deprecated\n public void setTimeStamp(String timeStamp) {\n this.timeStamp = timeStamp;\n }\n\n /**\n * Gets the time stamp.\n *\n * @return The time stamp\n */\n public String getTimeStamp() {\n return timeStamp;\n }\n\n /**\n * Returns additional data sent with the vote, if it exists.\n *\n * @return Additional data sent with the vote\n */\n public byte[] getAdditionalData() {\n return additionalData == null ? null : additionalData.clone();\n }\n\n public JsonObject serialize() {\n JsonObject ret = new JsonObject();\n ret.addProperty(\"serviceName\", serviceName);\n ret.addProperty(\"username\", username);\n ret.addProperty(\"address\", address);\n ret.addProperty(\"timestamp\", timeStamp);\n if (additionalData != null)\n ret.addProperty(\"additionalData\", Base64.getEncoder().encodeToString(additionalData));\n return ret;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (!(o instanceof Vote)) return false;\n\n Vote vote = (Vote) o;\n\n if (!serviceName.equals(vote.serviceName)) return false;\n if (!username.equals(vote.username)) return false;\n if (!address.equals(vote.address)) return false;\n if (!timeStamp.equals(vote.timeStamp)) return false;\n return Arrays.equals(additionalData, vote.additionalData);\n }\n\n @Override\n public int hashCode() {\n int result = serviceName.hashCode();\n result = 31 * result + username.hashCode();\n result = 31 * result + address.hashCode();\n result = 31 * result + timeStamp.hashCode();\n return result;\n }\n}",
"public class VotifierSession {\n public static final AttributeKey<VotifierSession> KEY = AttributeKey.valueOf(\"votifier_session\");\n private ProtocolVersion version = ProtocolVersion.UNKNOWN;\n private final String challenge;\n private boolean hasCompletedVote = false;\n\n public VotifierSession() {\n challenge = TokenUtil.newToken();\n }\n\n public void setVersion(ProtocolVersion version) {\n if (this.version != ProtocolVersion.UNKNOWN)\n throw new IllegalStateException(\"Protocol version already switched\");\n\n this.version = version;\n }\n\n public ProtocolVersion getVersion() {\n return version;\n }\n\n public String getChallenge() {\n return challenge;\n }\n\n public void completeVote() {\n if (hasCompletedVote)\n throw new IllegalStateException(\"Protocol completed vote twice!\");\n\n hasCompletedVote = true;\n }\n\n public boolean hasCompletedVote() {\n return hasCompletedVote;\n }\n\n public enum ProtocolVersion {\n UNKNOWN(\"unknown\"),\n ONE(\"protocol v1\"),\n TWO(\"protocol v2\"),\n TEST(\"test\");\n\n public final String humanReadable;\n ProtocolVersion(String hr) {\n this.humanReadable = hr;\n }\n }\n}",
"public class GsonInst {\n\n public static final Gson gson = new GsonBuilder().create();\n\n}",
"public class KeyCreator {\n public static Key createKeyFrom(String token) {\n return new SecretKeySpec(token.getBytes(StandardCharsets.UTF_8), \"HmacSHA256\");\n }\n}"
] | import com.google.gson.JsonObject;
import com.vexsoftware.votifier.platform.VotifierPlugin;
import com.vexsoftware.votifier.model.Vote;
import com.vexsoftware.votifier.net.VotifierSession;
import com.vexsoftware.votifier.util.GsonInst;
import com.vexsoftware.votifier.util.KeyCreator;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.CorruptedFrameException;
import io.netty.handler.codec.DecoderException;
import org.json.JSONObject;
import org.junit.jupiter.api.Test;
import javax.crypto.Mac;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.Base64;
import static org.junit.jupiter.api.Assertions.*; | package com.vexsoftware.votifier.net.protocol;
public class VotifierProtocol2DecoderTest {
private static final VotifierSession SESSION = new VotifierSession();
private EmbeddedChannel createChannel() {
EmbeddedChannel channel = new EmbeddedChannel(new VotifierProtocol2Decoder());
channel.attr(VotifierSession.KEY).set(SESSION); | channel.attr(VotifierPlugin.KEY).set(TestVotifierPlugin.getI()); | 0 |
sastix/cms | common/services/src/test/com/sastix/cms/common/services/ApiVersionControllerTest.java | [
"public interface Constants {\n\n /**\n * Rest API Version.\n */\n static String REST_API_1_0 = \"1.0\";\n String GET_API_VERSION = \"/apiversion\";\n String DEFAULT_LANGUAGE = \"en\";\n\n /**\n * CONTENT API ENDPOINTS\n */\n static String CREATE_RESOURCE = \"createResource\";\n static String UPDATE_RESOURCE = \"updateResource\";\n static String QUERY_RESOURCE = \"queryResource\";\n static String DELETE_RESOURCE = \"deleteResource\";\n static String GET_DATA = \"getData\";\n static String GET_MULTIPART_DATA = \"getMultiPartData\";\n static String GET_DATA_FROM_UUID = \"getDataUuid\";\n static String GET_PARENT_UUID = \"getParentUuid\";\n static String LOCK_RESOURCE_DTO = \"lockResourceDTO\";\n static String UNLOCK_RESOURCE_DTO = \"unlockResourceDTO\";\n static String RENEW_RESOURCE_DTO_LOCK = \"renewResourceDtoLock\";\n\n /**\n * CACHE API ENDPOINTS\n */\n static final String GET_CACHE = \"getCache\";\n static final String PUT_CACHE = \"putCache\";\n static final String REMOVE_CACHE = \"removeCache\";\n static final String CLEAR_CACHE_REGION = \"clearCache\";\n static final String CLEAR_CACHE_ALL = \"clearCacheAll\";\n static final String CLEAR_CACHE_ALL_EXCEPT = \"clearCacheAllExcept\";\n static final String GET_UID = \"getUID\";\n static final String UID_REGION = \"uidRegion\";\n static final String DEFAULT_CACHE_NAME = \"dynamicCache\";\n\n /**\n * LOCK API ENDPOINTS\n */\n static String LOCK_RESOURCE = \"lockResource\";\n static String UNLOCK_RESOURCE = \"unlockResource\";\n static String RENEW_RESOURCE_LOCK = \"renewResourceLock\";\n static String QUERY_RESOURCE_LOCK = \"queryResourceLock\";\n\n /**\n * Error messages.\n */\n\n static String LOCK_NOT_ALLOWED = \"The supplied resource UID cannot be locked, it is already locked by another user\";\n static String LOCK_NOT_HELD = \"The supplied resource UID cannot be unlocked, it is not locked by this owner or has already expired\";\n\n static String RESOURCE_ACCESS_ERROR = \"The supplied resource UID cannot be modified – the user already has the lock and cannot lock more than once.\";\n static String RESOURCE_NOT_OWNED = \"The supplied resource UID cannot be modified, the lock is held by someone else already\";\n static String RESOURCE_NOT_FOUND = \"The supplied resource UID does not exist. This is possible if the UID was recently deleted.\";\n static String VALIDATION_ERROR = \"The supplied resource data are invalid.\";\n\n\n static Long MAX_FILE_SIZE_TO_CACHE = (long) (10 * 1024 * 1024);\n}",
"@Getter @Setter @NoArgsConstructor\npublic class VersionDTO {\n\n /**\n * Minimum version of API supported, initial should be \"1.0\".\n */\n private double minVersion;\n\n /**\n * Maximum version of API.\n */\n private double maxVersion;\n\n private Map<String, String> versionContexts;\n \n public VersionDTO withMinVersion(double min) {\n \tminVersion = min;\n \treturn this;\n }\n \n public VersionDTO withMaxVersion(double max) {\n \tmaxVersion = max;\n \treturn this;\n }\n\n public VersionDTO withVersionContext(double version, String contextPrefix) {\n \tif (null == versionContexts) {\n \t\tversionContexts = new HashMap<String,String>();\n \t}\n \tversionContexts.put(Double.toString(version), contextPrefix);\n \treturn this;\n }\n \n\t@Override\n\tpublic String toString() {\n\t\tStringBuilder builder = new StringBuilder();\n\t\tbuilder.append(\"VersionDTO [minVersion=\").append(minVersion)\n\t\t\t\t.append(\", maxVersion=\").append(maxVersion)\n\t\t\t\t.append(\", versionContexts=\").append(versionContexts)\n\t\t\t\t.append(\"]\");\n\t\treturn builder.toString();\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tlong temp;\n\t\ttemp = Double.doubleToLongBits(maxVersion);\n\t\tresult = prime * result + (int) (temp ^ (temp >>> 32));\n\t\ttemp = Double.doubleToLongBits(minVersion);\n\t\tresult = prime * result + (int) (temp ^ (temp >>> 32));\n\t\tresult = prime * result\n\t\t\t\t+ ((versionContexts == null) ? 0 : versionContexts.hashCode());\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (!(obj instanceof VersionDTO))\n\t\t\treturn false;\n\t\tVersionDTO other = (VersionDTO) obj;\n\t\tif (Double.doubleToLongBits(maxVersion) != Double\n\t\t\t\t.doubleToLongBits(other.maxVersion))\n\t\t\treturn false;\n\t\tif (Double.doubleToLongBits(minVersion) != Double\n\t\t\t\t.doubleToLongBits(other.minVersion))\n\t\t\treturn false;\n\t\tif (versionContexts == null) {\n\t\t\tif (other.versionContexts != null)\n\t\t\t\treturn false;\n\t\t} else if (!versionContexts.equals(other.versionContexts))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\t\n}",
"public interface ApiVersionService {\n\n VersionDTO getApiVersion();\n}",
"@Service\npublic class ApiVersionServiceImpl implements ApiVersionService {\n /**\n * this is the API version we support\n */\n private VersionDTO version;\n\n @Autowired\n public ApiVersionServiceImpl(@Value(\"#{new com.sastix.cms.common.dataobjects.VersionDTO()}\") VersionDTO version) {\n this.version = version;\n }\n\n @Override\n public VersionDTO getApiVersion() {\n return version;\n }\n\n}",
"@Slf4j\n@RestController\npublic class ApiVersionController {\n\n @Autowired\n ApiVersionService apiVersionService;\n\n @RequestMapping(value = Constants.GET_API_VERSION, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE )\n public VersionDTO getApiVersion() {\n VersionDTO versionDTO = apiVersionService.getApiVersion();\n log.trace(\"REST: Called {}, will return {}\", Constants.GET_API_VERSION, versionDTO);\n return versionDTO;\n }\n}",
"@Configuration\n@WebAppConfiguration\n@EnableWebMvc\n@ComponentScan(\"com.sastix.cms.common.services.web\")\nstatic class TestConfig {\n\t\t\n\t@Bean\n\tpublic ApiVersionService apiVersionService() {\n\t\t/*\n\t\t * you need to configure the api version service with the \n\t\t * constructor argument of the api ranges you support\n\t\t */\n\t\treturn new ApiVersionServiceImpl(TEST_VERSION);\n\t}\n\t\t\n\t\t\n}"
] | import com.sastix.cms.common.Constants;
import com.sastix.cms.common.dataobjects.VersionDTO;
import com.sastix.cms.common.services.api.ApiVersionService;
import com.sastix.cms.common.services.api.ApiVersionServiceImpl;
import com.sastix.cms.common.services.web.ApiVersionController;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import lombok.extern.slf4j.Slf4j;
import com.sastix.cms.common.services.ApiVersionControllerTest.TestConfig;
import static org.junit.Assert.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; | /*
* Copyright(c) 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sastix.cms.common.services;
@Slf4j
@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {TestConfig.class})
public class ApiVersionControllerTest {
static VersionDTO TEST_VERSION = new VersionDTO()
.withMinVersion(1.0)
.withMaxVersion(1.0)
.withVersionContext(1.0,"/testapi/v1.0");
static String TEST_VERSION_JSON = "{\"minVersion\":1.0,\"maxVersion\":1.0,\"versionContexts\":{\"1.0\":\"/testapi/v1.0\"}}";
@Autowired | ApiVersionService service; | 2 |
nodebox/nodebox | src/main/java/nodebox/client/Application.java | [
"public class Log {\n private static final Logger LOGGER = java.util.logging.Logger.getGlobal();\n\n static {\n try {\n // Initialize logging directory\n AppDirs.ensureUserLogDir();\n File logDir = AppDirs.getUserLogDir();\n\n // Initialize file logging\n FileHandler handler = new FileHandler(logDir.getAbsolutePath() + \"/nodebox-%u.log\");\n handler.setFormatter(new SimpleFormatter());\n LOGGER.addHandler(handler);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n public static void info(String message) {\n LOGGER.log(Level.INFO, message);\n }\n\n public static void warn(String message) {\n LOGGER.log(Level.WARNING, message);\n }\n\n public static void warn(String message, Throwable t) {\n LOGGER.log(Level.WARNING, message, t);\n }\n\n public static void error(String message) {\n LOGGER.log(Level.SEVERE, message);\n }\n\n public static void error(String message, Throwable t) {\n LOGGER.log(Level.SEVERE, message, t);\n }\n\n}",
"public class LastResortHandler implements Thread.UncaughtExceptionHandler {\n\n public static void handle(Throwable t) {\n System.out.println(\"handle!\");\n showException(Thread.currentThread(), t);\n }\n\n public void uncaughtException(final Thread t, final Throwable e) {\n if (SwingUtilities.isEventDispatchThread()) {\n showException(t, e);\n } else {\n SwingUtilities.invokeLater(new Runnable() {\n public void run() {\n showException(t, e);\n }\n });\n }\n }\n\n private static void showException(Thread t, Throwable e) {\n String msg = String.format(Locale.US, \"Unexpected problem on thread %s: %s\",\n t.getName(), e.getMessage());\n\n logException(t, e);\n\n // note: in a real app, you should locate the currently focused frame\n // or dialog and use it as the parent. In this example, I'm just passing\n // a null owner, which means this dialog may get buried behind\n // some other screen.\n ExceptionDialog ed = new ExceptionDialog(null, e);\n ed.setVisible(true);\n }\n\n private static void logException(Thread t, Throwable e) {\n // todo: start a thread that sends an email, or write to a log file, or\n // send a JMS message...whatever\n }\n}",
"public class Platform {\n public static final int WIN = 1;\n public static final int MAC = 2;\n public static final int OTHER = 3;\n\n public static final int current_platform;\n public static final int platformSpecificModifier;\n\n public static final String SEP = System.getProperty(\"file.separator\");\n\n private static File userDataDirectory = null;\n private static Map<String, Object> JNA_OPTIONS = new HashMap<String, Object>();\n\n static {\n platformSpecificModifier = Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx();\n if (com.sun.jna.Platform.isWindows()) {\n current_platform = WIN;\n JNA_OPTIONS.put(Library.OPTION_TYPE_MAPPER, W32APITypeMapper.UNICODE);\n JNA_OPTIONS.put(Library.OPTION_FUNCTION_MAPPER, W32APIFunctionMapper.UNICODE);\n } else if (com.sun.jna.Platform.isMac()) {\n current_platform = MAC;\n } else {\n current_platform = OTHER;\n }\n }\n\n public static boolean onMac() {\n return current_platform == MAC;\n }\n\n public static boolean onWindows() {\n return current_platform == WIN;\n }\n\n public static boolean onOther() {\n return current_platform == OTHER;\n }\n\n //// Application directories ////\n\n public static File getHomeDirectory() {\n return new File(System.getProperty(\"user.home\"));\n }\n\n /**\n * Get the directory that contains the user's NodeBox library directory.\n * <p/>\n * <p/>\n * <ul>\n * <li>Mac: <code>/Users/username/Library/NodeBox</code></li>\n * <li>Windows: <code>/Documents And Settings/username/Local Settings/Application Data/NodeBox</code></li>\n * <li>Linux/BSD/Other: <code>~/.local/share/nodebox</code></li>\n * </ul>\n *\n * @return the user's library directory.\n */\n public static File getUserDataDirectory() throws RuntimeException {\n if (userDataDirectory != null)\n return userDataDirectory;\n if (onMac()) {\n userDataDirectory = new File(getHomeDirectory(), \"Library/\" + Application.NAME);\n } else if (onWindows()) {\n String localAppData;\n HWND hwndOwner = null;\n int nFolder = Shell32.CSIDL_LOCAL_APPDATA;\n HANDLE hToken = null;\n int dwFlags = Shell32.SHGFP_TYPE_CURRENT;\n char[] pszPath = new char[Shell32.MAX_PATH];\n int hResult = Shell32.INSTANCE.SHGetFolderPath(hwndOwner, nFolder, hToken, dwFlags, pszPath);\n if (Shell32.S_OK == hResult) {\n String path = new String(pszPath);\n int len = path.indexOf('\\0');\n localAppData = path.substring(0, len);\n } else {\n // If the native call fails, use the home directory.\n localAppData = getHomeDirectory().getPath();\n }\n userDataDirectory = new File(localAppData, Application.NAME);\n } else {\n userDataDirectory = new File(getHomeDirectory(), \".local/share/\" + Application.NAME.toLowerCase(Locale.US));\n }\n return userDataDirectory;\n }\n\n /**\n * Get the directory that contains NodeBox scripts the user has installed.\n * <p/>\n * <ul>\n * <li>Mac: <code>/Users/username/Library/NodeBox/Scripts</code></li>\n * <li>Windows: <code>/Users/username/Application Data/NodeBox/Scripts</code></li>\n * <li>Linux/BSD/Other: <code>~/.local/share/nodebox/scripts</code></li>\n * </ul>\n *\n * @return the user's NodeBox scripts directory.\n */\n public static File getUserScriptsDirectory() {\n if (onMac() || onWindows())\n return new File(getUserDataDirectory(), \"Scripts\");\n else\n return new File(getUserDataDirectory(), \"scripts\");\n }\n\n /**\n * Get the directory that contains Python libraries the user has installed.\n * <p/>\n * This directory is added to the PYTHONPATH; anything below it can be used in scripts.\n * <p/>\n * <ul>\n * <li>Mac: <code>/Users/username/Library/NodeBox/Python</code></li>\n * <li>Windows: <code>/Users/username/Application Data/NodeBox/Python</code></li>\n * <li>Linux/BSD/Other: <code>~/.local/share/nodebox/python</code></li>\n * </ul>\n *\n * @return the user's Python directory.\n */\n public static File getUserPythonDirectory() {\n if (onMac() || onWindows())\n return new File(getUserDataDirectory(), \"Python\");\n else\n return new File(getUserDataDirectory(), \"python\");\n }\n\n /**\n * Get the directory that contains the application's builtin NodeBox scripts.\n *\n * @return the application's NodeBox scripts directory.\n */\n public static File getApplicationScriptsDirectory() {\n return new File(\"libraries\");\n }\n\n //// Keystrokes ////\n\n public static KeyStroke getKeyStroke(int key) {\n return KeyStroke.getKeyStroke(key, platformSpecificModifier);\n }\n\n public static KeyStroke getKeyStroke(int key, int modifier) {\n return KeyStroke.getKeyStroke(key, platformSpecificModifier | modifier);\n }\n\n public static void openURL(String url) {\n try {\n Desktop.getDesktop().browse(URI.create(url));\n } catch (IOException e) {\n JOptionPane.showMessageDialog(null, \"Could not open browser window. Go to \" + url + \" directly. \\n\" + e.getLocalizedMessage());\n }\n }\n\n private static class HANDLE extends PointerType implements NativeMapped {\n }\n\n private static class HWND extends HANDLE {\n }\n\n private static interface Shell32 extends Library {\n\n public static final int MAX_PATH = 260;\n public static final int CSIDL_LOCAL_APPDATA = 0x001c;\n public static final int SHGFP_TYPE_CURRENT = 0;\n public static final int S_OK = 0;\n\n static Shell32 INSTANCE = (Shell32) Native.loadLibrary(\"shell32\", Shell32.class, JNA_OPTIONS);\n\n /**\n * See http://msdn.microsoft.com/en-us/library/bb762181(VS.85).aspx\n * <p/>\n *\n * @param hwndOwner [in] Reserved.\n * @param nFolder [in] A CSIDL value that identifies the folder whose path is to be retrieved.\n * @param hToken [in] An access token that can be used to represent a particular user. Always set this to null.\n * @param dwFlags [in] Flags that specify the path to be returned.\n * @param pszPath [out] A pointer to a null-terminated string of length MAX_PATH which will receive the path.\n * @return S_OK if successful, or an error value otherwise.\n */\n public int SHGetFolderPath(HWND hwndOwner, int nFolder, HANDLE hToken,\n int dwFlags, char[] pszPath);\n }\n\n\n}",
"public class ProgressDialog extends JDialog {\n\n private JProgressBar progressBar;\n private JLabel progressLabel;\n private JLabel messageLabel;\n private int tasksCompleted;\n private int taskCount;\n\n public ProgressDialog(Frame owner, String title) {\n super(owner, title, false);\n getRootPane().putClientProperty(\"Window.style\", \"small\");\n setResizable(false);\n setLayout(null);\n Container contentPane = getContentPane();\n contentPane.setLayout(null);\n tasksCompleted = 0;\n this.taskCount = 0;\n progressBar = new JProgressBar(JProgressBar.HORIZONTAL, 0, taskCount);\n progressBar.setIndeterminate(true);\n progressBar.setBounds(10, 10, 300, 32);\n contentPane.add(progressBar);\n progressLabel = new JLabel();\n progressLabel.setBounds(320, 10, 50, 32);\n progressLabel.setVisible(false);\n contentPane.add(progressLabel);\n messageLabel = new JLabel();\n messageLabel.setBounds(10, 40, 380, 32);\n contentPane.add(messageLabel);\n updateProgress();\n setSize(400, 100);\n setLocationRelativeTo(owner);\n }\n\n public void setTaskCount(int taskCount) {\n this.taskCount = taskCount;\n this.tasksCompleted = 0;\n progressBar.setIndeterminate(false);\n progressBar.setMaximum(taskCount);\n progressLabel.setVisible(true);\n\n }\n\n public void reset() {\n setTaskCount(this.taskCount);\n }\n\n public void updateProgress() {\n updateProgress(this.tasksCompleted);\n }\n\n public void updateProgress(int tasksCompleted) {\n progressBar.setValue(tasksCompleted);\n double percentage = (double) (tasksCompleted) / (double) (taskCount);\n int ip = (int) (percentage * 100);\n progressLabel.setText(ip + \" %\");\n repaint();\n }\n\n public void tick() {\n // Increment the tasks completed, but it can never be higher than the number of tasks.\n tasksCompleted = Math.min(tasksCompleted + 1, taskCount);\n updateProgress();\n }\n\n public void setMessage(String message) {\n messageLabel.setText(message);\n }\n\n\n}",
"public class Updater {\n\n public static final String LAST_UPDATE_CHECK = \"NBLastUpdateCheck\";\n public static final long UPDATE_INTERVAL = 1000 * 60 * 60 * 24; // 1000 milliseconds * 60 seconds * 60 minutes * 24 hours = Every day\n\n private final Host host;\n private Icon hostIcon;\n private boolean automaticCheck;\n private Preferences preferences;\n private UpdateChecker updateChecker;\n private UpdateDelegate delegate;\n private UpdateCheckDialog updateCheckDialog;\n\n public Updater(Host host) {\n this.host = host;\n automaticCheck = true;\n Class hostClass = host.getClass();\n this.preferences = Preferences.userNodeForPackage(hostClass);\n }\n\n public Host getHost() {\n return host;\n }\n\n public Icon getHostIcon() {\n if (hostIcon != null) return hostIcon;\n BufferedImage img = new BufferedImage(64, 64, BufferedImage.TYPE_INT_ARGB);\n Graphics2D g = (Graphics2D) img.getGraphics();\n Icon icon = new ImageIcon(host.getIconFile());\n float factor = 64f / icon.getIconHeight();\n g.scale(factor, factor);\n icon.paintIcon(null, g, 0, 0);\n hostIcon = new ImageIcon(img);\n return hostIcon;\n }\n\n public UpdateDelegate getDelegate() {\n return delegate;\n }\n\n public void setDelegate(UpdateDelegate delegate) {\n this.delegate = delegate;\n }\n\n public UpdateChecker getUpdateChecker() {\n return updateChecker;\n }\n\n /**\n * Notification sent from the application that the updater can do its thing.\n */\n public void applicationDidFinishLaunching() {\n checkForUpdatesInBackground();\n }\n\n public boolean isAutomaticCheck() {\n return automaticCheck;\n }\n\n /**\n * This method is initialized by a user action.\n * <p/>\n * It will check for updates and reports its findings in a user dialog.\n */\n public void checkForUpdates() {\n checkForUpdates(true);\n }\n\n /**\n * This method is initialized by a user action.\n * <p/>\n * It will check for updates and reports its findings in a user dialog.\n *\n * @param showProgressWindow if true, shows the progress window.\n */\n public void checkForUpdates(boolean showProgressWindow) {\n if (updateChecker != null && updateChecker.isAlive()) return;\n if (showProgressWindow) {\n updateCheckDialog = new UpdateCheckDialog(null, this);\n updateCheckDialog.setLocationRelativeTo(null);\n updateCheckDialog.setVisible(true);\n }\n updateChecker = new UpdateChecker(this, false);\n updateChecker.start();\n }\n\n /**\n * This method gets run when automatically checking for updates.\n * <p/>\n * If no updates are found, results are silently discarded. If an update is found, the update dialog will show.\n */\n public void checkForUpdatesInBackground() {\n if (shouldCheckForUpdate()) {\n updateChecker = new UpdateChecker(this, true);\n updateChecker.start();\n }\n }\n\n /**\n * Determines if the last check was far enough in the past to justify a new check.\n *\n * @return if the enough time has passed since the last check.\n */\n public boolean shouldCheckForUpdate() {\n long lastTime = getPreferences().getLong(LAST_UPDATE_CHECK, 0);\n long deltaTime = System.currentTimeMillis() - lastTime;\n return deltaTime > UPDATE_INTERVAL;\n }\n\n public Preferences getPreferences() {\n return preferences;\n }\n\n /**\n * The update checker completed the check without error.\n *\n * @param checker the update checker\n * @param appcast the appcast\n */\n public void checkCompleted(UpdateChecker checker, Appcast appcast) {\n hideUpdateCheckDialog();\n // Delegate method.\n if (delegate != null)\n if (delegate.checkCompleted(checker, appcast))\n return;\n\n // Store last check update check time.\n getPreferences().putLong(LAST_UPDATE_CHECK, System.currentTimeMillis());\n try {\n getPreferences().flush();\n } catch (BackingStoreException e) {\n throw new RuntimeException(\"Error while storing preferences\", e);\n }\n }\n\n public void checkerFoundValidUpdate(UpdateChecker checker, Appcast appcast) {\n // Delegate method.\n if (delegate != null)\n if (delegate.checkerFoundValidUpdate(checker, appcast))\n return;\n\n UpdateAlert alert = new UpdateAlert(this, appcast);\n alert.setLocationRelativeTo(null);\n alert.setVisible(true);\n }\n\n public void checkerDetectedLatestVersion(UpdateChecker checker, Appcast appcast) {\n // Delegate method.\n if (delegate != null)\n if (delegate.checkerDetectedLatestVersion(checker, appcast))\n return;\n\n // Show a message that you're using the latest version if you've explicitly checked for updates.\n if (!checker.isSilent()) {\n JOptionPane.showMessageDialog(null, \"<html><b>You're up to date!</b><br>\\n\" + host.getName() + \" \" + host.getVersion() + \" is the latest version available.\", \"\", JOptionPane.INFORMATION_MESSAGE, getHostIcon());\n }\n }\n\n public void checkerEncounteredError(UpdateChecker checker, Throwable t) {\n hideUpdateCheckDialog();\n // Delegate method.\n if (delegate != null)\n if (delegate.checkerEncounteredError(checker, t))\n return;\n if (checker.isSilent()) {\n Log.warn(\"Update checker encountered error.\", t);\n } else {\n throw new RuntimeException(t);\n }\n }\n\n public void waitForCheck(int timeoutMillis) {\n try {\n updateChecker.join(timeoutMillis);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n if (updateChecker.isAlive()) {\n updateChecker.interrupt();\n }\n }\n\n public void cancelUpdateCheck() {\n if (updateChecker != null && updateChecker.isAlive()) {\n updateChecker.interrupt();\n }\n }\n\n private void hideUpdateCheckDialog() {\n if (updateCheckDialog != null) {\n updateCheckDialog.setVisible(false);\n updateCheckDialog = null;\n }\n }\n}"
] | import nodebox.Log;
import nodebox.node.NodeLibrary;
import nodebox.node.NodeRepository;
import nodebox.ui.ExceptionDialog;
import nodebox.ui.LastResortHandler;
import nodebox.ui.Platform;
import nodebox.ui.ProgressDialog;
import nodebox.versioncheck.Host;
import nodebox.versioncheck.Updater;
import nodebox.versioncheck.Version;
import javax.swing.*;
import java.awt.*;
import java.awt.desktop.*;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.prefs.Preferences; | /*
* This file is part of NodeBox.
*
* Copyright (C) 2008 Frederik De Bleser (frederik@pandora.be)
*
* NodeBox is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* NodeBox is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NodeBox. If not, see <http://www.gnu.org/licenses/>.
*/
package nodebox.client;
public class Application implements Host {
public static final String PREFERENCE_ENABLE_DEVICE_SUPPORT = "NBEnableDeviceSupport";
public static boolean ENABLE_DEVICE_SUPPORT = false;
private static Application instance;
private JFrame hiddenFrame;
private ExamplesBrowser examplesBrowser;
public static Application getInstance() {
return instance;
}
private AtomicBoolean startingUp = new AtomicBoolean(true);
private SwingWorker<Throwable, String> startupWorker;
private Updater updater;
private List<NodeBoxDocument> documents = new ArrayList<NodeBoxDocument>();
private NodeBoxDocument currentDocument;
private NodeRepository systemRepository;
private ProgressDialog startupDialog;
private Version version;
private List<File> filesToLoad = Collections.synchronizedList(new ArrayList<File>());
private Console console = null;
public static final String NAME = "NodeBox";
private Application() {
instance = this;
initLastResortHandler();
initLookAndFeel();
System.setProperty("line.separator", "\n");
}
//// Application Load ////
/**
* Starts a SwingWorker that loads the application in the background.
* <p>
* Called in the event dispatch thread using invokeLater.
*/
private void run() {
showProgressDialog();
startupWorker = new SwingWorker<Throwable, String>() {
@Override
protected Throwable doInBackground() throws Exception {
try {
publish("Starting NodeBox");
initApplication();
checkForUpdates();
} catch (RuntimeException ex) {
return ex;
}
return null;
}
@Override
protected void process(List<String> strings) {
final String firstString = strings.get(0);
startupDialog.setMessage(firstString);
}
@Override
protected void done() {
startingUp.set(false);
startupDialog.setVisible(false);
// See if application startup has generated an exception.
Throwable t;
try {
t = get();
} catch (Exception e) {
t = e;
}
if (t != null) {
ExceptionDialog ed = new ExceptionDialog(null, t);
ed.setVisible(true);
System.exit(-1);
}
if (documents.isEmpty() && filesToLoad.isEmpty()) {
instance.createNewDocument();
} else {
for (File f : filesToLoad) {
openDocument(f);
}
}
}
};
startupWorker.execute();
}
private void initApplication() {
installDefaultExceptionHandler();
setNodeBoxVersion();
createNodeBoxDataDirectories();
applyPreferences();
registerForMacOSXEvents();
initPython();
}
private void installDefaultExceptionHandler() {
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread t, final Throwable e) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
ExceptionDialog d = new ExceptionDialog(null, e);
d.setVisible(true);
}
});
}
});
}
private void checkForUpdates() {
updater = new Updater(Application.this);
updater.checkForUpdatesInBackground();
}
/**
* Sets a handler for uncaught exceptions that pops up a message dialog with the exception.
* <p>
* Called from the constructor, in the main thread.
*/
private void initLastResortHandler() { | Thread.currentThread().setUncaughtExceptionHandler(new LastResortHandler()); | 1 |
holmes-org/holmes-validation | src/main/java/org/holmes/HolmesEngine.java | [
"public class BooleanEvaluator extends ObjectEvaluator<Boolean> {\n\n\tpublic BooleanEvaluator(Boolean target) {\n\n\t\tsuper(target);\n\t}\n\n\t/**\n\t * Ensures that the {@link Boolean} target is not null and it's logical value is TRUE.\n\t * \n\t * @return an instance of {@link Joint} class\n\t */\n\tpublic Joint isTrue() {\n\n\t\treturn setEvaluation(new Evaluation<Boolean>() {\n\n\t\t\tpublic boolean evaluate(Boolean target) {\n\n\t\t\t\treturn target != null && target;\n\t\t\t}\n\t\t\t\n\t\t}).getJoint();\n\t}\n\t\n\t/**\n\t * Ensures that the {@link Boolean} target is not null and it's logical value is FALSE.\n\t * \n\t * @return an instance of {@link Joint} class\n\t */\n\tpublic Joint isFalse() {\n\t\t\n\t\treturn setEvaluation(new Evaluation<Boolean>() {\n\n\t\t\tpublic boolean evaluate(Boolean target) {\n\n\t\t\t\treturn target != null && !target;\n\t\t\t}\n\t\t\t\n\t\t}).getJoint();\n\t}\n\n}",
"public class CollectionEvaluator<E> extends ObjectEvaluator<Collection<E>> {\n\n\tpublic CollectionEvaluator(Collection<E> target) {\n\t\tsuper(target);\n\t}\n\n\t/**\n\t * Evaluates the number of occurrences of\n\t * <code>element<code> in the target collection\n\t * \n\t * @param element\n\t * an element.\n\t * @return an instance of {@link NumberEvaluator}\n\t */\n\tpublic NumberEvaluator cardinalityOf(final E element) {\n\n\t\tfinal FutureNumber futureNumber = new FutureNumber();\n\t\tfinal NumberEvaluator evaluator = new NumberEvaluator(futureNumber);\n\n\t\tsetEvaluation(new Evaluation<Collection<E>>() {\n\n\t\t\tpublic boolean evaluate(Collection<E> target) {\n\n\t\t\t\tif (target == null) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t\tfutureNumber.wrap(getCardinality(element, target));\n\t\t\t\treturn evaluator.evaluate();\n\t\t\t}\n\t\t});\n\n\t\tevaluator.setJoint(getJoint());\n\t\treturn evaluator;\n\t}\n\n\t/**\n\t * Evaluates the size of the target collection. A null collection has no\n\t * size!\n\t * \n\t * @return an instance of {@link NumberEvaluator}\n\t */\n\tpublic NumberEvaluator size() {\n\n\t\tfinal FutureNumber futureNumber = new FutureNumber();\n\t\tfinal NumberEvaluator evaluator = new NumberEvaluator(futureNumber);\n\n\t\tsetEvaluation(new Evaluation<Collection<E>>() {\n\n\t\t\tpublic boolean evaluate(Collection<E> target) {\n\n\t\t\t\tif (target == null) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t\tfutureNumber.wrap(target.size());\n\t\t\t\treturn evaluator.evaluate();\n\t\t\t}\n\t\t});\n\n\t\tevaluator.setJoint(getJoint());\n\t\treturn evaluator;\n\t}\n\n\t/**\n\t * Ensures that the target does not contain elements.\n\t * \n\t * @return an instance of {@link Joint} class\n\t */\n\tpublic Joint isEmpty() {\n\n\t\treturn setEvaluation(new Evaluation<Collection<E>>() {\n\n\t\t\tpublic boolean evaluate(Collection<E> target) {\n\n\t\t\t\treturn target == null || target.isEmpty();\n\t\t\t}\n\n\t\t}).getJoint();\n\t}\n\n\t/**\n\t * Ensures that the target contains any element.\n\t * \n\t * @return an instance of {@link Joint} class\n\t */\n\tpublic Joint isNotEmpty() {\n\n\t\treturn setEvaluation(new Evaluation<Collection<E>>() {\n\n\t\t\tpublic boolean evaluate(Collection<E> target) {\n\n\t\t\t\treturn target != null && !target.isEmpty();\n\t\t\t}\n\n\t\t}).getJoint();\n\t}\n\n\t/**\n\t * Ensures that the target collection contains an <code>element</code>.\n\t * \n\t * @return an instance of {@link Joint} class\n\t */\n\tpublic Joint contains(final E element) {\n\n\t\treturn setEvaluation(new Evaluation<Collection<E>>() {\n\n\t\t\tpublic boolean evaluate(Collection<E> target) {\n\n\t\t\t\treturn target != null && target.contains(element);\n\t\t\t}\n\n\t\t}).getJoint();\n\t}\n\n\t/**\n\t * Ensures that the target collection does not contain an\n\t * <code>element</code>.\n\t * \n\t * @return an instance of {@link Joint} class\n\t */\n\tpublic Joint doesNotContain(final E element) {\n\n\t\treturn setEvaluation(new Evaluation<Collection<E>>() {\n\n\t\t\tpublic boolean evaluate(Collection<E> target) {\n\n\t\t\t\treturn target != null && !target.contains(element);\n\t\t\t}\n\n\t\t}).getJoint();\n\t}\n\n\t/**\n\t * Ensures that the target collection contains all elements of\n\t * <code>collection</code>.\n\t * \n\t * @return an instance of {@link Joint} class\n\t */\n\tpublic Joint containsAll(final Collection<E> collection) {\n\n\t\treturn setEvaluation(new Evaluation<Collection<E>>() {\n\n\t\t\tpublic boolean evaluate(Collection<E> target) {\n\n\t\t\t\tif (collection == null || target == null) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t\tfor (E e : collection) {\n\t\t\t\t\tif (!target.contains(e)) {\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t}).getJoint();\n\t}\n\n\t/**\n\t * Ensures that the target collection contains any elements of\n\t * <code>collection</code>.\n\t * \n\t * @return an instance of {@link Joint} class\n\t */\n\tpublic Joint containsAny(final Collection<E> collection) {\n\n\t\treturn setEvaluation(new Evaluation<Collection<E>>() {\n\n\t\t\tpublic boolean evaluate(Collection<E> target) {\n\n\t\t\t\tif (collection == null || target == null) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t\tfor (E e : collection) {\n\t\t\t\t\tif (target.contains(e)) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t}).getJoint();\n\t}\n\n\t/**\n\t * Ensures that all the elements of the target collection are valid by the\n\t * <code>validator</code>.\n\t * \n\t * @return an instance of {@link Joint} class\n\t */\n\tpublic Joint hasAllValidBy(final Validator<E> validator) {\n\n\t\treturn setEvaluation(new Evaluation<Collection<E>>() {\n\n\t\t\tpublic boolean evaluate(Collection<E> target) {\n\n\t\t\t\tif (target == null || validator == null) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t\tfor (E e : target) {\n\t\t\t\t\tif (!validator.isValid(e)) {\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t}).getJoint();\n\t}\n\n\tprivate int getCardinality(E element, Collection<E> collection) {\n\n\t\tint cardinality = 0;\n\n\t\tfor (E e : collection) {\n\n\t\t\tif ((element == null && e == null)\n\t\t\t\t\t|| (element != null && element.equals(e))) {\n\t\t\t\tcardinality++;\n\t\t\t}\n\t\t}\n\n\t\treturn cardinality;\n\t}\n\n}",
"public class DateEvaluator extends ObjectEvaluator<Date> {\n\n\tprivate static final int ZERO = 0;\n\n\tpublic DateEvaluator(Date target) {\n\t\tsuper(target);\n\t}\n\n\t/**\n\t * Applies a diff between the target and a past or future date.\n\t * \n\t * @param diff\n\t * The diff configuration.\n\t * @return {@link NumberEvaluator}\n\t */\n\tpublic NumberEvaluator applying(final Diff diff) {\n\n\t\tfinal FutureNumber futureNumber = new FutureNumber();\n\t\tfinal NumberEvaluator evaluator = new NumberEvaluator(futureNumber);\n\n\t\tsetEvaluation(new Evaluation<Date>() {\n\n\t\t\tpublic boolean evaluate(Date target) {\n\n\t\t\t\tdiff.setTarget(target);\n\t\t\t\tfutureNumber.wrap(diff.calculate());\n\n\t\t\t\treturn evaluator.evaluate();\n\t\t\t}\n\t\t});\n\n\t\tevaluator.setJoint(getJoint());\n\t\treturn evaluator;\n\t}\n\n\t/**\n\t * Ensures that the target is a date in the past.\n\t * \n\t * @return an instance of {@link Joint} class\n\t */\n\tpublic Joint isPast() {\n\n\t\treturn isBeforeThan(new Date());\n\t}\n\n\t/**\n\t * Ensures that the target is a date in the future.\n\t * \n\t * @return an instance of {@link Joint} class\n\t */\n\tpublic Joint isFuture() {\n\n\t\treturn isAfterThan(new Date());\n\t}\n\n\t/**\n\t * Ensures that the target is after than the argument date.\n\t * \n\t * @param date\n\t * the date to compare the target to\n\t * @return an instance of {@link Joint} class\n\t */\n\tpublic Joint isAfterThan(final Date date) {\n\n\t\treturn setEvaluation(new Evaluation<Date>() {\n\n\t\t\tpublic boolean evaluate(Date target) {\n\n\t\t\t\treturn target.compareTo(date) > ZERO;\n\t\t\t}\n\n\t\t}).getJoint();\n\t}\n\n\t/**\n\t * Ensures that the target is after than or equal to the argument date.\n\t * \n\t * @param date\n\t * the date to compare the target to\n\t * @return an instance of {@link Joint} class\n\t */\n\tpublic Joint isAfterThanOrEqualTo(final Date date) {\n\n\t\treturn setEvaluation(new Evaluation<Date>() {\n\n\t\t\tpublic boolean evaluate(Date target) {\n\n\t\t\t\treturn target.compareTo(date) >= ZERO;\n\t\t\t}\n\n\t\t}).getJoint();\n\t}\n\n\t/**\n\t * Ensures that the target is before than the argument date.\n\t * \n\t * @param date\n\t * the date to compare the target to\n\t * @return an instance of {@link Joint} class\n\t */\n\tpublic Joint isBeforeThan(final Date date) {\n\n\t\treturn setEvaluation(new Evaluation<Date>() {\n\n\t\t\tpublic boolean evaluate(Date target) {\n\n\t\t\t\treturn target.compareTo(date) < ZERO;\n\t\t\t}\n\n\t\t}).getJoint();\n\t}\n\n\t/**\n\t * Ensures that the target is before than or equal to the argument date.\n\t * \n\t * @param date\n\t * the date to compare the target to\n\t * @return an instance of {@link Joint} class\n\t */\n\tpublic Joint isBeforeThanOrEqualTo(final Date date) {\n\n\t\treturn setEvaluation(new Evaluation<Date>() {\n\n\t\t\tpublic boolean evaluate(Date target) {\n\n\t\t\t\treturn target.compareTo(date) <= ZERO;\n\t\t\t}\n\n\t\t}).getJoint();\n\t}\n\n\t/**\n\t * Ensures that the target belongs to the closed interval [leftBoundary,\n\t * rightBoundary].\n\t * \n\t * @param leftBoundary\n\t * the left boundary, inclusive.\n\t * @param rightBoundary\n\t * the right boundary, inclusive.\n\t * @return an instance of {@link Joint} class\n\t */\n\tpublic Joint belongsToInterval(final Date leftBoundary, final Date rightBoundary) {\n\n\t\treturn setEvaluation(new Evaluation<Date>() {\n\n\t\t\tpublic boolean evaluate(Date target) {\n\n\t\t\t\treturn Interval.closedInterval(leftBoundary, rightBoundary).contains(target);\n\t\t\t}\n\n\t\t}).getJoint();\n\t}\n\n\t/**\n\t * Ensures that the target belongs to the left-open interval (leftBoundary,\n\t * rightBoundary].\n\t * \n\t * @param leftBoundary\n\t * the left boundary, exclusive.\n\t * @param rightBoundary\n\t * the right boundary, inclusive.\n\t * @return an instance of {@link Joint} class\n\t */\n\tpublic Joint belongsToLeftOpenInterval(final Date leftBoundary, final Date rightBoundary) {\n\n\t\treturn setEvaluation(new Evaluation<Date>() {\n\n\t\t\tpublic boolean evaluate(Date target) {\n\n\t\t\t\treturn Interval.leftOpenInterval(leftBoundary, rightBoundary).contains(target);\n\t\t\t}\n\n\t\t}).getJoint();\n\t}\n\n\t/**\n\t * Ensures that the target belongs to the right-open interval [leftBoundary,\n\t * rightBoundary).\n\t * \n\t * @param leftBoundary\n\t * the left boundary, inclusive.\n\t * @param rightBoundary\n\t * the right boundary, exclusive.\n\t * @return an instance of {@link Joint} class\n\t */\n\tpublic Joint belongsToRightOpenInterval(final Date leftBoundary, final Date rightBoundary) {\n\n\t\treturn setEvaluation(new Evaluation<Date>() {\n\n\t\t\tpublic boolean evaluate(Date target) {\n\n\t\t\t\treturn Interval.rightOpenInterval(leftBoundary, rightBoundary).contains(target);\n\t\t\t}\n\n\t\t}).getJoint();\n\t}\n\n\t/**\n\t * Ensures that the target belongs to the open interval (leftBoundary,\n\t * rightBoundary).\n\t * \n\t * @param leftBoundary\n\t * the left boundary, exclusive.\n\t * @param rightBoundary\n\t * the right boundary, exclusive.\n\t * @return an instance of {@link Joint} class\n\t */\n\tpublic Joint belongsToOpenInterval(final Date leftBoundary, final Date rightBoundary) {\n\n\t\treturn setEvaluation(new Evaluation<Date>() {\n\n\t\t\tpublic boolean evaluate(Date target) {\n\n\t\t\t\treturn Interval.openInterval(leftBoundary, rightBoundary).contains(target);\n\t\t\t}\n\n\t\t}).getJoint();\n\t}\n}",
"public class NumberEvaluator extends ObjectEvaluator<Number> {\n\n\tprivate static final int MINUS_ONE = -1;\n\n\tprivate static final int ZERO = 0;\n\n\tprivate static final int ONE = 1;\n\n\tprivate static final BigInteger BIG_INT_TWO = BigInteger.valueOf(2);\n\n\tpublic NumberEvaluator(final Number target) {\n\n\t\tsuper(target);\n\t}\n\t\n\t/**\n\t * Ensures that the target value is equal to (==) the argument number.\n\t * \n\t * @param number\n\t * the number to compare the target to.\n\t * @return an instance of {@link Joint} class\n\t */\n\t@Override\n\tpublic Joint isEqualTo(final Number number) {\n\n\t\treturn setEvaluation(new Evaluation<Number>() {\n\n\t\t\tpublic boolean evaluate(Number target) {\n\n\t\t\t\treturn target != null && toBigDecimal(target).compareTo(toBigDecimal(number)) == ZERO;\n\t\t\t}\n\n\t\t}).getJoint();\n\t}\n\t\n\t/**\n\t * Ensures that the target value is equal to (==) the argument number.\n\t * \n\t * @param number\n\t * the number to compare the target to.\n\t * @return an instance of {@link Joint} class\n\t */\n\t@Override\n\tpublic Joint isNotEqualTo(final Number number) {\n\n\t\treturn setEvaluation(new Evaluation<Number>() {\n\n\t\t\tpublic boolean evaluate(Number target) {\n\n\t\t\t\treturn target != null && toBigDecimal(target).compareTo(toBigDecimal(number)) != ZERO;\n\t\t\t}\n\n\t\t}).getJoint();\n\t}\n\n\t/**\n\t * Ensures that the target is greater than (>) the argument number.\n\t * \n\t * @param number\n\t * the number to compare the target to.\n\t * @return an instance of {@link Joint} class\n\t */\n\tpublic Joint isGreaterThan(final Number number) {\n\n\t\treturn setEvaluation(new Evaluation<Number>() {\n\n\t\t\tpublic boolean evaluate(Number target) {\n\n\t\t\t\treturn toBigDecimal(target).compareTo(toBigDecimal(number)) > ZERO;\n\t\t\t}\n\n\t\t}).getJoint();\n\t}\n\n\t/**\n\t * Ensures that the target is greater than or equal to (>=) the argument\n\t * number.\n\t * \n\t * @param number\n\t * the number to compare the target to.\n\t * @return an instance of {@link Joint} class\n\t */\n\tpublic Joint isGreaterThanOrEqualTo(final Number number) {\n\n\t\treturn setEvaluation(new Evaluation<Number>() {\n\n\t\t\tpublic boolean evaluate(Number target) {\n\n\t\t\t\treturn toBigDecimal(target).compareTo(toBigDecimal(number)) >= ZERO;\n\t\t\t}\n\n\t\t}).getJoint();\n\t}\n\n\t/**\n\t * Ensures that the target is less than (<) the argument number.\n\t * \n\t * @param number\n\t * the number to compare the target to.\n\t * @return an instance of {@link Joint} class\n\t */\n\tpublic Joint isLessThan(final Number number) {\n\n\t\treturn setEvaluation(new Evaluation<Number>() {\n\n\t\t\tpublic boolean evaluate(Number target) {\n\n\t\t\t\treturn toBigDecimal(target).compareTo(toBigDecimal(number)) < ZERO;\n\t\t\t}\n\n\t\t}).getJoint();\n\t}\n\n\t/**\n\t * Ensures that the target is less than or equal to (<=) the argument\n\t * number.\n\t * \n\t * @param number\n\t * the number to compare the target to.\n\t * @return an instance of {@link Joint} class\n\t */\n\tpublic Joint isLessThanOrEqualTo(final Number number) {\n\n\t\treturn setEvaluation(new Evaluation<Number>() {\n\n\t\t\tpublic boolean evaluate(Number target) {\n\n\t\t\t\treturn toBigDecimal(target).compareTo(toBigDecimal(number)) <= ZERO;\n\t\t\t}\n\n\t\t}).getJoint();\n\t}\n\n\t/**\n\t * Ensures that the target is a positive number. Zero is not considered a\n\t * positive number.\n\t * \n\t * @return an instance of {@link Joint} class\n\t */\n\tpublic Joint isPositive() {\n\n\t\treturn setEvaluation(new Evaluation<Number>() {\n\n\t\t\tpublic boolean evaluate(Number target) {\n\n\t\t\t\treturn toBigDecimal(target).signum() == ONE;\n\t\t\t}\n\n\t\t}).getJoint();\n\t}\n\n\t/**\n\t * Ensures that the target is a negative number. Zero is not considered a\n\t * negative number.\n\t * \n\t * @return an instance of {@link Joint} class\n\t */\n\tpublic Joint isNegative() {\n\n\t\treturn setEvaluation(new Evaluation<Number>() {\n\n\t\t\tpublic boolean evaluate(Number target) {\n\n\t\t\t\treturn toBigDecimal(target).signum() == MINUS_ONE;\n\t\t\t}\n\n\t\t}).getJoint();\n\t}\n\n\t/**\n\t * Ensures that the target is a negative number or zero.\n\t * \n\t * @return an instance of {@link Joint} class\n\t */\n\tpublic Joint isNonPositive() {\n\n\t\treturn setEvaluation(new Evaluation<Number>() {\n\n\t\t\tpublic boolean evaluate(Number target) {\n\n\t\t\t\treturn toBigDecimal(target).signum() <= ZERO;\n\t\t\t}\n\n\t\t}).getJoint();\n\t}\n\n\t/**\n\t * Ensures that the target is a positive number or zero.\n\t * \n\t * @return an instance of {@link Joint} class\n\t */\n\tpublic Joint isNonNegative() {\n\n\t\treturn setEvaluation(new Evaluation<Number>() {\n\n\t\t\tpublic boolean evaluate(Number target) {\n\n\t\t\t\treturn toBigDecimal(target).signum() >= ZERO;\n\t\t\t}\n\n\t\t}).getJoint();\n\t}\n\n\t/**\n\t * Ensures that the target is an odd number. A number is odd if the\n\t * remainder of its division by 2 is not 0.\n\t * \n\t * @return an instance of {@link Joint} class\n\t */\n\tpublic Joint isOdd() {\n\n\t\treturn setEvaluation(new Evaluation<Number>() {\n\n\t\t\tpublic boolean evaluate(Number target) {\n\n\t\t\t\treturn !isMultiple(toBigInteger(target), BIG_INT_TWO);\n\t\t\t}\n\n\t\t}).getJoint();\n\t}\n\n\t/**\n\t * Ensures that the target is an even number. A number is even if the\n\t * remainder of its division by 2 is 0.\n\t * \n\t * @return an instance of {@link Joint} class\n\t */\n\tpublic Joint isEven() {\n\n\t\treturn setEvaluation(new Evaluation<Number>() {\n\n\t\t\tpublic boolean evaluate(Number target) {\n\n\t\t\t\treturn isMultiple(toBigInteger(target), BIG_INT_TWO);\n\t\t\t}\n\n\t\t}).getJoint();\n\t}\n\n\t/**\n\t * Ensures that the target is a multiple of the argument. A number X is\n\t * multiple of Y if X = N*Y for any integer N.\n\t * \n\t * @return an instance of {@link Joint} class\n\t */\n\tpublic Joint isMultipleOf(final Number number) {\n\n\t\treturn setEvaluation(new Evaluation<Number>() {\n\n\t\t\tpublic boolean evaluate(Number target) {\n\n\t\t\t\treturn isMultiple(toBigInteger(target), toBigInteger(number));\n\t\t\t}\n\n\t\t}).getJoint();\n\t}\n\n\t/**\n\t * Ensures that the target belongs to the closed interval [leftBoundary,\n\t * rightBoundary].\n\t * \n\t * @param leftBoundary\n\t * the left boundary, inclusive.\n\t * @param rightBoundary\n\t * the right boundary, inclusive.\n\t * @return an instance of {@link Joint} class\n\t */\n\tpublic Joint belongsToInterval(final Number leftBoundary,\n\t\t\tfinal Number rightBoundary) {\n\n\t\treturn setEvaluation(new Evaluation<Number>() {\n\n\t\t\tpublic boolean evaluate(Number target) {\n\n\t\t\t\treturn Interval.closedInterval(toBigDecimal(leftBoundary),\n\t\t\t\t\t\ttoBigDecimal(rightBoundary)).contains(\n\t\t\t\t\t\ttoBigDecimal(target));\n\t\t\t}\n\n\t\t}).getJoint();\n\t}\n\n\t/**\n\t * Ensures that the target belongs to the left-open interval (leftBoundary,\n\t * rightBoundary].\n\t * \n\t * @param leftBoundary\n\t * the left boundary, exclusive.\n\t * @param rightBoundary\n\t * the right boundary, inclusive.\n\t * @return an instance of {@link Joint} class\n\t */\n\tpublic Joint belongsToLeftOpenInterval(final Number leftBoundary,\n\t\t\tfinal Number rightBoundary) {\n\n\t\treturn setEvaluation(new Evaluation<Number>() {\n\n\t\t\tpublic boolean evaluate(Number target) {\n\n\t\t\t\treturn Interval.leftOpenInterval(toBigDecimal(leftBoundary),\n\t\t\t\t\t\ttoBigDecimal(rightBoundary)).contains(\n\t\t\t\t\t\ttoBigDecimal(target));\n\t\t\t}\n\n\t\t}).getJoint();\n\t}\n\n\t/**\n\t * Ensures that the target belongs to the right-open interval [leftBoundary,\n\t * rightBoundary).\n\t * \n\t * @param leftBoundary\n\t * the left boundary, inclusive.\n\t * @param rightBoundary\n\t * the right boundary, exclusive.\n\t * @return an instance of {@link Joint} class\n\t */\n\tpublic Joint belongsToRightOpenInterval(final Number leftBoundary,\n\t\t\tfinal Number rightBoundary) {\n\n\t\treturn setEvaluation(new Evaluation<Number>() {\n\n\t\t\tpublic boolean evaluate(Number target) {\n\n\t\t\t\treturn Interval.rightOpenInterval(toBigDecimal(leftBoundary),\n\t\t\t\t\t\ttoBigDecimal(rightBoundary)).contains(\n\t\t\t\t\t\ttoBigDecimal(target));\n\t\t\t}\n\n\t\t}).getJoint();\n\t}\n\n\t/**\n\t * Ensures that the target belongs to the open interval (leftBoundary,\n\t * rightBoundary).\n\t * \n\t * @param leftBoundary\n\t * the left boundary, exclusive.\n\t * @param rightBoundary\n\t * the right boundary, exclusive.\n\t * @return an instance of {@link Joint} class\n\t */\n\tpublic Joint belongsToOpenInterval(final Number leftBoundary,\n\t\t\tfinal Number rightBoundary) {\n\n\t\treturn setEvaluation(new Evaluation<Number>() {\n\n\t\t\tpublic boolean evaluate(Number target) {\n\n\t\t\t\treturn Interval.openInterval(toBigDecimal(leftBoundary),\n\t\t\t\t\t\ttoBigDecimal(rightBoundary)).contains(\n\t\t\t\t\t\ttoBigDecimal(target));\n\t\t\t}\n\n\t\t}).getJoint();\n\t}\n\n\tprivate boolean isMultiple(BigInteger multiple, BigInteger multipleOf) {\n\n\t\treturn multipleOf.intValue() != ZERO\n\t\t\t\t&& multiple.remainder(multipleOf).intValue() == ZERO;\n\t}\n\n\tprivate BigDecimal toBigDecimal(Number number) {\n\n\t\tif (number instanceof BigDecimal) {\n\t\t\treturn (BigDecimal) number;\n\t\t}\n\n\t\ttry {\n\n\t\t\treturn number != null ? new BigDecimal(number.toString()) : null;\n\n\t\t} catch (NumberFormatException e) {\n\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tprivate BigInteger toBigInteger(Number number) {\n\n\t\tif (number instanceof BigInteger) {\n\t\t\treturn (BigInteger) number;\n\t\t}\n\n\t\ttry {\n\n\t\t\treturn number != null ? new BigInteger(number.toString()) : null;\n\n\t\t} catch (NumberFormatException e) {\n\n\t\t\treturn null;\n\t\t}\n\t}\n}",
"public class ObjectEvaluator<T> extends AbstractEvaluator<T> {\n\n\tpublic ObjectEvaluator(T target) {\n\n\t\tsuper(target);\n\t}\n\n\t/**\n\t * Ensures that the target is null.\n\t * \n\t * @return an instance of {@link Joint} class\n\t */\n\tpublic Joint isNull() {\n\n\t\treturn setEvaluation(new Evaluation<T>() {\n\n\t\t\tpublic boolean evaluate(T target) {\n\n\t\t\t\treturn target == null;\n\t\t\t}\n\n\t\t}).getJoint();\n\t}\n\n\t/**\n\t * Ensures that the target is not null.\n\t * \n\t * @return an instance of {@link Joint} class\n\t */\n\tpublic Joint isNotNull() {\n\n\t\treturn setEvaluation(new Evaluation<T>() {\n\n\t\t\tpublic boolean evaluate(T target) {\n\n\t\t\t\treturn target != null;\n\t\t\t}\n\n\t\t}).getJoint();\n\t}\n\n\t/**\n\t * Ensures that the target is equals to the <code>other</code>.\n\t * \n\t * @param other\n\t * the object to compare the target to\n\t * @return an instance of {@link Joint} class\n\t */\n\tpublic Joint isEqualTo(final T other) {\n\n\t\treturn setEvaluation(new Evaluation<T>() {\n\n\t\t\tpublic boolean evaluate(T target) {\n\n\t\t\t\treturn (target == null && other == null)\n\t\t\t\t\t\t|| target.equals(other);\n\t\t\t}\n\n\t\t}).getJoint();\n\t}\n\n\t/**\n\t * Ensures that the target is not equals to the <code>other</code>.\n\t * \n\t * @param other\n\t * the object to compare the target to\n\t * @return an instance of {@link Joint} class\n\t */\n\tpublic Joint isNotEqualTo(final T other) {\n\n\t\treturn setEvaluation(new Evaluation<T>() {\n\n\t\t\tpublic boolean evaluate(T target) {\n\n\t\t\t\treturn (target == null && other != null)\n\t\t\t\t\t\t|| !target.equals(other);\n\t\t\t}\n\n\t\t}).getJoint();\n\t}\n\n\t/**\n\t * Ensures that the target is valid accordingly to the {@link Validator}.\n\t * \n\t * @param validator\n\t * the custom validator.\n\t * @return an instance of {@link Joint} class\n\t */\n\tpublic Joint isValidBy(final Validator<T> validator) {\n\n\t\treturn setEvaluation(new Evaluation<T>() {\n\n\t\t\tpublic boolean evaluate(T target) {\n\n\t\t\t\treturn validator.isValid(target);\n\t\t\t}\n\n\t\t}).getJoint();\n\t}\n}",
"public class StringEvaluator extends ObjectEvaluator<String> {\n\n\tpublic StringEvaluator(String target) {\n\t\tsuper(target);\n\t}\n\n\t/**\n\t * Ensures that the target does not contains characters.\n\t * \n\t * @return an instance of {@link Joint} class\n\t */\n\tpublic Joint isEmpty() {\n\n\t\treturn setEvaluation(new Evaluation<String>() {\n\n\t\t\tpublic boolean evaluate(String target) {\n\n\t\t\t\treturn target == null || target.trim().isEmpty();\n\t\t\t}\n\n\t\t}).getJoint();\n\t}\n\n\t/**\n\t * Ensures that the target contains characters.\n\t * \n\t * @return an instance of {@link Joint} class\n\t */\n\tpublic Joint isNotEmpty() {\n\n\t\treturn setEvaluation(new Evaluation<String>() {\n\n\t\t\tpublic boolean evaluate(String target) {\n\n\t\t\t\treturn !target.trim().isEmpty();\n\t\t\t}\n\n\t\t}).getJoint();\n\t}\n\n\t/**\n\t * Ensures that the target matches the pattern.\n\t * \n\t * @param pattern\n\t * the compiled regex to validate the target\n\t * @return an instance of {@link Joint} class\n\t */\n\tpublic Joint matches(final Pattern pattern) {\n\n\t\treturn setEvaluation(new Evaluation<String>() {\n\n\t\t\tpublic boolean evaluate(String target) {\n\n\t\t\t\treturn pattern.matcher(target).matches();\n\t\t\t}\n\n\t\t}).getJoint();\n\t}\n\n\t/**\n\t * Gets the {@link String} length.\n\t * \n\t * @return {@link NumberEvaluator}\n\t */\n\tpublic NumberEvaluator length() {\n\n\t\tfinal FutureNumber futureNumber = new FutureNumber();\n\t\tfinal NumberEvaluator evaluator = new NumberEvaluator(futureNumber);\n\n\t\tsetEvaluation(new Evaluation<String>() {\n\n\t\t\tpublic boolean evaluate(String target) {\n\t\t\t\tif (target == null) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tfutureNumber.wrap(target.length());\n\t\t\t\treturn evaluator.evaluate();\n\t\t\t}\n\t\t});\n\n\t\tevaluator.setJoint(getJoint());\n\t\treturn evaluator;\n\t}\n}",
"public class RuleViolationException extends RuntimeException {\n\n\tprivate static final long serialVersionUID = -6285497347762856549L;\n\n\tprivate final Object[] violationDescriptorArguments;\n\n\tpublic RuleViolationException(String violationDescriptor, Object... violationDescriptorArguments) {\n\n\t\tsuper(violationDescriptor);\n\t\tthis.violationDescriptorArguments = violationDescriptorArguments;\n\t}\n\n\tpublic String getViolationDescriptor() {\n\n\t\treturn getMessage();\n\t}\n\n\tpublic Object[] getViolationDescriptorArguments() {\n\n\t\treturn violationDescriptorArguments;\n\t}\n}",
"public class ValidationException extends RuntimeException {\n\n\tprivate static final long serialVersionUID = 3422556211439163240L;\n\n\tprivate final Set<String> violationsDescriptors;\n\n\tpublic ValidationException(Collection<String> violationsDescriptors) {\n\n\t\tthis.violationsDescriptors = new LinkedHashSet<String>(violationsDescriptors);\n\t}\n\n\tpublic Set<String> getViolationsDescriptors() {\n\n\t\treturn Collections.unmodifiableSet(violationsDescriptors);\n\t}\n\t\n\t@Override\n\tpublic String getMessage() {\n\t\t\n\t\treturn this.toString();\n\t}\n\n\t@Override\n\tpublic String toString() {\n\n\t\treturn violationsDescriptors.toString();\n\t}\n}",
"public class SimpleMessageResolver implements MessageResolver {\n\n\t@Override\n\tpublic String resolveMessage(String message, Object... arguments) {\n\t\t\n\t\treturn message;\n\t}\n}"
] | import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import org.holmes.evaluator.BooleanEvaluator;
import org.holmes.evaluator.CollectionEvaluator;
import org.holmes.evaluator.DateEvaluator;
import org.holmes.evaluator.NumberEvaluator;
import org.holmes.evaluator.ObjectEvaluator;
import org.holmes.evaluator.StringEvaluator;
import org.holmes.exception.RuleViolationException;
import org.holmes.exception.ValidationException;
import org.holmes.resolver.SimpleMessageResolver; | package org.holmes;
/**
* The main class of the framework.
*
* @author diegossilveira
*/
public class HolmesEngine {
private final List<Rule> rules;
private final ResultCollector collector;
private MessageResolver messageResolver;
private String defaultViolationDescriptor;
private HolmesEngine(ResultCollector collector) {
rules = new ArrayList<Rule>();
this.messageResolver = new SimpleMessageResolver();
this.collector = collector;
}
/**
* Initializes the engine with GREEDY {@link Op2erationMode}.
*
* @return initialized engine instance.
*/
public static HolmesEngine init() {
return new HolmesEngine(OperationMode.GREEDY.getResultCollector());
}
/**
* Initializes the engine with the given {@link OperationMode}.
*
* @param mode
* the {@link OperationMode}
* @return initialized engine instance.
*/
public static HolmesEngine init(OperationMode mode) {
return new HolmesEngine(mode.getResultCollector());
}
/**
* Initializes the engine with the given {@link ResultCollector}.
*
* @param collector
* @return initialized engine instance.
*/
public static HolmesEngine init(ResultCollector collector) {
return new HolmesEngine(collector);
}
/**
* Creates a new {@link Rule} for a {@link Boolean} target type.
*
* @param bool
* the target
* @return an appropriated {@link Evaluator} for the given target type.
*/ | public BooleanEvaluator ensureThat(final Boolean bool) { | 0 |
alda-lang/alda-client-java | src/alda/repl/commands/ReplDownUp.java | [
"public class AldaScore {\n @SerializedName(\"chord-mode\")\n public Boolean chordMode;\n @SerializedName(\"current-instruments\")\n public Set<String> currentInstruments;\n\n public Map<String, Set<String>> nicknames;\n\n /**\n * Returns the current instruments if possible\n * @return null if not possible, string array with current instruments if possible.\n */\n public Set<String> currentInstruments() {\n if (this.currentInstruments != null &&\n this.currentInstruments.size() > 0) {\n return this.currentInstruments;\n }\n return null;\n }\n}",
"public class AldaServer extends AldaProcess {\n private static final int PING_TIMEOUT = 100; // ms\n private static final int PING_RETRIES = 5;\n private static final int STARTUP_RETRY_INTERVAL = 250; // ms\n private static final int SHUTDOWN_RETRY_INTERVAL = 250; // ms\n private static final int STATUS_RETRY_INTERVAL = 200; // ms\n private static final int STATUS_RETRIES = 10;\n private static final int JOB_STATUS_INTERVAL = 250; // ms\n\n // Relevant to playing input from the REPL.\n private static final int BUSY_WORKER_TIMEOUT = 10000; // ms\n private static final int BUSY_WORKER_RETRY_INTERVAL = 500; // ms\n\n public AldaServer(AldaServerOptions opts) {\n host = normalizeHost(opts.host);\n port = opts.port;\n timeout = opts.timeout;\n verbose = opts.verbose;\n quiet = opts.quiet;\n noColor = opts.noColor;\n\n if (!noColor) AnsiConsole.systemInstall();\n }\n\n // Calculate the number of retries before giving up, based on a fixed retry\n // interval and the desired overall timeout in seconds.\n private int calculateRetries(int timeout, int interval) {\n int retriesPerSecond = 1000 / interval;\n return timeout * retriesPerSecond;\n }\n\n private boolean ping(int timeout, int retries) throws NoResponseException {\n AldaRequest req = new AldaRequest(this.host, this.port);\n req.command = \"ping\";\n AldaResponse res = req.send(timeout, retries);\n return res.success;\n }\n\n public boolean checkForConnection(int timeout, int retries) {\n try {\n return ping(timeout, retries);\n } catch (NoResponseException e) {\n return false;\n }\n }\n\n public boolean checkForConnection() {\n return checkForConnection(PING_TIMEOUT, PING_RETRIES);\n }\n\n // Waits until the process is confirmed to be up, or we reach the timeout.\n //\n // Throws a NoResponseException if the timeout is reached.\n public void waitForConnection() throws NoResponseException {\n int retries = calculateRetries(timeout, STARTUP_RETRY_INTERVAL);\n\n if (!checkForConnection(STARTUP_RETRY_INTERVAL, retries)) {\n throw new NoResponseException(\n \"Timed out waiting for response from the server.\"\n );\n }\n }\n\n // Waits until the process is confirmed to be down, i.e. there is no response\n // to \"ping,\" OR, there is a response to \"ping,\" but the response indicates\n // \"success\": false.\n //\n // Throws a NoResponseException if the process is still pingable after the\n // timeout.\n public void waitForLackOfConnection() throws NoResponseException {\n int retries = calculateRetries(timeout, SHUTDOWN_RETRY_INTERVAL);\n\n while (retries >= 0) {\n try {\n if (!ping(SHUTDOWN_RETRY_INTERVAL, 0)) return;\n } catch (NoResponseException e) {\n return;\n }\n\n Util.sleep(SHUTDOWN_RETRY_INTERVAL);\n retries--;\n }\n\n throw new NoResponseException(\n \"Timed out waiting for the server to shut down.\"\n );\n }\n\n private static String normalizeHost(String host) {\n // trim leading/trailing whitespace and trailing \"/\"\n host = host.trim().replaceAll(\"/$\", \"\");\n // prepend tcp:// if not already present\n if (!(host.startsWith(\"tcp://\"))) {\n host = \"tcp://\" + host;\n }\n return host;\n }\n\n private void assertNotRemoteHost() throws InvalidOptionsException {\n String hostWithoutProtocol = host.replaceAll(\"tcp://\", \"\");\n\n if (!hostWithoutProtocol.equals(\"localhost\")) {\n throw new InvalidOptionsException(\n \"Alda servers cannot be started remotely.\");\n }\n }\n\n public void setQuiet(boolean quiet) {\n this.quiet = quiet;\n }\n\n public void msg(String message) {\n if (quiet)\n return;\n\n String hostWithoutProtocol = host.replaceAll(\"tcp://\", \"\");\n\n String prefix;\n if (hostWithoutProtocol.equals(\"localhost\")) {\n prefix = \"\";\n } else {\n prefix = hostWithoutProtocol + \":\";\n }\n\n prefix += Integer.toString(port);\n\n if (noColor) {\n prefix = String.format(\"[%s] \", prefix);\n } else {\n prefix = String.format(\"[%s] \", ansi().fg(BLUE)\n .a(prefix)\n .reset()\n .toString());\n }\n\n System.out.println(prefix + message);\n }\n\n public void error(String message) {\n String prefix;\n if (noColor) {\n prefix = \"ERROR \";\n } else {\n prefix = ansi().fg(RED).a(\"ERROR \").reset().toString();\n }\n\n // save and restore quiet value to print out errors\n boolean oldQuiet = quiet;\n quiet = false;\n msg(prefix + message);\n quiet = oldQuiet;\n }\n\n private final String CHECKMARK = \"\\u2713\";\n private final String X = \"\\u2717\";\n\n private void announceReady() {\n if (noColor) {\n msg(\"Ready \" + CHECKMARK);\n } else {\n msg(ansi().a(\"Ready \").fg(GREEN).a(CHECKMARK).reset().toString());\n }\n }\n\n private void announceServerUp() {\n if (noColor) {\n msg(\"Server up \" + CHECKMARK);\n } else {\n msg(ansi().a(\"Server up \").fg(GREEN).a(CHECKMARK).reset().toString());\n }\n }\n\n private void announceServerDown(boolean isGood) {\n Color color = isGood ? GREEN : RED;\n String glyph = isGood ? CHECKMARK : X;\n if (noColor) {\n msg(\"Server down \" + glyph);\n } else {\n msg(ansi().a(\"Server down \").fg(color).a(glyph).reset().toString());\n }\n }\n\n private void announceServerDown() {\n announceServerDown(false);\n }\n\n public void upBg(int numberOfWorkers)\n throws InvalidOptionsException, NoResponseException, AlreadyUpException,\n SystemException {\n assertNotRemoteHost();\n\n boolean serverAlreadyUp = checkForConnection();\n if (serverAlreadyUp) {\n throw new AlreadyUpException(\"Server already up.\");\n }\n\n boolean serverAlreadyTryingToStart;\n try {\n serverAlreadyTryingToStart = SystemUtils.IS_OS_UNIX &&\n AldaClient.checkForExistingServer(port);\n } catch (SystemException e) {\n System.out.println(\"WARNING: Unable to detect whether or not there is \" +\n \"already a server running on that port.\");\n serverAlreadyTryingToStart = false;\n }\n\n if (serverAlreadyTryingToStart) {\n throw new AlreadyUpException(\n \"There is already a server trying to start on this port. Please be \" +\n \"patient -- this can take a while.\"\n );\n }\n\n Object[] opts = {\"--host\", host,\n \"--port\", Integer.toString(port),\n \"--workers\", Integer.toString(numberOfWorkers),\n \"--alda-fingerprint\"};\n\n try {\n Util.forkProgram(Util.conj(opts, \"server\"));\n msg(\"Starting Alda server...\");\n waitForConnection();\n announceServerUp();\n } catch (URISyntaxException e) {\n throw new SystemException(\n String.format(\"Unable to fork '%s' into the background.\"), e\n );\n } catch (IOException e) {\n throw new SystemException(\"Unable to fork a background process.\", e);\n }\n\n msg(\"Starting worker processes...\");\n\n int workersAvailable = 0;\n while (workersAvailable == 0) {\n Util.sleep(STARTUP_RETRY_INTERVAL);\n AldaRequest req = new AldaRequest(host, port);\n req.command = \"status\";\n AldaResponse res = req.send();\n if (res.body.contains(\"Server up\")) {\n Matcher a = Pattern.compile(\"(\\\\d+)/\\\\d+ workers available\")\n .matcher(res.body);\n if (a.find()) {\n workersAvailable = Integer.parseInt(a.group(1));\n }\n }\n }\n\n announceReady();\n }\n\n public void upFg(int numberOfWorkers) throws InvalidOptionsException {\n assertNotRemoteHost();\n\n Object[] args = {numberOfWorkers, port, verbose};\n\n Util.callClojureFn(\"alda.server/start-server!\", args);\n }\n\n public void down() throws NoResponseException {\n boolean serverAlreadyDown = !checkForConnection();\n if (serverAlreadyDown) {\n msg(\"Server already down.\");\n return;\n }\n\n msg(\"Stopping Alda server...\");\n\n AldaRequest req = new AldaRequest(host, port);\n req.command = \"stop-server\";\n\n try {\n AldaResponse res = req.send();\n if (res.success) {\n announceServerDown(true);\n } else {\n throw new NoResponseException(\"Failed to stop server.\");\n }\n } catch (NoResponseException e) {\n announceServerDown(true);\n }\n }\n\n public void downUp(int numberOfWorkers)\n throws NoResponseException, AlreadyUpException, InvalidOptionsException,\n SystemException {\n down();\n\n waitForLackOfConnection();\n // The process can still hang around sometimes, causing upBg to fail if we\n // try to do it too soon. Giving it a little extra time here as a buffer.\n Util.sleep(1000);\n\n System.out.println();\n upBg(numberOfWorkers);\n }\n\n public void status() {\n AldaRequest req = new AldaRequest(host, port);\n req.command = \"status\";\n\n try {\n AldaResponse res = req.send(STATUS_RETRY_INTERVAL, STATUS_RETRIES);\n if (!res.success) throw new UnsuccessfulException(res.body);\n msg(res.body);\n } catch (NoResponseException e) {\n announceServerDown();\n } catch (UnsuccessfulException e) {\n msg(\"Unable to report status.\");\n }\n }\n\n public void version() throws NoResponseException {\n AldaRequest req = new AldaRequest(host, port);\n req.command = \"version\";\n AldaResponse res = req.send();\n String serverVersion = res.body;\n\n msg(serverVersion);\n }\n\n public AldaResponse play(String code, String from, String to)\n throws NoAvailableWorkerException, UnsuccessfulException,\n NoResponseException {\n return play(code, null, from, to);\n }\n\n /**\n * Tries to play a bit of alda code\n *\n * @param code The pimary code to play\n * @param history The history context to supplement code\n * @param from Time to play from\n * @param to Time to stop playing\n * @return The response from the play, with useful information.\n */\n public AldaResponse play(String code, String history, String from, String to)\n throws NoAvailableWorkerException, UnsuccessfulException,\n NoResponseException {\n\n AldaRequest req = new AldaRequest(host, port);\n req.command = \"play\";\n req.body = code;\n req.options = new AldaRequestOptions();\n\n if (from != null) {\n req.options.from = from;\n }\n\n if (to != null) {\n req.options.to = to;\n }\n\n if (history != null) {\n req.options.history = history;\n }\n\n return awaitAsyncResponse(req);\n }\n\n public AldaResponse playFromRepl(String input, String history, String from,\n String to)\n throws NoAvailableWorkerException, UnsuccessfulException,\n NoResponseException {\n int retries = BUSY_WORKER_TIMEOUT / BUSY_WORKER_RETRY_INTERVAL;\n return playFromRepl(input, history, from, to, retries);\n }\n\n public AldaResponse playFromRepl(String input, String history, String from,\n String to, int retries)\n throws NoAvailableWorkerException, UnsuccessfulException,\n NoResponseException {\n // Placeholder exception; we should never see this get thrown.\n String msg = \"Unexpected error trying to play input from the Alda REPL.\";\n NoAvailableWorkerException error = new NoAvailableWorkerException(msg);\n\n // Retry until we get a NoAvailableWorkerException `retries` times.\n while (retries >= 0) {\n try {\n return play(input, history.toString(), from, to);\n } catch (NoAvailableWorkerException e) {\n error = e;\n Util.sleep(BUSY_WORKER_RETRY_INTERVAL);\n retries--;\n }\n }\n\n // Throw the most recent NoAvailableWorkerException before we ran out of\n // retries.\n throw error;\n }\n\n\n public AldaResponse jobStatus(byte[] workerAddress, String jobId)\n throws NoResponseException {\n AldaRequest req = new AldaRequest(host, port);\n req.command = \"job-status\";\n req.workerToUse = workerAddress;\n req.options = new AldaRequestOptions();\n req.options.jobId = jobId;\n return req.send();\n }\n\n public void stop() throws UnsuccessfulException {\n AldaRequest req = new AldaRequest(host, port);\n req.command = \"stop-playback\";\n\n try {\n AldaResponse res = req.send();\n if (!res.success) throw new UnsuccessfulException(res.body);\n msg(res.body);\n } catch (NoResponseException e) {\n announceServerDown();\n }\n }\n\n /**\n * Raw parsing function\n * @return Returns the result of the parse.\n */\n public String parseRaw(String code, String outputType)\n throws NoResponseException, ParseError {\n AldaRequest req = new AldaRequest(host, port);\n req.command = \"parse\";\n req.body = code;\n req.options = new AldaRequestOptions();\n req.options.output = outputType;\n AldaResponse res = req.send();\n\n if (!res.success) {\n throw new ParseError(res.body);\n }\n\n return res.body;\n }\n\n public void parse(String code, String outputType)\n throws NoResponseException, ParseError {\n String res = parseRaw(code, outputType);\n if (res != null) {\n System.out.println(res);\n }\n }\n\n public void parse(File file, String outputType)\n throws NoResponseException, ParseError, SystemException {\n String fileBody = Util.readFile(file);\n parse(fileBody, outputType);\n }\n\n public void displayInstruments() throws NoResponseException {\n AldaRequest req = new AldaRequest(host, port);\n req.command = \"instruments\";\n AldaResponse res = req.send();\n\n for (String instrument : res.instruments) {\n System.out.println(instrument);\n }\n }\n\n public AldaResponse export(String code, String outputFormat, String filename)\n throws NoAvailableWorkerException, UnsuccessfulException,\n NoResponseException {\n\n AldaRequest req = new AldaRequest(host, port);\n req.command = \"export\";\n req.body = code;\n req.options = new AldaRequestOptions();\n req.options.filename = filename;\n\n return awaitAsyncResponse(req);\n }\n\n // Makes an initial request, then makes job status requests until the request\n // is done and returns the final status response.\n private AldaResponse awaitAsyncResponse(AldaRequest req)\n throws NoAvailableWorkerException, UnsuccessfulException,\n NoResponseException {\n String jobId = UUID.randomUUID().toString();\n req.options.jobId = jobId;\n\n // The original request can have side effects (e.g. playing a score), so it\n // needs to be sent exactly once and not retried, otherwise the side effects\n // could happen multiple times.\n //\n // play requests are asynchronous; the response from the worker should be\n // immediate, and then in the code below, we repeatedly ask the worker for\n // status and send updates to the user until the status is \"playing.\"\n AldaResponse res = req.send(3000, 0);\n\n if (!res.success) {\n String noWorkersYetMsg = \"No worker processes are ready yet\";\n String workersBusyMsg = \"All worker processes are currently busy\";\n\n if (res.body.contains(noWorkersYetMsg) ||\n res.body.contains(workersBusyMsg)) {\n throw new NoAvailableWorkerException(res.body);\n } else {\n throw new UnsuccessfulException(res.body);\n }\n }\n\n if (res.workerAddress == null) {\n throw new UnsuccessfulException(\n \"No worker address included in response; unable to check for status.\"\n );\n }\n\n String status = \"requested\";\n\n while (true) {\n AldaResponse update = jobStatus(res.workerAddress, jobId);\n\n // Ensures that any update we process is for this score, and not a\n // previous one.\n if (!update.jobId.equals(jobId)) continue;\n\n // Bail out if there was some problem server-side.\n if (!update.success) throw new UnsuccessfulException(update.body);\n\n // Update the job status if it's different.\n if (!update.body.equals(status)) {\n status = update.body;\n switch (status) {\n case \"parsing\": msg(\"Parsing/evaluating...\"); break;\n case \"playing\": msg(\"Playing...\"); break;\n case \"exporting\": msg(\"Exporting...\"); break;\n // In rare cases (i.e. when the score is really short), the worker can\n // be done already.\n case \"success\": msg(\"Done.\"); break;\n default: msg(status);\n }\n }\n\n // If the job is still pending, pause and then keep looping.\n if (update.pending) {\n Util.sleep(JOB_STATUS_INTERVAL);\n } else {\n // We succeeded!\n return update;\n }\n }\n }\n}",
"public class AlreadyUpException extends AldaException {\n\n public AlreadyUpException(String msg) {\n super(msg);\n }\n\n @Override\n public ExitCode getExitCode() { return ExitCode.USER_ERROR; }\n\n}",
"public class InvalidOptionsException extends AldaException {\n\n public InvalidOptionsException(String msg) {\n super(msg);\n }\n\n @Override\n public ExitCode getExitCode() { return ExitCode.USER_ERROR; }\n\n}",
"public class NoResponseException extends AldaException {\n\n public NoResponseException(String msg) {\n super(msg);\n }\n\n @Override\n public ExitCode getExitCode() { return ExitCode.NETWORK_ERROR; }\n\n}",
"public class SystemException extends AldaException {\n public SystemException(String msg) {\n super(msg);\n }\n\n public SystemException(String msg, Throwable e) {\n super(msg, e);\n }\n\n @Override\n public ExitCode getExitCode() { return ExitCode.SYSTEM_ERROR; }\n\n}",
"public class AldaRepl {\n public static final String ASCII_ART =\n \" █████╗ ██╗ ██████╗ █████╗\\n\" +\n \"██╔══██╗██║ ██╔══██╗██╔══██╗\\n\" +\n \"███████║██║ ██║ ██║███████║\\n\" +\n \"██╔══██║██║ ██║ ██║██╔══██║\\n\" +\n \"██║ ██║███████╗██████╔╝██║ ██║\\n\" +\n \"╚═╝ ╚═╝╚══════╝╚═════╝ ╚═╝ ╚═╝\\n\";\n\n public static final int ASCII_WIDTH = ASCII_ART.substring(0, ASCII_ART.indexOf('\\n')).length();\n public static final String HELP_TEXT = \"Type :help for a list of available commands.\";\n public static final String PROMPT = \"> \";\n\n public static final int DEFAULT_NUMBER_OF_WORKERS = 2;\n\n private AldaServer server;\n private ConsoleReader r;\n private boolean verbose;\n\n private ReplCommandManager manager;\n\n private StringBuffer history;\n private FileHistory fileHistory;\n\n private String promptPrefix = \"\";\n\n public AldaRepl(AldaServer server, boolean verbose) {\n this.server = server;\n server.setQuiet(true);\n this.verbose = verbose;\n history = new StringBuffer();\n manager = new ReplCommandManager();\n try {\n r = new ConsoleReader();\n\n // Capture Ctrl-C and throw a jline.console.UserInterruptException.\n r.setHandleUserInterrupt(true);\n\n // Disable default behavior where JLine treats `!` like a Bash expansion\n // character.\n r.setExpandEvents(false);\n\n // Enable history file.\n Path historyFile = Paths.get(System.getProperty(\"user.home\"),\n \".alda-repl-history\");\n if (!historyFile.toFile().exists()) Files.createFile(historyFile);\n fileHistory = new FileHistory(historyFile.toFile());\n r.setHistory(fileHistory);\n r.setHistoryEnabled(true);\n } catch (IOException e) {\n System.err.println(\"An error was detected when we tried to read a line.\");\n e.printStackTrace();\n ExitCode.SYSTEM_ERROR.exit();\n }\n if (!server.noColor) AnsiConsole.systemInstall();\n }\n\n /**\n * Centers and colors text\n * @param totalLen the total length to center to\n * @param toFormat the string to format\n * @param color the ANSI code to color. null will result in no color\n */\n private String centerText(int totalLen, String toFormat, Color color) {\n int offset = totalLen / 2 - toFormat.length() / 2;\n String out = \"\";\n if (offset > 0) {\n // Print out spaces to center the version string\n out = out + String.format(\"%1$\"+offset+\"s\", \" \");\n }\n out = out + toFormat;\n if (!server.noColor && color != null) {\n out = ansi().fg(color).a(out).reset().toString();\n }\n return out;\n }\n\n /**\n * Sanitizes instruments to remove their inst id.\n * guitar-IrqxY becomes guitar\n */\n public String sanitizeInstrument(String instrument) {\n return instrument.replaceFirst(\"-\\\\w+$\", \"\");\n }\n\n /**\n * Converts the current instrument to it's prefix form\n * For example, midi-square-wave becomes msw\n */\n public String instrumentToPrefix(String instrument) {\n // Split on non-words\n String[] parts = instrument.split(\"\\\\W\");\n StringBuffer completedName = new StringBuffer();\n // Build new name on first char of every part from the above split.\n for (String s : parts) {\n if (s.length() > 0)\n completedName.append(s.charAt(0));\n }\n return completedName.toString();\n }\n\n public void setPromptPrefix(AldaScore score) {\n if (score != null\n\t\t&& score.currentInstruments() != null\n\t\t&& score.currentInstruments().size() > 0) {\n\t Set<String> instruments = score.currentInstruments();\n\t boolean nicknameFound = false;\n\t String newPrompt = null;\n if (score.nicknames != null) {\n\t\t// Convert nick -> inst map to inst -> nick\n\t\tfor (Map.Entry<String, Set<String>> entry : score.nicknames.entrySet()) {\n\t\t // Check to see if we are playing any instruments from the nickname value set.\n\t\t Set<String> val = entry.getValue();\n\t\t // This destroys the nicknames value sets in the process.\n\t\t val.retainAll(instruments);\n\t\t if (val.size() > 0) {\n\t\t\t// Remove a possible period seperator, IE: nickname.piano\n\t\t\tnewPrompt = entry.getKey().replaceFirst(\"\\\\.\\\\w+$\", \"\");\n\t\t\tnewPrompt = instrumentToPrefix(newPrompt);\n\t\t\tbreak;\n\t\t }\n\t\t}\n\t }\n\n\t // No groups found, translate instruments normally:\n\t if (newPrompt == null) {\n\t\tnewPrompt =\n\t\t score.currentInstruments().stream()\n\t\t // Translate instruments to nicknames if available\n\t\t .map(this::sanitizeInstrument)\n\t\t // Translate midi-electric-piano-1 -> mep1\n\t\t .map(this::instrumentToPrefix)\n\t\t // Combine all instruments with /\n\t\t .reduce(\"\", (a, b) -> a + \"/\" + b)\n\t\t // remove leading / (which is always present)\n\t\t .substring(1);\n\t }\n\n\t if (newPrompt != null && newPrompt.length() > 0) {\n promptPrefix = newPrompt;\n return;\n }\n }\n // If we failed anywhere, reset prompt (probably no instruments playing).\n promptPrefix = \"\";\n }\n\n // Used by the Alda REPL.\n //\n // Errors are handled internally; if one occurs, the stacktrace is printed and\n // execution continues.\n private void offerToStartServer() {\n System.out.println(\"The server is down. Start server on port \" +\n server.port + \"?\");\n try {\n switch (Util.promptWithChoices(r, Arrays.asList(\"yes\", \"no\", \"quit\"))) {\n case \"yes\":\n try {\n System.out.println();\n server.setQuiet(false);\n server.upBg(DEFAULT_NUMBER_OF_WORKERS);\n server.setQuiet(true);\n } catch (InvalidOptionsException | NoResponseException |\n AlreadyUpException | SystemException e) {\n System.err.println(\"Unable to start server:\");\n e.printStackTrace();\n }\n break;\n case \"no\":\n // do nothing\n break;\n case \"quit\":\n ExitCode.SUCCESS.exit();\n default:\n // this shouldn't happen; if it does, just move on\n break;\n }\n } catch (SystemException e) {\n System.err.println(\"Error trying to read character:\");\n e.printStackTrace();\n }\n System.out.println();\n }\n\n private String asciiArt() {\n if (server.noColor) return ASCII_ART;\n return ansi().fg(BLUE).a(ASCII_ART).reset().toString();\n }\n\n private String helpText() {\n if (server.noColor) return HELP_TEXT;\n return ansi().fg(WHITE).bold().a(HELP_TEXT).reset().toString();\n }\n\n public void run() {\n System.out.println(asciiArt());\n System.out.println(centerText(ASCII_WIDTH, Util.version(), CYAN));\n System.out.println(centerText(ASCII_WIDTH, \"repl session\", CYAN));\n System.out.println(\"\\n\" + helpText() + \"\\n\");\n\n if (!server.checkForConnection()) {\n offerToStartServer();\n }\n\n while (true) {\n String input = \"\";\n try {\n input = r.readLine(promptPrefix + PROMPT);\n fileHistory.flush();\n } catch (IOException e) {\n System.err.println(\"An error was detected when we tried to read a line.\");\n e.printStackTrace();\n ExitCode.SYSTEM_ERROR.exit();\n } catch (UserInterruptException e) {\n\t\tinput = \":quit\";\n\t }\n\n // Check for quick quit keywords. input is null when we get EOF\n if (input == null || input.matches(\"^:?(quit|exit|bye).*\")) {\n // If we got an EOF, we need to print a line, so we quit on a newline\n if (input == null)\n System.out.println();\n\n // Let the master quit function handle this.\n input = \":quit\";\n }\n\n if (input.length() == 0) {\n // Don't do anything if we get no input\n continue;\n }\n\n // check for :keywords and act on them\n if (input.charAt(0) == ':') {\n // throw away ':'\n input = input.substring(1);\n\n // This limits size of splitString to 2 elements.\n // All arguments will be in splitString[1]\n String[] splitString = input.split(\"\\\\s\", 2);\n ReplCommand cmd = manager.get(splitString[0]);\n\n if (cmd != null) {\n // pass in empty string if we have no arguments\n String arguments = splitString.length > 1 ? splitString[1] : \"\";\n // Run the command\n try {\n cmd.act(arguments.trim(), history, server, r, this::setPromptPrefix);\n } catch (NoResponseException e) {\n System.out.println();\n offerToStartServer();\n } catch (UserInterruptException e) {\n try {\n // Quit the repl\n cmd.act(\":quit\", history, server, r, this::setPromptPrefix);\n } catch (NoResponseException nre) {\n // This shouldn't happen, but if it does...\n nre.printStackTrace();\n // Intentionally quitting should be considered successful.\n ExitCode.SUCCESS.exit();\n }\n }\n } else {\n System.err.println(\"No command '\" + splitString[0] + \"' was found\");\n }\n } else {\n try {\n // Play the stuff we just got, with history as context\n AldaResponse playResponse = server.playFromRepl(\n input, history.toString(), null, null\n );\n\n // If we have no exceptions, add to history\n history.append(input);\n history.append(\"\\n\");\n\n // If we're good, we should check to see if we reset the instrument\n if (playResponse != null) {\n this.setPromptPrefix(playResponse.score);\n }\n } catch (NoResponseException e) {\n System.out.println();\n offerToStartServer();\n } catch (NoAvailableWorkerException | UnsuccessfulException e) {\n server.error(e.getMessage());\n if (verbose) {\n System.out.println();\n e.printStackTrace();\n }\n }\n }\n }\n }\n}"
] | import alda.AldaResponse.AldaScore;
import alda.AldaServer;
import alda.error.AlreadyUpException;
import alda.error.InvalidOptionsException;
import alda.error.NoResponseException;
import alda.error.SystemException;
import alda.repl.AldaRepl;
import java.util.function.Consumer;
import jline.console.ConsoleReader; | package alda.repl.commands;
public class ReplDownUp implements ReplCommand {
@Override | public void act(String args, StringBuffer history, AldaServer server, | 1 |
vbauer/jconditions | src/test/java/com/github/vbauer/jconditions/annotation/AbstractAnnotationsTest.java | [
"public class IfJavaVersionChecker implements ConditionChecker<IfJavaVersion> {\n\n private static final String PROPERTY_JAVA_VERSION = \"java.version\";\n\n\n /**\n * {@inheritDoc}\n */\n @Override\n public boolean isSatisfied(final CheckerContext<IfJavaVersion> context) {\n final IfJavaVersion annotation = context.getAnnotation();\n final String[] versions = annotation.value();\n return PropUtils.hasAnyWithProperties(javaVersion(), versions);\n }\n\n\n public static String javaVersion() {\n return PropUtils.getSystemProperty(PROPERTY_JAVA_VERSION).toLowerCase();\n }\n\n}",
"public class CheckerContext<T> {\n\n private final Object instance;\n private final T annotation;\n\n\n public CheckerContext(final Object instance, final T annotation) {\n this.instance = instance;\n this.annotation = annotation;\n }\n\n\n public Object getInstance() {\n return instance;\n }\n\n public T getAnnotation() {\n return annotation;\n }\n\n}",
"public interface ConditionChecker<T> {\n\n /**\n * Checks if execution of test method should be continued or not.\n *\n * @param context input data for checker\n * @return true if execution should be continued and false - otherwise\n * @throws Exception on any error (it is the same as false in return value)\n */\n boolean isSatisfied(CheckerContext<T> context) throws Exception;\n\n}",
"public class Always<T> implements ConditionChecker<T> {\n\n @Override\n public boolean isSatisfied(final CheckerContext<T> context) {\n return true;\n }\n\n}",
"public class Never<T> implements ConditionChecker<T> {\n\n @Override\n public boolean isSatisfied(final CheckerContext<T> context) {\n return false;\n }\n\n}",
"public final class FSUtils {\n\n private FSUtils() {\n throw new UnsupportedOperationException();\n }\n\n\n public static boolean exists(final String path) {\n final File file = new File(path);\n return file.exists();\n }\n\n public static boolean fileExists(final String path) {\n final File file = new File(path);\n return file.exists() && file.isFile();\n }\n\n public static boolean directoryExists(final String path) {\n final File file = new File(path);\n return file.exists() && file.isDirectory();\n }\n\n public static boolean isSymlink(final String path) throws IOException {\n final File file = new File(path);\n final File fileInCanonicalDir;\n\n if (file.getParent() == null) {\n fileInCanonicalDir = file;\n } else {\n fileInCanonicalDir = new File(file.getParentFile().getCanonicalFile(), file.getName());\n }\n\n final File canonicalFile = fileInCanonicalDir.getCanonicalFile();\n final File absoluteFile = fileInCanonicalDir.getAbsoluteFile();\n return !canonicalFile.equals(absoluteFile);\n }\n\n public static boolean deleteFile(final String path) {\n final File file = new File(path);\n return file.delete();\n }\n\n}",
"public final class PropUtils {\n\n private static final String VAR_PREFIX = \"${\";\n private static final String VAR_POSTFIX = \"}\";\n\n\n private PropUtils() {\n throw new UnsupportedOperationException();\n }\n\n\n public static String getSystemProperty(final String key) {\n final Map<String, String> properties = getSystemProperties();\n return properties.get(key);\n }\n\n public static Map<String, String> getSystemProperties() {\n final Map<String, String> result = new HashMap<>();\n result.putAll(System.getenv());\n result.putAll(convertPropertiesToMap(System.getProperties()));\n return result;\n }\n\n public static Map<String, String> convertPropertiesToMap(final Properties properties) {\n final Map<String, String> result = new HashMap<>();\n for (final String name : properties.stringPropertyNames()) {\n result.put(name, properties.getProperty(name));\n }\n return result;\n }\n\n public static String injectProperties(final String text) {\n if (text != null && text.contains(VAR_PREFIX)) {\n String result = text;\n final Map<String, String> systemProperties = getSystemProperties();\n for (final Map.Entry<String, String> entry : systemProperties.entrySet()) {\n final String key = entry.getKey();\n final String value = entry.getValue();\n result = result.replace(VAR_PREFIX + key + VAR_POSTFIX, value);\n }\n return result;\n }\n return text;\n }\n\n public static boolean hasAnyWithProperties(final String value, final String... variants) {\n for (final String operationSystem : variants) {\n final String injected = injectProperties(operationSystem);\n if (TextUtils.containsIgnoreCase(value, injected)) {\n return true;\n }\n }\n return false;\n }\n\n}"
] | import com.github.vbauer.jconditions.checker.IfJavaVersionChecker;
import com.github.vbauer.jconditions.core.CheckerContext;
import com.github.vbauer.jconditions.core.ConditionChecker;
import com.github.vbauer.jconditions.misc.Always;
import com.github.vbauer.jconditions.misc.AppleWorksFine;
import com.github.vbauer.jconditions.misc.Never;
import com.github.vbauer.jconditions.util.FSUtils;
import com.github.vbauer.jconditions.util.PropUtils;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import java.net.URL;
import java.net.URLConnection;
import java.util.concurrent.Callable; | package com.github.vbauer.jconditions.annotation;
/**
* @author Vladislav Bauer
*/
@Ignore
public abstract class AbstractAnnotationsTest implements InterfaceAnnotationsTest {
@SuppressWarnings("all")
private final boolean isSatisfiedInnerCheck = false;
@Test
@RunIf(ExceptionClass.class)
public void testIgnoreIfException() {
Assert.fail();
}
@Test | @IgnoreIf(Always.class) | 3 |
KeithYokoma/LGTMCamera | app/src/main/java/jp/yokomark/lgtm/app/compose/model/ComposeStateHolder.java | [
"public class ComposeData implements Parcelable {\n public static final Creator<ComposeData> CREATOR = new Creator<ComposeData>() {\n @Override\n @Nullable\n public ComposeData createFromParcel(Parcel source) {\n return new ComposeData(source);\n }\n\n @Override\n public ComposeData[] newArray(int size) {\n return new ComposeData[size];\n }\n };\n private Uri mImage;\n private String mText;\n private int mTextSize;\n private int mTextColor;\n\n /* package */ ComposeData(Parcel source) {\n mImage = source.readParcelable(Uri.class.getClassLoader());\n mText = source.readString();\n mTextSize = source.readInt();\n mTextColor = source.readInt();\n }\n\n public ComposeData(Uri image, String text, int textSize, int textColor) {\n mImage = image;\n mText = text;\n mTextSize = textSize;\n mTextColor = textColor;\n }\n\n public static ComposeData buildDefault(Context context, Uri uri) {\n return new ComposeData(uri, context.getString(R.string.default_lgtm_text), 80, Color.WHITE);\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n dest.writeParcelable(mImage, flags);\n dest.writeString(mText);\n dest.writeInt(mTextSize);\n dest.writeInt(mTextColor);\n }\n\n public Uri getImage() {\n return mImage;\n }\n\n public String getText() {\n return mText;\n }\n\n public int getTextSize() {\n return mTextSize;\n }\n\n public int getTextColor() {\n return mTextColor;\n }\n\n public void setText(String text) {\n mText = text;\n }\n\n public void setTextSize(int textSize) {\n mTextSize = textSize;\n }\n\n public void setTextColor(int textColor) {\n mTextColor = textColor;\n }\n}",
"public class SaveSuccessEvent {\n private final Uri mUri;\n\n public SaveSuccessEvent(Uri uri) {\n mUri = uri;\n\n }\n\n public Uri getUri() {\n return mUri;\n }\n}",
"public class SaveImageTask extends AsyncTaskLoader<Uri> {\n public static final String TAG = SaveImageTask.class.getSimpleName();\n @Inject MediaStoreClient mClient;\n private final Bitmap mBitmap;\n\n public SaveImageTask(Context context, Bitmap bitmap) {\n super(context);\n ObjectGraphUtils.getObjectGraph(context.getApplicationContext()).inject(this);\n mBitmap = bitmap;\n }\n\n @Override\n public Uri loadInBackground() {\n return mClient.save(mBitmap);\n }\n\n @Override\n protected void onStartLoading() {\n super.onStartLoading();\n forceLoad();\n }\n}",
"public final class ImageUtils {\n public static final String TAG = ImageUtils.class.getSimpleName();\n private static final int MAX_WIDTH_ON_VIEW = 1600;\n private static final String SCHEME_CONTENT = \"content\";\n\n private ImageUtils() {\n throw new AssertionError();\n }\n\n public static Point getRawBitmapBound(ContentResolver resolver, Uri uri) {\n InputStream is = null;\n try {\n BitmapFactory.Options options = new BitmapFactory.Options();\n options.inJustDecodeBounds = true;\n is = resolver.openInputStream(uri);\n BitmapFactory.decodeStream(is, null, options);\n int width = options.outWidth;\n int height = options.outHeight;\n return new Point(width, height);\n } catch (FileNotFoundException e) {\n return new Point(0, 0);\n } finally {\n CloseableUtils.close(is);\n }\n }\n\n public static String getPath(ContentResolver resolver, Uri uri) {\n if (uri == null) {\n return null;\n }\n\n if (SCHEME_CONTENT.equals(uri.getScheme())) {\n Cursor cursor = null;\n try {\n cursor = resolver.query(uri, new String[] { MediaStore.Images.ImageColumns.DATA }, null, null, null);\n if (cursor == null || !cursor.moveToFirst()) {\n return null;\n }\n return cursor.getString(cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA));\n } finally {\n CursorUtils.close(cursor);\n }\n }\n return uri.getPath();\n }\n\n public static boolean shouldRotate(ContentResolver resolver, Uri uri) {\n ExifInterface exif;\n try {\n exif = ExifInterfaceCompat.newInstance(getPath(resolver, uri));\n } catch (IOException e) {\n Log.e(TAG, \"could not read exif info of the image: \" + uri);\n return false;\n }\n int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, -1);\n return orientation == ExifInterface.ORIENTATION_ROTATE_90\n || orientation == ExifInterface.ORIENTATION_ROTATE_270;\n }\n\n public static Point getViewBitmapBound(ContentResolver resolver, Uri uri) {\n Point imageSize = getRawBitmapBound(resolver, uri);\n int w = imageSize.x;\n int h = imageSize.y;\n if (shouldRotate(resolver, uri)) {\n w = imageSize.y;\n h = imageSize.x;\n }\n int width = w > MAX_WIDTH_ON_VIEW ? MAX_WIDTH_ON_VIEW : w;\n int height = (int) Math.floor(h * width / width);\n return new Point(width, height);\n }\n}",
"public final class EventBusUtils {\n private EventBusUtils() {\n throw new AssertionError();\n }\n\n public static void postOnMainThread(final Bus bus, final Object event) {\n HandlerUtils.postOnMain(new Runnable() {\n @Override\n public void run() {\n bus.post(event);\n }\n });\n }\n\n public static void postOnMainThreadWithDelay(final Bus bus, final Object event, long delayInMillis) {\n HandlerUtils.postOnMainWithDelay(new Runnable() {\n @Override\n public void run() {\n bus.post(event);\n }\n }, delayInMillis);\n }\n}",
"public abstract class AbstractModel {\n private Context mContext;\n\n public AbstractModel(Context context) {\n mContext = context;\n }\n\n protected Context getContext() {\n return mContext;\n }\n\n protected LoaderManager getLoaderManager() {\n return ((Activity) mContext).getLoaderManager();\n }\n\n protected ContentResolver getContentResolver() {\n return mContext.getContentResolver();\n }\n}"
] | import android.app.LoaderManager;
import android.content.Context;
import android.content.Loader;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.net.Uri;
import android.os.Bundle;
import com.amalgam.os.BundleUtils;
import com.anprosit.android.dagger.annotation.ForActivity;
import com.anprosit.android.dagger.utils.ObjectGraphUtils;
import com.squareup.otto.Bus;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.inject.Inject;
import jp.yokomark.lgtm.app.compose.entity.ComposeData;
import jp.yokomark.lgtm.app.compose.event.SaveSuccessEvent;
import jp.yokomark.lgtm.media.loader.SaveImageTask;
import jp.yokomark.lgtm.media.utils.ImageUtils;
import jp.yokomark.lgtm.misc.event.EventBusUtils;
import jp.yokomark.lgtm.misc.model.AbstractModel; | package jp.yokomark.lgtm.app.compose.model;
/**
* @author yokomakukeishin
* @version 1.0.0
* @since 1.0.0
*/
public class ComposeStateHolder extends AbstractModel implements LoaderManager.LoaderCallbacks<Uri> {
public static final String TAG = ComposeStateHolder.class.getSimpleName();
private static final int LOADER_ID = 1;
private static final String ARGS_BITMAP = BundleUtils.buildKey(ComposeStateHolder.class, "ARGS_BITMAP");
private static final String STATE_DATA = BundleUtils.buildKey(ComposeStateHolder.class, "STATE_DATA");
private static final String STATE_VIEW_DIM = BundleUtils.buildKey(ComposeStateHolder.class, "STATE_VIEW_DIM");
private static final String STATE_X_SCALE = BundleUtils.buildKey(ComposeStateHolder.class, "STATE_X_SCALE");
private static final String STATE_Y_SCALE = BundleUtils.buildKey(ComposeStateHolder.class, "STATE_Y_SCALE");
private ComposeData mData;
private Point mViewDimension;
private float mXScaleFactor;
private float mYScaleFactor;
@Inject Bus mBus;
@Inject
public ComposeStateHolder(@ForActivity Context context) {
super(context);
ObjectGraphUtils.getObjectGraph(context).inject(this);
}
@Override
public Loader<Uri> onCreateLoader(int id, Bundle args) {
Bitmap bitmap = args.getParcelable(ARGS_BITMAP); | return new SaveImageTask(getContext(), bitmap); | 2 |
PaulNoth/saral | src/main/java/com/pidanic/saral/domain/ArrayDeclaration.java | [
"public abstract class Expression {\n private Type type;\n\n public Expression(Type type) {\n this.type = type;\n }\n\n public Type type() {\n return type;\n }\n\n public abstract void accept(ExpressionGenerator generator);\n}",
"public class CastExpression extends UnaryExpression {\n public CastExpression(Type castingType, Expression expression) {\n super(castingType, getSign(castingType, expression.type()), expression);\n }\n @Override\n public void accept(ExpressionGenerator generator) {\n generator.generate(this);\n }\n\n private static CastingSign getSign(Type castingType, Type expressionType) {\n if(castingType == BuiltInType.DOUBLE) {\n return CastingSign.LONG_TO_DOUBLE;\n }\n if(castingType == BuiltInType.INT) {\n return CastingSign.LONG_TO_INT;\n }\n return CastingSign.LONG_TO_DOUBLE;\n }\n}",
"public class SimpleStatementGenerator extends StatementGenerator {\n\n private static final int NULL_CHAR = '\\0';\n\n private interface BooleanByteValue {\n void putOnStack();\n }\n\n private MethodVisitor methodVisitor;\n private Scope scope;\n private ExpressionGenerator expressionGenerator;\n\n public SimpleStatementGenerator(MethodVisitor methodVisitor, Scope scope) {\n super();\n this.methodVisitor = methodVisitor;\n this.scope = scope;\n this.expressionGenerator = new ExpressionGenerator(methodVisitor, scope);\n }\n\n public void generate(PrintStatement instruction) {\n final LocalVariable variable = instruction.getVariable();\n if (!variable.isInitialized()) {\n throw new VariableNotInitialized(scope, variable.name());\n }\n final Type type = variable.type();\n final int variableId = scope.getLocalVariableIndex(variable.name());\n methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, \"java/lang/System\", \"out\", \"Ljava/io/PrintStream;\");\n String descriptor = createPrintlnDescriptor(type);\n if (variable instanceof LocalVariableArrayIndex) {\n methodVisitor.visitVarInsn(Opcodes.ALOAD, variableId);\n LocalVariableArrayIndex localArrayIndex = (LocalVariableArrayIndex) variable;\n Expression index = localArrayIndex.getIndex();\n index.accept(expressionGenerator);\n if (type == BuiltInType.STRING) {\n descriptor = \"(C)V\";\n // duplicate index and reference\n index.accept(expressionGenerator);\n methodVisitor.visitVarInsn(Opcodes.ALOAD, variableId);\n methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, \"java/lang/String\", \"length\", \"()I\", false);\n\n Label trueLabel = new Label();\n Label endLabel = new Label();\n methodVisitor.visitJumpInsn(Opcodes.IF_ICMPLT, trueLabel);\n\n // throw away index\n methodVisitor.visitInsn(Opcodes.POP);\n // throw away reference\n methodVisitor.visitInsn(Opcodes.POP);\n methodVisitor.visitIntInsn(Opcodes.BIPUSH, NULL_CHAR);\n\n methodVisitor.visitJumpInsn(Opcodes.GOTO, endLabel);\n methodVisitor.visitLabel(trueLabel);\n // true label\n methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, \"java/lang/String\", \"charAt\", \"(I)C\", false);\n methodVisitor.visitLabel(endLabel);\n } else {\n methodVisitor.visitInsn(type.getTypeSpecificOpcode().getLoad());\n if (type == BuiltInType.BOOLEAN_ARR) {\n generateBooleanAsKleene(() -> {\n methodVisitor.visitVarInsn(Opcodes.ALOAD, variableId);\n index.accept(expressionGenerator);\n methodVisitor.visitInsn(type.getTypeSpecificOpcode().getLoad());\n });\n }\n }\n } else {\n methodVisitor.visitVarInsn(type.getTypeSpecificOpcode().getLoad(), variableId);\n if (type == BuiltInType.BOOLEAN) {\n generateBooleanAsKleene(() -> methodVisitor.visitVarInsn(type.getTypeSpecificOpcode().getLoad(), variableId));\n\n }\n }\n methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL,\n \"java/io/PrintStream\", \"println\", descriptor, false);\n }\n\n public void generate(ReadStatement readStatement) {\n if (!scope.existsLocalVariable(LocalVariable.SYSTEM_IN)) {\n initializeSystemIn();\n }\n int systemInIndex = scope.getLocalVariableIndex(LocalVariable.SYSTEM_IN);\n\n final LocalVariable variable = readStatement.variable();\n if (!variable.isInitialized()) {\n throw new VariableNotInitialized(scope, variable.name());\n }\n if (variable.isConstant()) {\n throw new ConstantAssignmentNotAllowed(scope, variable.name());\n }\n final Type variableType = variable.type();\n final int variableId = scope.getLocalVariableIndex(variable.name());\n\n if (variable instanceof LocalVariableArrayIndex) {\n\n if (variableType == BuiltInType.BOOLEAN_ARR) {\n String tempVarName = \"booleanTemp\" + scope.localVariablesCount();\n scope.addLocalVariable(new LocalVariable(tempVarName, BuiltInType.BOOLEAN, true));\n\n int booleanTempIndex = scope.getLocalVariableIndex(tempVarName);\n\n methodVisitor.visitVarInsn(Opcodes.ALOAD, systemInIndex);\n methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, \"java/util/Scanner\",\n getScannerMethod(variableType), getScannerMethodReturnDescriptor(variableType), false);\n\n Label endLabel = new Label();\n Label pravdaLabel = new Label();\n Label osalLabel = new Label();\n Label skoroosalLabel = new Label();\n\n methodVisitor.visitInsn(Opcodes.DUP);\n\n methodVisitor.visitLdcInsn(Logic.PRAVDA.getStringValue());\n methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, \"java/lang/String\", \"compareTo\", \"(Ljava/lang/String;)I\", false);\n methodVisitor.visitJumpInsn(Opcodes.IFNE, skoroosalLabel);\n methodVisitor.visitIntInsn(Opcodes.BIPUSH, Logic.PRAVDA.getIntValue());\n methodVisitor.visitJumpInsn(Opcodes.GOTO, endLabel);\n\n methodVisitor.visitLabel(skoroosalLabel);\n methodVisitor.visitInsn(Opcodes.DUP);\n methodVisitor.visitLdcInsn(Logic.SKOROOSAL.getStringValue());\n methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, \"java/lang/String\", \"compareTo\", \"(Ljava/lang/String;)I\", false);\n\n methodVisitor.visitJumpInsn(Opcodes.IFNE, osalLabel);\n methodVisitor.visitIntInsn(Opcodes.BIPUSH, Logic.SKOROOSAL.getIntValue());\n methodVisitor.visitJumpInsn(Opcodes.GOTO, endLabel);\n\n methodVisitor.visitLabel(osalLabel);\n methodVisitor.visitIntInsn(Opcodes.BIPUSH, Logic.OSAL.getIntValue());\n\n methodVisitor.visitLabel(endLabel);\n\n methodVisitor.visitVarInsn(Opcodes.ISTORE, booleanTempIndex);\n\n methodVisitor.visitVarInsn(Opcodes.ALOAD, variableId);\n LocalVariableArrayIndex localArrayIndex = (LocalVariableArrayIndex) variable;\n\n Expression index = localArrayIndex.getIndex();\n index.accept(expressionGenerator);\n\n methodVisitor.visitVarInsn(Opcodes.ILOAD, booleanTempIndex);\n } else {\n methodVisitor.visitVarInsn(Opcodes.ALOAD, variableId);\n LocalVariableArrayIndex localArrayIndex = (LocalVariableArrayIndex) variable;\n\n Expression index = localArrayIndex.getIndex();\n index.accept(expressionGenerator);\n\n methodVisitor.visitVarInsn(Opcodes.ALOAD, systemInIndex);\n methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, \"java/util/Scanner\",\n getScannerMethod(variableType), getScannerMethodReturnDescriptor(variableType), false);\n\n if (variableType == BuiltInType.CHAR_ARR) {\n methodVisitor.visitInsn(Opcodes.ICONST_0);\n methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, \"java/lang/String\", \"charAt\", \"(I)C\", false);\n }\n }\n\n methodVisitor.visitInsn(variableType.getTypeSpecificOpcode().getStore());\n } else {\n methodVisitor.visitVarInsn(Opcodes.ALOAD, systemInIndex);\n methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, \"java/util/Scanner\",\n getScannerMethod(variableType), getScannerMethodReturnDescriptor(variableType), false);\n\n if (TypeResolver.isBoolean(variableType)) {\n Label endLabel = new Label();\n Label pravdaLabel = new Label();\n Label osalLabel = new Label();\n Label skoroosalLabel = new Label();\n\n methodVisitor.visitInsn(Opcodes.DUP);\n\n methodVisitor.visitLdcInsn(Logic.PRAVDA.getStringValue());\n methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, \"java/lang/String\", \"compareTo\", \"(Ljava/lang/String;)I\", false);\n methodVisitor.visitJumpInsn(Opcodes.IFNE, skoroosalLabel);\n methodVisitor.visitIntInsn(Opcodes.BIPUSH, Logic.PRAVDA.getIntValue());\n methodVisitor.visitJumpInsn(Opcodes.GOTO, endLabel);\n\n methodVisitor.visitLabel(skoroosalLabel);\n methodVisitor.visitInsn(Opcodes.DUP);\n methodVisitor.visitLdcInsn(Logic.SKOROOSAL.getStringValue());\n methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, \"java/lang/String\", \"compareTo\", \"(Ljava/lang/String;)I\", false);\n\n methodVisitor.visitJumpInsn(Opcodes.IFNE, osalLabel);\n methodVisitor.visitIntInsn(Opcodes.BIPUSH, Logic.SKOROOSAL.getIntValue());\n methodVisitor.visitJumpInsn(Opcodes.GOTO, endLabel);\n\n methodVisitor.visitLabel(osalLabel);\n methodVisitor.visitIntInsn(Opcodes.BIPUSH, Logic.OSAL.getIntValue());\n\n methodVisitor.visitLabel(endLabel);\n }\n if (TypeResolver.isChar(variableType)) {\n methodVisitor.visitInsn(Opcodes.ICONST_0);\n methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, \"java/lang/String\", \"charAt\", \"(I)C\", false);\n }\n methodVisitor.visitVarInsn(variableType.getTypeSpecificOpcode().getStore(), variableId);\n }\n }\n\n private void initializeSystemIn() {\n LocalVariable scanner = new LocalVariable(LocalVariable.SYSTEM_IN, BuiltInType.STRING, true);\n scope.addLocalVariable(scanner);\n\n int systemInIndex = scope.getLocalVariableIndex(LocalVariable.SYSTEM_IN);\n methodVisitor.visitTypeInsn(Opcodes.NEW, \"java/util/Scanner\");\n\n methodVisitor.visitVarInsn(Opcodes.ASTORE, systemInIndex);\n\n methodVisitor.visitVarInsn(Opcodes.ALOAD, systemInIndex);\n methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, \"java/lang/System\", \"in\", \"Ljava/io/InputStream;\");\n methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, \"java/util/Scanner\", \"<init>\", \"(Ljava/io/InputStream;)V\", false);\n }\n\n private String getScannerMethod(Type variableType) {\n if (variableType == BuiltInType.LONG || variableType == BuiltInType.LONG_ARR) {\n return \"nextLong\";\n }\n if (variableType == BuiltInType.DOUBLE || variableType == BuiltInType.DOUBLE_ARR) {\n return \"nextDouble\";\n }\n return \"next\";\n }\n\n private String getScannerMethodReturnDescriptor(Type variableType) {\n if (variableType == BuiltInType.LONG || variableType == BuiltInType.LONG_ARR) {\n return \"()\" + BuiltInType.LONG.getDescriptor();\n }\n if (variableType == BuiltInType.DOUBLE || variableType == BuiltInType.DOUBLE_ARR) {\n return \"()\" + BuiltInType.DOUBLE.getDescriptor();\n }\n return \"()\" + BuiltInType.STRING.getDescriptor();\n }\n\n private String createPrintlnDescriptor(Type type) {\n String descriptor = \"(\" + type.getDescriptor() + \")V\";\n if (type == BuiltInType.BOOLEAN) {\n descriptor = \"(\" + BuiltInType.STRING.getDescriptor() + \")V\";\n } else if (type == BuiltInType.BOOLEAN_ARR) {\n descriptor = \"(\" + BuiltInType.STRING.getDescriptor() + \")V\";\n } else if (type == BuiltInType.LONG_ARR) {\n descriptor = \"(\" + BuiltInType.LONG.getDescriptor() + \")V\";\n } else if (type == BuiltInType.DOUBLE_ARR) {\n descriptor = \"(\" + BuiltInType.DOUBLE.getDescriptor() + \")V\";\n } else if (type == BuiltInType.CHAR_ARR) {\n descriptor = \"(\" + BuiltInType.CHAR.getDescriptor() + \")V\";\n } else if (type == BuiltInType.STRING_ARR) {\n descriptor = \"(\" + BuiltInType.STRING.getDescriptor() + \")V\";\n }\n return descriptor;\n }\n\n private void generateBooleanAsKleene(BooleanByteValue valueOnStack) {\n Label endLabel = new Label();\n Label pravdaLabel = new Label();\n Label osalLabel = new Label();\n Label skoroosalLabel = new Label();\n\n methodVisitor.visitIntInsn(Opcodes.BIPUSH, Logic.PRAVDA.getIntValue());\n methodVisitor.visitJumpInsn(Opcodes.IF_ICMPNE, osalLabel);\n methodVisitor.visitLdcInsn(Logic.PRAVDA.getStringValue());\n methodVisitor.visitJumpInsn(Opcodes.GOTO, endLabel);\n methodVisitor.visitLabel(osalLabel);\n\n // comparing value of the left expression if \"false\"\n valueOnStack.putOnStack();\n methodVisitor.visitIntInsn(Opcodes.BIPUSH, Logic.OSAL.getIntValue());\n methodVisitor.visitJumpInsn(Opcodes.IF_ICMPNE, skoroosalLabel);\n methodVisitor.visitLdcInsn(Logic.OSAL.getStringValue());\n methodVisitor.visitJumpInsn(Opcodes.GOTO, endLabel);\n\n methodVisitor.visitLabel(skoroosalLabel);\n methodVisitor.visitLdcInsn(Logic.SKOROOSAL.getStringValue());\n\n methodVisitor.visitLabel(endLabel);\n }\n\n public void generate(VariableDeclaration variableDeclaration) {\n final String variableName = variableDeclaration.getName();\n final int variableId = scope.getLocalVariableIndex(variableName);\n final Optional<LocalVariable> var = scope.getLocalVariable(variableName);\n if(!var.isPresent()) {\n throw new VariableNotFound(scope, variableName);\n }\n final Optional<Expression> expressionOption = variableDeclaration.getExpression();\n if (expressionOption.isPresent()) {\n Expression expression = expressionOption.get();\n expression.accept(expressionGenerator);\n methodVisitor.visitVarInsn(var.get().type().getTypeSpecificOpcode().getStore(), variableId);\n }\n }\n\n public void generate(ProcedureCall functionCall) {\n List<Argument> parameters = functionCall.getFunction().getArguments();\n List<CalledArgument> calledParameter = functionCall.getCalledArguments();\n for (int i = 0; i < parameters.size(); i++) {\n Argument param = parameters.get(i);\n CalledArgument callArg = calledParameter.get(i);\n String realLocalVariableName = callArg.getName();\n param.accept(this, realLocalVariableName);\n }\n //Type owner = functionCall.getFunction().getReturnType().orElse(new ClassType(scope.getClassName()));\n Type owner = new ClassType(scope.getClassName());\n String ownerDescription = owner.getInternalName();\n String functionName = functionCall.getFunction().getName();\n String methodDescriptor = getFunctionDescriptor(functionCall);\n methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, ownerDescription, functionName, methodDescriptor, false);\n }\n\n public void generate(Argument parameter, String localVariableName) {\n Type argumentType = parameter.getType();\n int index = scope.getLocalVariableIndex(localVariableName);\n if (TypeResolver.isArray(argumentType)) {\n methodVisitor.visitVarInsn(Opcodes.ALOAD, index);\n } else {\n methodVisitor.visitVarInsn(argumentType.getTypeSpecificOpcode().getLoad(), index);\n }\n }\n\n private String getFunctionDescriptor(ProcedureCall functionCall) {\n return Optional.of(getDescriptorForFunctionInScope(functionCall))\n .orElse(getDescriptorForFunctionOnClasspath(functionCall))\n .orElseThrow(() -> new FunctionCallNotFound(functionCall));\n }\n\n private Optional<String> getDescriptorForFunctionInScope(ProcedureCall functionCall) {\n return Optional.ofNullable(DescriptorFactory.getMethodDescriptor(functionCall.getFunction()));\n }\n\n private Optional<String> getDescriptorForFunctionOnClasspath(ProcedureCall functionCall) {\n try {\n String functionName = functionCall.getFunction().getName();\n Collection<CalledArgument> parameters = functionCall.getCalledArguments();\n Type owner = functionCall.getFunction().getReturnType();\n //String className = owner.isPresent() ? owner.get().name() : scope.getClassName();\n String className = scope.getClassName();\n Class<?> aClass = Class.forName(className);\n Method method = aClass.getMethod(functionName);\n String methodDescriptor = org.objectweb.asm.Type.getMethodDescriptor(method);\n return Optional.of(methodDescriptor);\n } catch (ReflectiveOperationException e) {\n return Optional.empty();\n }\n }\n\n public void generate(Assignment assignment) {\n final String variableName = assignment.getName();\n final int variableId = scope.getLocalVariableIndex(variableName);\n final Optional<Expression> expressionOption = assignment.getExpression();\n if (expressionOption.isPresent()) {\n Expression expression = expressionOption.get();\n if (assignment instanceof ArrayAssignment) {\n Optional<LocalVariable> localArrayOption = scope.getLocalVariable(variableName);\n if (!localArrayOption.isPresent()) {\n throw new VariableNotFound(scope, variableName);\n }\n LocalVariable localArray = localArrayOption.get();\n if (TypeResolver.isString(localArray.type())) {\n this.generateStringFromConcatenatedSubstrings(assignment, expression, variableId);\n } else {\n methodVisitor.visitVarInsn(Opcodes.ALOAD, variableId);\n\n ((ArrayAssignment) assignment).getIndex().accept(expressionGenerator);\n expression.accept(expressionGenerator);\n\n methodVisitor.visitInsn(localArray.type().getTypeSpecificOpcode().getStore());\n }\n } else {\n expression.accept(expressionGenerator);\n final Type type = expression.type();\n methodVisitor.visitVarInsn(type.getTypeSpecificOpcode().getStore(), variableId);\n }\n }\n }\n\n /**\n * create new string based on string.substring(0, index) + char + string.substring(index + 1, string.length)\n */\n private void generateStringFromConcatenatedSubstrings(Assignment arrayAssignment, Expression expression, int variableId) {\n // add substring parameters 0, index value\n methodVisitor.visitVarInsn(BuiltInType.STRING.getTypeSpecificOpcode().getLoad(), variableId);\n\n methodVisitor.visitInsn(Opcodes.ICONST_0);\n ((ArrayAssignment) arrayAssignment).getIndex().accept(expressionGenerator);\n methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, \"java/lang/String\", \"substring\", \"(II)Ljava/lang/String;\", false);\n\n // add char and convert it to string\n expression.accept(expressionGenerator);\n methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, \"java/lang/String\", \"valueOf\", \"(C)Ljava/lang/String;\", false);\n\n // concat char with first substring\n methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, \"java/lang/String\", \"concat\", \"(Ljava/lang/String;)Ljava/lang/String;\", false);\n\n // add substring parameters index + 1, string.length value\n methodVisitor.visitVarInsn(BuiltInType.STRING.getTypeSpecificOpcode().getLoad(), variableId);\n\n ((ArrayAssignment) arrayAssignment).getIndex().accept(expressionGenerator);\n methodVisitor.visitInsn(Opcodes.ICONST_1);\n methodVisitor.visitInsn(Opcodes.IADD);\n methodVisitor.visitVarInsn(BuiltInType.STRING.getTypeSpecificOpcode().getLoad(), variableId);\n methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, \"java/lang/String\", \"length\", \"()I\", false);\n\n methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, \"java/lang/String\", \"substring\", \"(II)Ljava/lang/String;\", false);\n\n //concat concated string with above substring\n methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, \"java/lang/String\", \"concat\", \"(Ljava/lang/String;)Ljava/lang/String;\", false);\n\n // store it into var\n methodVisitor.visitVarInsn(Opcodes.ASTORE, variableId);\n }\n\n public void generate(ArrayDeclaration array) {\n Type arrayType = array.getType();\n Expression arrayLength = array.getLength();\n arrayLength.accept(expressionGenerator);\n if(arrayType == BuiltInType.STRING_ARR) {\n methodVisitor.visitTypeInsn(arrayType.getTypeSpecificOpcode().getNew(), \"java/lang/String\");\n } else {\n methodVisitor.visitIntInsn(arrayType.getTypeSpecificOpcode().getNew(), arrayType.getTypeSpecificOpcode().getAsmType());\n }\n String name = array.getName();\n int variableIndex = scope.getLocalVariableIndex(name);\n methodVisitor.visitVarInsn(Opcodes.ASTORE, variableIndex);\n }\n}",
"public class StatementGenerator {\n}",
"public enum BuiltInType implements Type {\n BOOLEAN(\"logický\", boolean.class, \"Z\", TypeSpecificOpcodes.INT),\n INT (\"neskutočné numeralio int\", int.class, \"I\", TypeSpecificOpcodes.INT),\n CHAR (\"písmeno\", char.class, \"C\", TypeSpecificOpcodes.INT),\n //BYTE (\"neskutočné numeralio\", byte.class, \"B\", TypeSpecificOpcodes.INT),\n //SHORT (\"neskutočné numeralio\", short.class, \"S\", TypeSpecificOpcodes.INT),\n LONG (\"neskutočné numeralio\", long.class, \"J\", TypeSpecificOpcodes.LONG),\n //FLOAT (\"skutočné numeralio\", float.class, \"F\", TypeSpecificOpcodes.FLOAT),\n DOUBLE (\"skutočné numeralio\", double.class, \"D\", TypeSpecificOpcodes.DOUBLE),\n STRING (\"slovo\", String.class, \"Ljava/lang/String;\", TypeSpecificOpcodes.OBJECT),\n BOOLEAN_ARR(\"funduš logický\", boolean[].class, \"[B\", TypeSpecificOpcodes.BOOLEAN_ARRAY),\n //INT_ARR (\"int[]\", int[].class, \"[I\"),\n CHAR_ARR (\"funduš písmeno\", char[].class, \"[C\", TypeSpecificOpcodes.CHAR_ARRAY),\n //BYTE_ARR (\"byte[]\", byte[].class, \"[B\"),\n //SHORT_ARR (\"short[]\", short[].class, \"[S\"),\n LONG_ARR (\"funduš neskutočné numeralio\", long[].class, \"[J\", TypeSpecificOpcodes.LONG_ARRAY),\n //FLOAT_ARR (\"float[]\", float[].class, \"[F\"),\n DOUBLE_ARR (\"funduš skutočné numeralio\", double[].class, \"[D\", TypeSpecificOpcodes.DOUBLE_ARRAY),\n STRING_ARR (\"funduš slovo\", String[].class, \"[Ljava/lang/String;\", TypeSpecificOpcodes.OBJECT_ARRAY),\n //NONE(\"\", null,\"\"),\n VOID(\"void\", void.class, \"V\", TypeSpecificOpcodes.VOID);\n\n private String name;\n private Class<?> typeClass;\n private String descriptor;\n private TypeSpecificOpcodes opCode;\n\n BuiltInType(String name, Class<?> typeClass, String descriptor, TypeSpecificOpcodes op) {\n this.name = name;\n this.typeClass = typeClass;\n this.descriptor = descriptor;\n this.opCode = op;\n }\n\n @Override\n public String getName() {\n return name;\n }\n\n @Override\n public Class<?> getTypeClass() {\n return typeClass;\n }\n\n @Override\n public String getDescriptor() {\n return descriptor;\n }\n\n @Override\n public String getInternalName() {\n return getDescriptor();\n }\n\n @Override\n public TypeSpecificOpcodes getTypeSpecificOpcode() {\n return opCode;\n }\n}",
"public interface Type {\n String getName();\n Class<?> getTypeClass();\n String getDescriptor();\n String getInternalName();\n TypeSpecificOpcodes getTypeSpecificOpcode();\n}"
] | import com.pidanic.saral.domain.expression.Expression;
import com.pidanic.saral.domain.expression.cast.CastExpression;;
import com.pidanic.saral.generator.SimpleStatementGenerator;
import com.pidanic.saral.generator.StatementGenerator;
import com.pidanic.saral.util.BuiltInType;
import com.pidanic.saral.util.Type; | package com.pidanic.saral.domain;
public class ArrayDeclaration implements SimpleStatement {
private Type type; | private Expression length; | 0 |
VisualDataWeb/OWL2VOWL | src/main/java/de/uni_stuttgart/vis/vowl/owl2vowl/Owl2Vowl.java | [
"public interface Converter {\n\tString getLoadingInfoString();\n\tvoid setOntologyHasMissingImports(boolean val);\n\tboolean ontologyHasMissingImports();\n\tvoid addLoadingInfo(String msg);\n\tboolean getCurrentlyLoadingFlag();\n\tvoid setCurrentlyLoadingFlag(boolean val);\n\tvoid setCurrentlyLoadingFlag(String parentLine,boolean val);\n\tvoid addLoadingInfoToParentLine(String msg);\n\tvoid clearLoadingMsg();\n\tvoid convert();\n\tvoid releaseMemory();\n\n\tvoid export(Exporter exporter) throws Exception;\n}",
"public class IRIConverter extends AbstractConverter {\n\tprotected IRI mainOntology;\n\tprotected Collection<IRI> depdencyOntologies;\n\tprivate static final Logger logger = LogManager.getLogger(IRIConverter.class);\n\n\tpublic IRIConverter(IRI ontologyIRI) {\n\t\tthis(ontologyIRI, Collections.<IRI>emptyList());\n\t}\n\n\tpublic IRIConverter(IRI ontologyIRI, Collection<IRI> necessaryExternals) {\n\t\tmainOntology = ontologyIRI;\n\t\tdepdencyOntologies = Collections.unmodifiableCollection(necessaryExternals);\n\t}\n\n\t@Override\n\tprotected void loadOntology() throws OWLOntologyCreationException {\n\t\tlogger.info(\"Converting IRIs...\");\n\t\t\n\t\tlogger.info(\"Loading ontologies ... [\" + mainOntology + \", \" + depdencyOntologies + \"]\");\n\t\tthis.setOntologyHasMissingImports(false);\n\t\tmanager = OWLManager.createOWLOntologyManager();\n\n\t\tif (!depdencyOntologies.isEmpty()) {\n\t\t\tfor (IRI externalIRI : depdencyOntologies) {\n\t\t\t\tmanager.loadOntology(externalIRI);\n\t\t\t}\n\t\t\tlogger.info(\"External ontologies loaded!\");\n\t\t}\n\t\t\n\t\n\t\ttry {\n\t\t\tthis.addLoadingInfo(\"* Parsing ontology with OWL API \");\n\t\t\tthis.setCurrentlyLoadingFlag(\"* Parsing ontology with OWL API \",true);\n\t\t\tmissingListener=new OWLAPI_MissingImportsListener(this);\n\t\t\tmanager.addMissingImportListener(missingListener);\n\t\t\tmanager.getOntologyConfigurator().setMissingImportHandlingStrategy(MissingImportHandlingStrategy.SILENT);\n\t\t\tmanager.getOntologyConfigurator().setFollowRedirects(true);\n\t\t\tmanager.getOntologyConfigurator().setConnectionTimeout(100000);\n\n\t\t\tmanager.getOntologyConfigurator().setAcceptingHTTPCompression(true);\n\t\t\tmanager.getOntologyConfigurator().withRepairIllegalPunnings(false);\n\t\t\t\n\t\t\tontology = manager.loadOntology(mainOntology);\n\t\t\t\n\t\t\t\n\t\t\tthis.addLoadingInfoToParentLine(\"... done \" );\n\t\t\tthis.setCurrentlyLoadingFlag(false);\n\t\t\tif (this.ontologyHasMissingImports()==true) {\n\t\t\t\tthis.addLoadingInfoToLine(\"* Parsing ontology with OWL API \",\"<span style='color:yellow;'>(with warnings)</span>\" );\n\t\t\t}\n\t\t\n\t\t} catch (Exception e ) {\n\t\t\tthis.addLoadingInfoToLine(\"* Parsing ontology with OWL API \",\"... <span style='color:red;'>failed</span>\" );\n\t\t\tthis.setCurrentlyLoadingFlag(false);\n\t\t\tthis.addLoadingInfo(\"\\n <span style='color:red;'>Loading process failed:</span> \\n\"+msgForWebVOWL(e.getMessage()));\n\t\t\tlogger.info(this.getLoadingInfoString());\n\t\t}\n\t\t\n\t\tloadedOntologyPath = mainOntology.toString();\n\n\t\tString logOntoName;\n\t\tif (!ontology.isAnonymous()) {\n\t\t\tlogOntoName = ontology.getOntologyID().getOntologyIRI().get().toString();\n\t\t} else {\n\t\t\tlogOntoName = mainOntology.toString();\n\t\t\tlogger.info(\"Ontology IRI is anonymous. Use loaded URI/IRI instead.\");\n\t\t}\n\t\tlogger.info(\"Ontologies loaded! Main Ontology: \" + logOntoName);\n\t}\n}",
"public class InputStreamConverter extends AbstractConverter {\n\tprotected InputStream mainOntology;\n\tprotected Collection<InputStream> depdencyOntologies;\n\tprivate static final Logger logger = LogManager.getLogger(InputStreamConverter.class);\n\tpublic boolean ontologyHasMissingImports() {\n\t\treturn missingImports;\n\t}\n\tpublic void setOntologyHasMissingImports(boolean val) {\n\t\tmissingImports=val;\n\t}\n\t\n\tpublic InputStreamConverter(InputStream ontology) {\n\t\tthis(ontology, Collections.emptyList());\n\t}\n\n\tpublic InputStreamConverter(InputStream ontology, Collection<InputStream> necessaryExternals) {\n\t\tmainOntology = ontology;\n\t\tdepdencyOntologies = Collections.unmodifiableCollection(necessaryExternals);\n\t}\n\n\t\n\t@Override\n\tprotected void loadOntology() throws OWLOntologyCreationException {\n\t\tlogger.info(\"Converting input streams...\");\n\t\tthis.setOntologyHasMissingImports(false);\n\t\tmanager = OWLManager.createOWLOntologyManager();\n\n\t\tfor (InputStream depdencyOntology : depdencyOntologies) {\n\t\t\tmanager.loadOntologyFromOntologyDocument(depdencyOntology);\n\t\t}\n\t\tString CharEncoding=\"UTF-8\";\n\t\tString copiedOntologyContent=\"\";\n\t\ttry {\n\t\t\tcopiedOntologyContent = IOUtils.toString(mainOntology, CharEncoding);\n\t\t} catch (IOException e1) {\n\t\t\te1.printStackTrace();\n\t\t\t\n\t\t}\n\t\t// need a workaround with copied string since the input stream is flushed on reading ... \n\t\ttry {\n\t\t\tthis.addLoadingInfo(\"* Parsing ontology with OWL API \");\n\t\t\tthis.setCurrentlyLoadingFlag(\"* Parsing ontology with OWL API \",true);\n\t\t\tInputStream copyOfInputBuffer = new ByteArrayInputStream(copiedOntologyContent.getBytes(CharEncoding));\n\t\t\tmissingListener=new OWLAPI_MissingImportsListener(this);\n\t\t\tmanager.addMissingImportListener(missingListener);\n\t\t\tmanager.getOntologyConfigurator().setMissingImportHandlingStrategy(MissingImportHandlingStrategy.SILENT);\n\t\t\tontology = manager.loadOntologyFromOntologyDocument(copyOfInputBuffer);\n\t\t\tthis.addLoadingInfoToParentLine(\"... done \" );\n\t\t\tthis.setCurrentlyLoadingFlag(false);\n\t\t\t\n\t\t\tif (this.ontologyHasMissingImports()==true) {\n\t\t\t\tthis.addLoadingInfoToLine(\"* Parsing ontology with OWL API \",\"<span style='color:yellow;'>(with warnings)</span>\" );\n\t\t\t}\n\t\t\tcopyOfInputBuffer=null;\n\t\t} catch (Exception e ) {\n\t\t\tthis.setCurrentlyLoadingFlag(false);\n\t\t\tthis.addLoadingInfoToLine(\"* Parsing ontology with OWL API \",\"... <span style='color:red;'>failed</span>\" );\n\t\t\tthis.addLoadingInfo(\"\\n <span style='color:red;'>Loading process failed:</span> \\n\"+msgForWebVOWL(e.getMessage()));\n\t\t}\n\t\t\n\t\tloadedOntologyPath = \"file upload\";\n\t\tcopiedOntologyContent=\"\";\n\t\tString logOntoName;\n\t\tif (!ontology.isAnonymous()) {\n\t\t\tlogOntoName = ontology.getOntologyID().getOntologyIRI().get().toString();\n\t\t} else {\n\t\t\tlogOntoName = \"Anonymous\";\n\t\t\tlogger.info(\"Ontology IRI is anonymous. Use loaded URI/IRI instead.\");\n\t\t}\n\t\tlogger.info(\"Ontologies loaded! Main Ontology: \" + logOntoName);\n\t}\n}",
"public class OntologyConverter extends AbstractConverter {\n\tprivate static final Logger logger = LogManager.getLogger(OntologyConverter.class);\n\n\tpublic OntologyConverter(OWLOntology ontology) {\n\t\tthis.ontology = ontology;\n\t}\n\n\tpublic OntologyConverter(OWLOntology ontology, String ontologyIRI) {\n\t\tthis(ontology);\n\t\tloadedOntologyPath = ontologyIRI;\n\t}\n\n\t@Override\n\tprotected void loadOntology() throws OWLOntologyCreationException {\n\t\tlogger.info(\"Converting Ontolgy...\");\n\t\tlogger.info(\"Loading ontology ... [\" + ontology + \"]\");\n\n\t\tmanager = ontology.getOWLOntologyManager();\n\t\tloadedOntologyPath = \"Direct ontology\";\n\n\t\tString logOntoName;\n\t\tif (!ontology.isAnonymous()) {\n\t\t\tlogOntoName = ontology.getOntologyID().getOntologyIRI().get().toString();\n\t\t} else {\n\t\t\tlogOntoName = \"Anonymous\";\n\t\t\tlogger.info(\"Ontology IRI is anonymous.\");\n\t\t}\n\t\tlogger.info(\"Ontologies loaded! Main Ontology: \" + logOntoName);\n\t}\n}",
"public class BackupExporter implements Exporter {\n\tprotected String convertedJson;\n\n\tpublic String getConvertedJson() {\n\t\treturn convertedJson;\n\t}\n\n\t@Override\n\tpublic void write(String text) throws Exception {\n\t\tconvertedJson = text;\n\t}\n}",
"public class FileExporter implements Exporter {\n\n\tprivate File destinationFile;\n\n\tpublic FileExporter(File destinationFile) {\n\t\tthis.destinationFile = destinationFile;\n\t}\n\n\t@Override\n\tpublic void write(String text) throws IOException {\n\t\twhile (destinationFile.exists()) {\n\t\t\tdestinationFile.delete();\n\t\t}\n\t\tFileWriter writer = new FileWriter(destinationFile);\n\t\twriter.write(text);\n\t\twriter.close();\n\t}\n\n}"
] | import de.uni_stuttgart.vis.vowl.owl2vowl.converter.Converter;
import de.uni_stuttgart.vis.vowl.owl2vowl.converter.IRIConverter;
import de.uni_stuttgart.vis.vowl.owl2vowl.converter.InputStreamConverter;
import de.uni_stuttgart.vis.vowl.owl2vowl.converter.OntologyConverter;
import de.uni_stuttgart.vis.vowl.owl2vowl.export.types.BackupExporter;
import de.uni_stuttgart.vis.vowl.owl2vowl.export.types.FileExporter;
import org.semanticweb.owlapi.model.IRI;
import org.semanticweb.owlapi.model.OWLOntology;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.util.Collection; | package de.uni_stuttgart.vis.vowl.owl2vowl;
/**
* Global class for easy to use of this library to include in other projects.
*/
public class Owl2Vowl {
protected Converter converter;
public Owl2Vowl(OWLOntology ontology) { | converter = new OntologyConverter(ontology); | 3 |
wesabe/grendel | src/main/java/com/wesabe/grendel/resources/DocumentsResource.java | [
"public class Credentials {\n\t/**\n\t * An authentication challenge {@link Response}. Use this when a client's\n\t * provided credentials are invalid.\n\t */\n\tpublic static final Response CHALLENGE =\n\t\tResponse.status(Status.UNAUTHORIZED)\n\t\t\t.header(HttpHeaders.WWW_AUTHENTICATE, \"Basic realm=\\\"Grendel\\\"\")\n\t\t\t.build();\n\t\n\tprivate final String username;\n\tprivate final String password;\n\t\n\t/**\n\t * Creates a new set of credentials.\n\t * \n\t * @param username the client's provided username\n\t * @param password the client's provided password\n\t */\n\tpublic Credentials(String username, String password) {\n\t\tthis.username = username;\n\t\tthis.password = password;\n\t}\n\t\n\t/**\n\t * Returns the client's provided username.\n\t */\n\tpublic String getUsername() {\n\t\treturn username;\n\t}\n\t\n\t/**\n\t * Returns the client's provided password.\n\t */\n\tpublic String getPassword() {\n\t\treturn password;\n\t}\n\t\n\t/**\n\t * Given a {@link UserDAO}, finds the associated {@link User} and returns a\n\t * {@link Session}.\n\t * \n\t * @param userDAO\n\t * a {@link UserDAO}\n\t * @throws WebApplicationException\n\t * if the user can't be found, or if the user's password is\n\t * incorrect\n\t */\n\tpublic Session buildSession(UserDAO userDAO) throws WebApplicationException {\n\t\tfinal User user = userDAO.findById(username);\n\t\tif (user != null) {\n\t\t\ttry {\n\t\t\t\tfinal UnlockedKeySet keySet = user.getKeySet().unlock(password.toCharArray());\n\t\t\t\treturn new Session(user, keySet);\n\t\t\t} catch (CryptographicException e) {\n\t\t\t\tthrow new WebApplicationException(CHALLENGE);\n\t\t\t}\n\t\t}\n\t\t\n\t\tthrow new WebApplicationException(CHALLENGE);\n\t}\n\t\n\t/**\n\t * Given a {@link UserDAO} and an allowed {@link User} id, finds the\n\t * associated {@link User} and returns a {@link Session}.\n\t * \n\t * @param userDAO\n\t * a {@link UserDAO}\n\t * @param allowedId\n\t * the id of the only {@link User} which should be allowed access\n\t * to session context\n\t * @throws WebApplicationException\n\t * if the user can't be found, or if the user's password is\n\t * incorrect\n\t */\n\tpublic Session buildSession(UserDAO userDAO, String allowedId) {\n\t\tfinal Session session = buildSession(userDAO);\n\t\tif (session.getUser().getId().equals(allowedId)) {\n\t\t\treturn session;\n\t\t}\n\t\t\n\t\tthrow new WebApplicationException(Status.FORBIDDEN);\n\t}\n}",
"public class Session {\n\tprivate final User user;\n\tprivate final UnlockedKeySet keySet;\n\t\n\tpublic Session(User user, UnlockedKeySet keySet) {\n\t\tthis.user = user;\n\t\tthis.keySet = keySet;\n\t}\n\t\n\tpublic UnlockedKeySet getKeySet() {\n\t\treturn keySet;\n\t}\n\t\n\tpublic User getUser() {\n\t\treturn user;\n\t}\n}",
"@Entity\n@Table(name=\"documents\")\n@IdClass(DocumentPK.class)\n@NamedQueries({\n\t@NamedQuery(\n\t\tname=\"com.wesabe.grendel.entities.Document.ByOwnerAndName\",\n\t\tquery=\"SELECT d FROM Document AS d WHERE d.name = :name AND d.owner = :owner\"\n\t)\n})\npublic class Document implements Serializable {\n\tprivate static final long serialVersionUID = 5699449595549234402L;\n\n\t@Id\n\tprivate String name;\n\t\n\t@Id\n\tprivate User owner;\n\t\n\t@Column(name=\"content_type\", nullable=false, length=40)\n\tprivate String contentType;\n\t\n\t@Column(name=\"body\", nullable=false)\n\t@Lob\n\tprivate byte[] body;\n\t\n\t@Column(name=\"created_at\", nullable=false)\n\t@Type(type=\"org.joda.time.contrib.hibernate.PersistentDateTime\")\n\tprivate DateTime createdAt;\n\t\n\t@Column(name=\"modified_at\", nullable=false)\n\t@Type(type=\"org.joda.time.contrib.hibernate.PersistentDateTime\")\n\tprivate DateTime modifiedAt;\n\t\n\t@ManyToMany(fetch=FetchType.LAZY, mappedBy=\"linkedDocuments\", cascade={CascadeType.ALL})\n\t@JoinTable(name=\"links\")\n\tprivate Set<User> linkedUsers = Sets.newHashSet();\n\t\n\t@Version\n\t@Column(name=\"version\", nullable=false)\n\tprivate long version = 0;\n\t\n\t@Deprecated\n\tpublic Document() {\n\t\t// for Hibernate usage only\n\t}\n\t\n\t/**\n\t * Creates a new {@link Document}, owned by the given {@link User} and with\n\t * the given name.\n\t * \n\t * @param owner the new document's owner\n\t * @param name the new document's name\n\t * @param contentType the document's content type\n\t */\n\tpublic Document(User owner, String name, MediaType contentType) {\n\t\tthis.owner = owner;\n\t\tthis.name = name;\n\t\tthis.contentType = contentType.toString();\n\t\t\n\t\tthis.createdAt = new DateTime(DateTimeZone.UTC);\n\t\tthis.modifiedAt = new DateTime(DateTimeZone.UTC);\n\t}\n\t\n\t/**\n\t * Returns the document's owner.\n\t */\n\tpublic User getOwner() {\n\t\treturn owner;\n\t}\n\t\n\t/**\n\t * Returns the document's name.\n\t */\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\t\n\t/**\n\t * Returns a set of {@link User}s who have read-only access to this\n\t * document.\n\t */\n\tpublic Set<User> getLinkedUsers() {\n\t\treturn linkedUsers;\n\t}\n\t\n\t/**\n\t * Provide a {@link User} with read-only access to this document.\n\t */\n\tpublic void linkUser(User user) {\n\t\tlinkedUsers.add(user);\n\t\tuser.getLinkedDocuments().add(this);\n\t}\n\t\n\t/**\n\t * Remove a {@link User}'s read-only access to this document.\n\t */\n\tpublic void unlinkUser(User user) {\n\t\tlinkedUsers.remove(user);\n\t\tuser.getLinkedDocuments().remove(this);\n\t}\n\t\n\t/**\n\t * Returns {@code true} if the given {@link User} has read-only access to\n\t * this document.\n\t */\n\tpublic boolean isLinked(User user) {\n\t\treturn linkedUsers.contains(user);\n\t}\n\t\n\t/**\n\t * Returns the document's content type.\n\t */\n\tpublic MediaType getContentType() {\n\t\treturn MediaType.valueOf(contentType);\n\t}\n\t\n\t/**\n\t * Returns a UTC timestamp of when this document was created.\n\t */\n\tpublic DateTime getCreatedAt() {\n\t\treturn toUTC(createdAt);\n\t}\n\t\n\t/**\n\t * Sets a UTC timestamp of when this document was created.\n\t */\n\tpublic void setCreatedAt(DateTime createdAt) {\n\t\tthis.createdAt = toUTC(createdAt);\n\t}\n\t\n\t/**\n\t * Returns a UTC timestamp of when this document was last modified.\n\t */\n\tpublic DateTime getModifiedAt() {\n\t\treturn toUTC(modifiedAt);\n\t}\n\t\n\t/**\n\t * Sets a UTC timestamp of when this document was last modified.\n\t */\n\tpublic void setModifiedAt(DateTime modifiedAt) {\n\t\tthis.modifiedAt = toUTC(modifiedAt);\n\t}\n\t\n\t/**\n\t * Sets the {@link Document}'s body to an encrypted+signed OpenPGP message\n\t * containing {@code body}.\n\t * \n\t * @param keySet\n\t * the {@link UnlockedKeySet} of the {@link User} that owns this\n\t * {@link Document}\n\t * @param random\n\t * a {@link SecureRandom} instance\n\t * @param body\n\t * the unencrypted document body\n\t * @throws CryptographicException\n\t * if the owner's {@link KeySet} cannot be unlocked with {@code\n\t * ownerPassphrase}\n\t * @see MessageWriter\n\t */\n\tpublic void encryptAndSetBody(UnlockedKeySet keySet, SecureRandom random,\n\t\tbyte[] body) throws CryptographicException {\n\t\t\n\t\tfinal Set<KeySet> recipients = Sets.newHashSetWithExpectedSize(linkedUsers.size());\n\t\tfor (User linkedUser : linkedUsers) {\n\t\t\trecipients.add(linkedUser.getKeySet());\n\t\t}\n\t\t\n\t\tfinal MessageWriter writer = new MessageWriter(keySet, recipients, random);\n\t\tthis.body = writer.write(body);\n\t}\n\t\n\t/**\n\t * Decrypts the document's body using the {@link UnlockedKeySet} of the\n\t * owner or a recipient;\n\t * \n\t * @param unlockedKeySet\n\t * an {@link UnlockedKeySet} belonging to either the\n\t * {@link Document}'s owner or a recipient\n\t * @return the decrypted document body\n\t * @throws CryptographicException\n\t * if there is an error decrypting and verifying the\n\t * encrypted+signed OpenPGP message\n\t * @see MessageReader\n\t */\n\tpublic byte[] decryptBody(UnlockedKeySet unlockedKeySet) throws CryptographicException {\n\t\tfinal MessageReader reader = new MessageReader(owner.getKeySet(), unlockedKeySet);\n\t\treturn reader.read(body);\n\t}\n\t\n\tprivate DateTime toUTC(DateTime dateTime) {\n\t\treturn dateTime.toDateTime(DateTimeZone.UTC);\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn HashCode.calculate(\n\t\t\tgetClass(), body, contentType, createdAt, modifiedAt, name, owner\n\t\t);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj) {\n\t\t\treturn true;\n\t\t}\n\t\tif (obj == null) {\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tif (!(obj instanceof Document)) {\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tfinal Document that = (Document) obj;\n\t\treturn equal(name, that.name) && equal(owner, that.owner) &&\n\t\t\t\tequal(body, that.body) && equal(createdAt, that.createdAt) &&\n\t\t\t\tequal(contentType, that.contentType) &&\n\t\t\t\tequal(modifiedAt, that.modifiedAt);\n\t}\n\t\n\t@Override\n\tpublic String toString() {\n\t\treturn name;\n\t}\n\t\n\t/**\n\t * Returns an opaque string indicating the {@link Document}'s name and\n\t * version.\n\t */\n\tpublic String getEtag() {\n\t\treturn new StringBuilder(\"doc-\").append(name).append('-').append(version).toString();\n\t}\n}",
"public class UserDAO extends AbstractDAO<User> {\n\t\n\t@Inject\n\tpublic UserDAO(Provider<Session> provider) {\n\t\tsuper(provider, User.class);\n\t}\n\t\n\t/**\n\t * Returns {@code true} if a user already exists with the given id.\n\t */\n\tpublic boolean contains(String id) {\n\t\treturn namedQuery(\"com.wesabe.grendel.entities.User.Exists\")\n\t\t\t\t\t.setString(\"id\", id)\n\t\t\t\t\t.uniqueResult() != null;\n\t}\n\t\n\t/**\n\t * Returns the {@link User} with the given id, or {@code null} if the user\n\t * does not exist.\n\t */\n\tpublic User findById(String id) {\n\t\treturn get(id);\n\t}\n\t\n\t/**\n\t * Returns a list of all {@link User}s.\n\t */\n\tpublic List<User> findAll() {\n\t\treturn list(namedQuery(\"com.wesabe.grendel.entities.User.All\"));\n\t}\n\t\n\t/**\n\t * Writes the {@link User} to the database.\n\t * \n\t * @see Session#saveOrUpdate(Object)\n\t */\n\tpublic User saveOrUpdate(User user) {\n\t\tcurrentSession().saveOrUpdate(user);\n\t\treturn user;\n\t}\n\n\t/**\n\t * Deletes the {@link User} from the database.\n\t */\n\tpublic void delete(User user) {\n\t\tcurrentSession().delete(user);\n\t}\n}",
"public class DocumentListRepresentation {\n\tpublic static class DocumentListItem {\n\t\tprivate final UriInfo uriInfo;\n\t\tprivate final Document document;\n\t\t\n\t\tpublic DocumentListItem(UriInfo uriInfo, Document document) {\n\t\t\tthis.uriInfo = uriInfo;\n\t\t\tthis.document = document;\n\t\t}\n\t\t\n\t\t@JsonGetter(\"name\")\n\t\tpublic String getName() {\n\t\t\treturn document.getName();\n\t\t}\n\t\t\n\t\t@JsonGetter(\"uri\")\n\t\tpublic String getURI() {\n\t\t\treturn uriInfo.getBaseUriBuilder()\n\t\t\t\t\t\t\t.path(DocumentResource.class)\n\t\t\t\t\t\t\t.build(document.getOwner(), document)\n\t\t\t\t\t\t\t.toASCIIString();\n\t\t}\n\t}\n\t\n\tprivate UriInfo uriInfo;\n\tprivate Set<Document> documents;\n\t\n\tpublic DocumentListRepresentation(UriInfo uriInfo, Set<Document> documents) {\n\t\tthis.uriInfo = uriInfo;\n\t\tthis.documents = documents;\n\t}\n\t\n\t@JsonGetter(\"documents\")\n\tpublic List<DocumentListItem> listDocuments() {\n\t\tfinal List<DocumentListItem> items = Lists.newArrayListWithCapacity(documents.size());\n\t\tfor (Document doc : documents) {\n\t\t\titems.add(new DocumentListItem(uriInfo, doc));\n\t\t}\n\t\treturn items;\n\t}\n\t\n\t@JsonIgnore\n\tpublic Set<Document> getDocuments() {\n\t\treturn documents;\n\t}\n\t\n\t@JsonIgnore\n\tpublic UriInfo getUriInfo() {\n\t\treturn uriInfo;\n\t}\n}"
] | import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriInfo;
import com.google.inject.Inject;
import com.wesabe.grendel.auth.Credentials;
import com.wesabe.grendel.auth.Session;
import com.wesabe.grendel.entities.Document;
import com.wesabe.grendel.entities.dao.UserDAO;
import com.wesabe.grendel.representations.DocumentListRepresentation; | package com.wesabe.grendel.resources;
/**
* A class which exposes a list of {@link Document}s as a resource.
*
* @author coda
*/
@Path("/users/{id}/documents")
@Produces(MediaType.APPLICATION_JSON)
public class DocumentsResource {
final UserDAO userDAO;
@Inject
public DocumentsResource(UserDAO userDAO) {
this.userDAO = userDAO;
}
@GET
public DocumentListRepresentation listDocuments(@Context UriInfo uriInfo, | @Context Credentials credentials, @PathParam("id") String id) { | 0 |
aredee/accumulo-mesos | accumulo-mesos-executor/src/main/java/aredee/mesos/frameworks/accumulo/executor/AccumuloStartExecutor.java | [
"public class Environment {\n\n public static final String JAVA_HOME = \"JAVA_HOME\";\n\n public static final String CLASSPATH = \"CLASSPATH\";\n\n public static final String HADOOP_PREFIX = \"HADOOP_PREFIX\";\n public static final String HADOOP_CONF_DIR = \"HADOOP_CONF_DIR\";\n public static final String HADOOP_HOME = \"HADOOP_HOME\";\n \n public static final String ACCUMULO_HOME = \"ACCUMULO_HOME\";\n public static final String ACCUMULO_LOG_DIR = \"ACCUMULO_LOG_DIR\";\n public static final String ACCUMULO_CLIENT_CONF_PATH = \"ACCUMULO_CLIENT_CONF_PATH\";\n public static final String ACCUMULO_CONF_DIR = \"ACCUMULO_CONF_DIR\";\n public static final String ACCUMULO_WALOG = \"ACCUMULO_WALOG\";\n \n public static final String LD_LIBRARY_PATH = \"LD_LIBRARY_PATH\";\n public static final String DYLD_LIBRARY_PATH = \"DYLD_LIBRARY_PATH\";\n \n // List of paths separated by commas\n public static final String NATIVE_LIB_PATHS = \"NATIVE_LIB_PATHS\";\n \n public static final String ZOOKEEPER_HOME = \"ZOOKEEPER_HOME\";\n\n public static final String MESOS_DIRECTORY = \"MESOS_DIRECTORY\";\n\n public static final List<String> REQUIRED_FRAMEWORK_VARS = Arrays.asList(\n JAVA_HOME,\n ACCUMULO_HOME,\n HADOOP_PREFIX,\n HADOOP_CONF_DIR,\n ZOOKEEPER_HOME);\n\n public static final List<String> REQUIRED_EXECUTOR_VARS = Arrays.asList(\n JAVA_HOME,\n ACCUMULO_HOME,\n HADOOP_PREFIX,\n ZOOKEEPER_HOME,\n ACCUMULO_LOG_DIR);\n\n\n /*\n Optional Accumulo vars for executor\n */\n public static final String ACCUMULO_XTRAJARS = \"ACCUMULO_XTRAJARS\";\n public static final String ACCUMULO_GENERAL_OPTS = \"ACCUMULO_GENERAL_OPTS\";\n public static final String ACCUMULO_JAAS_CONF = \"ACCUMULO_JAAS_CONF\"; //-Djava.security.auth.login.config=${ACCUMULO_JAAS_CONF}\n public static final String ACCUMULO_KRB5_CONF = \"ACCUMULO_KRB5_CONF\"; //-Djava.security.krb5.conf=${ACCUMULO_KRB5_CONF}\n\n public static final String ACCUMULO_MASTER_OPTS = \"ACCUMULO_MASTER_OPTS\";\n public static final String ACCUMULO_GC_OPTS = \"ACCUMULO_GC_OPTS\";\n public static final String ACCUMULO_TSERVER_OPTS = \"ACCUMULO_TSERVER_OPTS\";\n public static final String ACCUMULO_MONITOR_OPTS = \"ACCUMULO_MONITOR_OPTS\";\n public static final String ACCUMULO_LOGGER_OPTS = \"ACCUMULO_LOGGER_OPTS\";\n public static final String ACCUMULO_OTHER_OPTS = \"ACCUMULO_OTHER_OPTS\";\n public static final String ACCUMULO_KILL_CMD = \"ACCUMULO_KILL_CMD\";\n\n // generated\n public static final String START_JAR = \"START_JAR\";\n public static final String LIB_PATH = \"LIB_PATH\";\n /*\n if [ -e \"${HADOOP_PREFIX}/lib/native/libhadoop.so\" ]; then\n LIB_PATH=\"${HADOOP_PREFIX}/lib/native\"\n LD_LIBRARY_PATH=\"${LIB_PATH}:${LD_LIBRARY_PATH}\" # For Linux\n DYLD_LIBRARY_PATH=\"${LIB_PATH}:${DYLD_LIBRARY_PATH}\" # For Mac\n fi\n */\n\n\n public static List<String> getMissingVariables(List<String> vars) {\n List<String> missingVariables = new ArrayList<>();\n Set<String> envKeys = System.getenv().keySet();\n for(String var : vars ) {\n if(!envKeys.contains(var)){\n missingVariables.add(var);\n }\n }\n return missingVariables;\n }\n\n public static String get(String var){\n return System.getenv(var);\n }\n\n}",
"public class AccumuloInitializer {\n private static final Logger LOGGER = LoggerFactory.getLogger(AccumuloInitializer.class);\n\n private Accumulo config;\n private String accumuloHome;\n \n public AccumuloInitializer(Accumulo config) {\n this.config = config;\n this.accumuloHome = Environment.get(Environment.ACCUMULO_HOME);\n }\n \n /**\n * Write the accumulo site file and initialize accumulo.\n * \n * The system property Environment.ACCUMULO_HOME and HADOOP_CONF_DIR must be set and config must have\n * the accumulo instance name, root password, along with the accumulo directories set.\n *\n * @return accumulo instance name\n */\n public int initialize() throws IOException {\n \n // run accumulo init procedure\n LOGGER.info(\"Writing accumulo-site.xml\");\n\n AccumuloSiteXml siteXml = new AccumuloSiteXml(this.config);\n siteXml.initializeFromScheduler(AccumuloSiteXml.getEmptySiteXml());\n\n writeAccumuloSiteFile(accumuloHome, siteXml);\n config.setSiteXml(siteXml.toString());\n\n // accumulo-env.sh\n copyAccumuloEnvFile(accumuloHome); // IOException\n\n LinkedList<String> initArgs = new LinkedList<>();\n initArgs.add(\"--instance-name\");\n initArgs.add(config.getInstance());\n initArgs.add(\"--password\");\n initArgs.add(config.getRootPassword());\n initArgs.add(\"--clear-instance-name\");\n\n AccumuloProcessFactory processFactory = new AccumuloProcessFactory();\n \n Process initProcess;\n int status = 0;\n try {\n initProcess = processFactory.exec(ServerProfile.TypeEnum.init.getServerKeyword(),\n initArgs.toArray(new String[initArgs.size()]));\n initProcess.waitFor();\n status = initProcess.exitValue();\n } catch (Exception ioe) {\n LOGGER.error(\"IOException while trying to initialize Accumulo\", ioe);\n status = -1;\n } \n return status;\n }\n\n public static void writeAccumuloSiteFile(String accumuloHomeDir, AccumuloSiteXml siteXml) {\n LOGGER.info(\"ACCUMULO HOME? \" + accumuloHomeDir);\n try {\n \n File accumuloSiteFile = new File(accumuloHomeDir + File.separator +\n \"conf\" + File.separator + \"accumulo-site.xml\");\n\n LOGGER.info(\"Writing accumulo-site.xml to {}\", accumuloSiteFile.getAbsolutePath());\n\n OutputStream siteFile = new FileOutputStream(accumuloSiteFile);\n IOUtils.write(siteXml.toXml(), siteFile);\n IOUtils.closeQuietly(siteFile);\n\n } catch (Exception e) {\n logErrorAndDie(\"Error Creating accumulo-site.xml\\n\",e);\n }\n }\n\n /**\n * This is required because the bin/accumulo script complains without it. The framework should be setting\n * all the environment variables that this sets, and the script uses them if already set.\n *\n * @param accumuloHomeDir\n * @throws IOException\n */\n public static void copyAccumuloEnvFile(String accumuloHomeDir) throws IOException {\n File inputFile = new File(accumuloHomeDir+File.separator+\"conf/examples/1GB/native-standalone/accumulo-env.sh\");\n File destFile = new File(accumuloHomeDir+File.separator+\"conf/accumulo-env.sh\");\n Files.copy(inputFile.toPath(), destFile.toPath(), StandardCopyOption.REPLACE_EXISTING);\n }\n\n /**\n * Copy native maps from mesosDirectory to accumuloHome/lib/native if the maps exist\n *\n * @param mesosDirectory\n * @param accumuloHome\n * @throws IOException\n */\n public static void copyAccumuloNativeMaps( String mesosDirectory, String accumuloHome) throws IOException {\n File inputFile = new File(mesosDirectory+File.separator+ Constants.ACCUMULO_NATIVE_LIB);\n File destFile = new File(accumuloHome+File.separator+\"lib/native\");\n if( inputFile.exists() ) {\n Files.copy(inputFile.toPath(), destFile.toPath(), StandardCopyOption.REPLACE_EXISTING);\n }\n }\n\n\n private static void logErrorAndDie(String message, Exception e){\n LOGGER.error(message, e);\n throw new RuntimeException(message, e);\n }\n\n\n}",
"public class AccumuloSiteXml {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(AccumuloSiteXml.class);\n\n private static final String INSTANCE_VOLUMES = \"instance.volumes\"; // hdfs://localhost:9000/accumulo ...\n private static final String INSTANCE_ZOOKEEPER_HOST = \"instance.zookeeper.host\";\n\n private static final String TRACE_USER = \"trace.user\";\n private static final String TRACE_USER_DEFAULT = \"root\";\n private static final String TRACE_TOKEN_PROPERTY_PASSWORD = \"trace.password\";\n private static final String TRACE_TOKEN_PROPERTY_PASSWORD_DEFAULT = \"secret\";\n\n private static final String INSTANCE_SECRET = \"instance.secret\";\n private static final String INSTANCE_SECRET_DEFAULT = \"DEFAULT\";\n\n private static final String GENERAL_CLASSPATHS = \"general.classpaths\";\n private static final String GENERAL_CLASSPATHS_DEFAULT =\n \"$ACCUMULO_CONF_DIR,\\n\" +\n \"$ACCUMULO_HOME/lib/[^.].*.jar,\\n\" +\n \"$ZOOKEEPER_HOME/zookeeper[^.].*.jar,\\n\" +\n \"$HADOOP_CONF_DIR,\\n\" +\n \"$HADOOP_PREFIX/[^.].*.jar,\\n\" +\n \"$HADOOP_PREFIX/lib/(?!slf4j)[^.].*.jar,\\n\" +\n \"$HADOOP_PREFIX/share/hadoop/common/[^.].*.jar,\\n\" +\n \"$HADOOP_PREFIX/share/hadoop/common/lib/(?!slf4j)[^.].*.jar,\\n\" +\n \"$HADOOP_PREFIX/share/hadoop/hdfs/[^.].*.jar,\\n\" +\n \"$HADOOP_PREFIX/share/hadoop/mapreduce/[^.].*.jar,\\n\" +\n \"$HADOOP_PREFIX/share/hadoop/yarn/[^.].*.jar,\\n\" +\n \"$HADOOP_PREFIX/share/hadoop/yarn/lib/jersey.*.jar,\\n\" +\n \"$EMPTY/usr/hdp/current/hadoop-client/[^.].*.jar,\\n\" +\n \"$EMPTY/usr/hdp/current/hadoop-client/lib/(?!slf4j)[^.].*.jar,\\n\" +\n \"$EMPTY/usr/hdp/current/hadoop-hdfs-client/[^.].*.jar,\\n\" +\n \"$EMPTY/usr/hdp/current/hadoop-mapreduce-client/[^.].*.jar,\\n\" +\n \"$EMPTY/usr/hdp/current/hadoop-yarn-client/[^.].*.jar,\\n\" +\n \"$EMPTY/usr/hdp/current/hadoop-yarn-client/lib/jersey.*.jar,\\n\" +\n \"$EMPTY/usr/hdp/current/hive-client/lib/hive-accumulo-handler.jar\\n\" +\n \"$EMPTY/usr/lib/hadoop/[^.].*.jar,\\n\" +\n \"$EMPTY/usr/lib/hadoop/hadoop-common.jar,\\n\" +\n \"$EMPTY/usr/lib/hadoop/lib/[^.].*.jar,\\n\" +\n \"$EMPTY/usr/lib/hadoop-hdfs/[^.].*.jar,\\n\" +\n \"$EMPTY/usr/lib/hadoop-mapreduce/[^.].*.jar,\\n\" +\n \"$EMPTY/usr/lib/hadoop-yarn/[^.].*.jar,\\n\" +\n \"$EMPTY/usr/lib/hadoop-yarn/lib/jersey.*.jar,\\n\"+\n \"$EMPTY/usr/share/java/[^.].*.jar\\n\";\n\n // These are set on the Executor because different tservers might have different memory profiles\n private static final String TSERVER_MEMORY_MAPS_MAX = \"tserver.memory.maps.max\";\n private static final double TSERVER_MEMORY_MAPS_MAX_FACTOR = 0.75;\n private static final String TSERVER_CACHE_DATA_SIZE = \"tserver.cache.data.size\";\n private static final double TSERVER_CACHE_DATA_SIZE_FACTOR = 0.25;\n private static final String TSERVER_CACHE_INDEX_SIZE = \"tserver.cache.index.size\";\n private static final double TSERVER_CACHE_INDEX_SIZE_FACTOR = 0.1;\n private static final String TSERVER_SORT_BUFFER_SIZE = \"tserver.sort.buffer.size\";\n private static final double TSERVER_SORT_BUFFER_SIZE_FACTOR = 0.25;\n private static final String TSERVER_WALOG_MAX_SIZE = \"tserver.walog.max.size\";\n private static final double TSERVER_WALOG_MAX_SIZE_FACTOR = 0.1;\n\n private static final String TSERVER_MEMORY_MAPS_NATIVE_ENABLED = \"tserver.memory.maps.native.enabled\";\n\n private Document document;\n //private static XPath xPath = XPathFactory.newInstance().newXPath();\n\n private Accumulo config = null;\n\n public AccumuloSiteXml(){\n // empty, used by Executor\n }\n\n public AccumuloSiteXml(Accumulo config) {\n this.config = config;\n }\n\n public void initializeFromScheduler(String xmlString){\n Preconditions.checkNotNull(this.config, \"Scheduler must instantiate class with configuration object\");\n initXml(xmlString);\n addDefaultProperties();\n addPropertiesFromConfig();\n defineNativeMaps();\n }\n\n /**\n * Most of the properties should be set by the scheduler. This initializes the XML\n * to override memory properties, and set native maps based on local os.\n *\n * @param xmlString\n */\n public void initializeFromExecutor(String xmlString){\n initXml(xmlString);\n }\n\n /**\n *\n * Breaks apart given total memory into sane tserver memory settings\n *\n * @param memory\n */\n public void defineTserverMemory(double memory) {\n // TODO this should probably be more sophisticated. Some of these may have a pratical cap\n // TODO vary this based on native maps being used or not\n setMemoryValue(memory, TSERVER_MEMORY_MAPS_MAX, TSERVER_MEMORY_MAPS_MAX_FACTOR);\n setMemoryValue(memory, TSERVER_CACHE_DATA_SIZE, TSERVER_CACHE_DATA_SIZE_FACTOR);\n setMemoryValue(memory, TSERVER_CACHE_INDEX_SIZE, TSERVER_CACHE_INDEX_SIZE_FACTOR);\n setMemoryValue(memory, TSERVER_SORT_BUFFER_SIZE, TSERVER_SORT_BUFFER_SIZE_FACTOR);\n setMemoryValue(memory, TSERVER_WALOG_MAX_SIZE, TSERVER_WALOG_MAX_SIZE_FACTOR);\n }\n\n private void setMemoryValue(double memory, String name, double factor){\n Double result = memory * factor;\n Integer whole = result.intValue();\n String mem = whole.toString() + \"M\";\n setPropertyValue(name, mem);\n }\n\n /*\n only called from initFromScheduler\n */\n private void defineNativeMaps(){\n String enableNativeMaps = \"false\";\n if( this.config.hasNativeLibUri() ) {\n String os = System.getProperty(\"os.name\");\n if (os.contains(\"Linux\")) {\n // only supporting native maps on linux\n enableNativeMaps = \"true\";\n }\n }\n setPropertyValue(TSERVER_MEMORY_MAPS_NATIVE_ENABLED, enableNativeMaps);\n }\n\n private void addPropertiesFromConfig(){\n setPropertyValue(INSTANCE_ZOOKEEPER_HOST, config.getZkServers());\n String hdfsUri = config.getHdfsUri();\n if( !hdfsUri.endsWith(File.separator)){\n hdfsUri += File.separator;\n }\n hdfsUri += config.getInstance();\n // TODO check if directory exists? test if Accumulo creates it\n setPropertyValue(INSTANCE_VOLUMES, hdfsUri);\n }\n\n private void addDefaultProperties(){\n setPropertyValue(GENERAL_CLASSPATHS, GENERAL_CLASSPATHS_DEFAULT);\n setPropertyValue(INSTANCE_SECRET, INSTANCE_SECRET_DEFAULT);\n setPropertyValue(TRACE_USER, TRACE_USER_DEFAULT);\n setPropertyValue(TRACE_TOKEN_PROPERTY_PASSWORD, TRACE_TOKEN_PROPERTY_PASSWORD_DEFAULT);\n }\n\n /**\n * \n * @return accumulo-site.xml as a string\n * \n */\n public String toXml() {\n return getXmlStringFromDocument(document);\n }\n \n /**\n * @return accumulo-site.xml as a string\n */\n public String toString() {\n return toXml();\n }\n\n /**\n * Get the value of a property\n * @param propertyName\n * @return property value, Optional.isPresent == true if property is there but could be empty\n * otherwise Optional.isPresent == false.\n * @throws Exception\n */\n/*\n private Optional<String> getPropertyValue(String propertyName) throws Exception {\n Optional<String> value = Optional.fromNullable(null);\n Node node = getPropertyValueNode(propertyName);\n if (node != null){\n value = Optional.fromNullable(node.getTextContent());\n }\n return value;\n }\n*/\n\n /**\n * This will set and existing property to a new value. If its a new property\n * then use addProperty().\n *\n * @param propertyName of property\n * @param value of property\n * @throws Exception\n *\n */\n private void setPropertyValue(String propertyName, String value) {\n /*\n try {\n Node node = null;\n node = getPropertyValueNode(propertyName);\n if (node != null){\n LOGGER.info(\"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!setText setPropertyValue !!!!!!!!!!!!!!!!!!!!!!!!!!!!!\");\n node.setTextContent(value);\n } else {\n addProperty(propertyName, value);\n }\n } catch (XPathExpressionException e) {\n addProperty(propertyName, value);\n }\n */\n addProperty(propertyName, value);\n\n }\n\n private void addProperty(String name, String value) {\n\n Element propertyElement = document.createElement(\"property\");\n document.getDocumentElement().appendChild(propertyElement);\n\n Element nameElement = document.createElement(\"name\");\n nameElement.appendChild(document.createTextNode(name));\n propertyElement.appendChild(nameElement);\n\n Element valueElement = document.createElement(\"value\");\n valueElement.appendChild(document.createTextNode(value));\n propertyElement.appendChild(valueElement);\n }\n\n/*\n private Node getPropertyValueNode(String propertyName) throws XPathExpressionException {\n String xpath = \"//property/name[. = '\"+propertyName+\"']\";\n Node node = (Node) xPath.evaluate(xpath, document, XPathConstants.NODE);\n if (node != null){\n while (!node.getNextSibling().getNodeName().equalsIgnoreCase(\"value\")) {\n node = node.getNextSibling();\n }\n node = node.getNextSibling();\n }\n return node;\n }\n*/\n\n private void initXml(String input) {\n try {\n LOGGER.error(\"Reconstituting XML from String: {}\", input);\n\n DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();\n DocumentBuilder db = dbf.newDocumentBuilder();\n document = db.parse(new InputSource(new ByteArrayInputStream(input.getBytes(\"utf-8\"))));\n //XPathFactory factory = XPathFactory.newInstance();\n //xPath = factory.newXPath();\n } catch (ParserConfigurationException e) {\n LOGGER.error(\"Error reconsituting XML from String: {}\", input);\n throw new RuntimeException(e);\n } catch (SAXException e) {\n LOGGER.error(\"Error reconsituting XML from String: {}\", input);\n throw new RuntimeException(e);\n } catch (IOException e) {\n LOGGER.error(\"Error reconsituting XML from String: {}\", input);\n throw new RuntimeException(e);\n }\n }\n\n/*\n private void initXml(){\n this.xPath = XPathFactory.newInstance().newXPath();\n\n DocumentBuilder builder = null;\n try {\n builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();\n } catch (ParserConfigurationException e) {\n // TODO handle this failure\n throw new RuntimeException(e);\n }\n\n this.document = builder.newDocument();\n }\n*/\n /**\n * Creates an xml string containing just the configuration node\n *\n * @return\n */\n public static String getEmptySiteXml(){\n DocumentBuilder docBuilder = null;\n try {\n DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();\n docBuilder = docFactory.newDocumentBuilder();\n } catch (ParserConfigurationException e) {\n LOGGER.error(\"Unable to create xml document\");\n throw new RuntimeException(e);\n }\n\n // root elements\n Document doc = docBuilder.newDocument();\n Element rootElement = doc.createElement(\"configuration\");\n doc.appendChild(rootElement);\n\n\n return getXmlStringFromDocument(doc);\n }\n\n private static String getXmlStringFromDocument(Document doc){\n DOMSource source = new DOMSource(doc);\n StringWriter writer = new StringWriter();\n StreamResult result = new StreamResult(writer);\n TransformerFactory tf = TransformerFactory.newInstance();\n Transformer transformer = null;\n try {\n transformer = tf.newTransformer();\n transformer.transform(source, result);\n } catch (TransformerConfigurationException e) {\n LOGGER.error(\"Error creating XML transformer configuration\");\n throw new RuntimeException(e);\n } catch (TransformerException e) {\n LOGGER.error(\"Error performing xml transform\");\n throw new RuntimeException(e);\n }\n return writer.toString();\n }\n}",
"public class ServerProfile {\n\n public enum TypeEnum {\n master(\"master\"),\n tserver(\"tserver\"),\n gc(\"gc\"),\n tracer(\"tracer\"),\n monitor(\"monitor\"),\n init(\"init\"),\n shell(\"shell\");\n\n private final String keyword;\n\n TypeEnum(String keyword){\n this.keyword = keyword;\n }\n\n public String getServerKeyword(){ return keyword;}\n }\n\n private String name = null;\n private String description = null;\n private TypeEnum type = null;\n private Integer memory = 128;\n private BigDecimal cpus = null;\n private String launcher = null;\n private String user = null;\n private String siteXml = null;\n private List<String> serverKeywordArgs = null;\n private boolean useNativeMaps = false;\n\n /**\n * A short name for this profile\\n\n **/\n @JsonProperty(\"name\")\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n\n\n /**\n * Description of this profile\\n\n **/\n @JsonProperty(\"description\")\n public String getDescription() {\n return description;\n }\n public void setDescription(String description) {\n this.description = description;\n }\n\n /**\n * Accumulo server type\\n\n **/\n @JsonProperty(\"type\")\n public TypeEnum getType() {\n return type;\n }\n public void setType(TypeEnum type) {\n this.type = type;\n }\n\n\n /**\n * Memory to allocate to this server in MB. -Xmx yyyyM\\n\n **/\n @JsonProperty(\"mem\")\n public Integer getMemory() {\n return memory;\n }\n public void setMemory(Integer memory) {\n this.memory = memory;\n }\n\n\n /**\n * Number of cpus to allocate to this server\\n\n **/\n @JsonProperty(\"cpus\")\n public BigDecimal getCpus() {\n return cpus;\n }\n public void setCpus(BigDecimal cpus) {\n this.cpus = cpus;\n }\n\n\n /**\n * Fully qualified class name of launcher class to launch with.\\n\n **/\n //TODO implement defining launcher as config\n @JsonProperty(\"launcher\")\n public String getLauncher() {\n return launcher;\n }\n public void setLauncher(String launcher) {\n this.launcher = launcher;\n }\n\n\n /**\n * System user name to run server processes as.\\n\n **/\n @JsonProperty(\"user\")\n public String getUser() {\n return user;\n }\n public void setUser(String user) {\n this.user = user;\n }\n public boolean hasUser(){\n boolean hasUser = false;\n if( user != null ){\n hasUser = !user.isEmpty();\n }\n return hasUser;\n }\n\n @JsonProperty(\"siteXml\")\n public String getSiteXml() { return siteXml; }\n public void setSiteXml(String siteXml) { this.siteXml = siteXml; }\n\n @JsonProperty(\"serverKeywordArgs\")\n public List<String> getServerKeywordArgs(){\n if( serverKeywordArgs == null ){\n serverKeywordArgs = Lists.newArrayList();\n }\n return this.serverKeywordArgs;\n }\n public void setServerKeywordArgs(List<String> serverKeywordArgs){\n this.serverKeywordArgs = serverKeywordArgs;\n }\n\n @JsonProperty(\"useNativeMaps\")\n public boolean getUseNativeMaps(){ return useNativeMaps; }\n public void setUseNativemaps(boolean useNativeMaps){\n this.useNativeMaps = useNativeMaps;\n }\n\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"class ServerProfile {\\n\");\n\n sb.append(\" name: \").append(name).append(\"\\n\");\n sb.append(\" description: \").append(description).append(\"\\n\");\n sb.append(\" type: \").append(type).append(\"\\n\");\n sb.append(\" memory: \").append(memory).append(\"\\n\");\n sb.append(\" cpus: \").append(cpus).append(\"\\n\");\n sb.append(\" launcher: \").append(launcher).append(\"\\n\");\n sb.append(\" user: \").append(user).append(\"\\n\");\n sb.append(\" siteXml: \").append(siteXml).append(\"\\n\");\n sb.append(\"}\\n\");\n return sb.toString();\n }\n}",
"public class AccumuloProcessFactory {\n private static final Logger LOGGER = LoggerFactory.getLogger(AccumuloProcessFactory.class);\n\n private List<LogWriter> logWriters = new ArrayList<>(5);\n private List<Process> cleanup = new ArrayList<>();\n private Map<String, String> processEnv = Maps.newHashMap();\n\n public AccumuloProcessFactory(){\n\n initializeEnvironment();\n }\n\n public Process exec(String keyword, String... keywordArgs) throws IOException {\n\n\n String javaHome = System.getProperty(\"java.home\");\n String javaBin = javaHome + File.separator + \"bin\" + File.separator + \"java\";\n\n LOGGER.debug(\"exec: Java Bin? \" + javaBin);\n\n String classpath = getClasspath();\n putProcessEnv(Environment.CLASSPATH, classpath);\n\n String accumulo_script = processEnv.get(Environment.ACCUMULO_HOME)+\"/bin/accumulo\";\n\n List<String> cmd = new ArrayList<>(2+keywordArgs.length);\n cmd.add(accumulo_script);\n cmd.add(keyword);\n\n for( String kwd : keywordArgs){\n cmd.add(kwd);\n }\n LOGGER.info(\"exec: accumulo command: {}\", cmd);\n ProcessBuilder builder = new ProcessBuilder(cmd.toArray(new String[0]));\n\n // copy environment into builder environment\n Map<String, String> environment = builder.environment();\n if( !processEnv.isEmpty() ) {\n LOGGER.debug(\"processEnv ? {}\", processEnv);\n environment.putAll(processEnv);\n }\n\n LOGGER.debug(\"exec: environment ? {}\", environment);\n\n Process process = builder.start();\n addLogWriter(processEnv.get(Environment.ACCUMULO_LOG_DIR),\n process.getErrorStream(), keyword, process.hashCode(), \".err\");\n addLogWriter(processEnv.get(Environment.ACCUMULO_LOG_DIR),\n process.getInputStream(), keyword, process.hashCode(), \".out\");\n\n return process;\n }\n\n private void initializeEnvironment(){\n putProcessEnv(Environment.JAVA_HOME, System.getenv(Environment.JAVA_HOME));\n\n String accumuloHome = System.getenv(Environment.ACCUMULO_HOME);\n putProcessEnv(Environment.ACCUMULO_HOME, System.getenv(Environment.ACCUMULO_HOME));\n putProcessEnv(Environment.ACCUMULO_LOG_DIR, accumuloHome + File.separator + \"logs\");\n putProcessEnv(Environment.ACCUMULO_CONF_DIR, accumuloHome + File.separator + \"conf\");\n\n String nativePaths = System.getenv(Environment.NATIVE_LIB_PATHS);\n String ldLibraryPath = \"\";\n if(!StringUtils.isEmpty(nativePaths)) {\n // change comma for a :\n ldLibraryPath = Joiner.on(File.pathSeparator).join(Arrays.asList(nativePaths.split(\",\")));\n }\n putProcessEnv(Environment.LD_LIBRARY_PATH, ldLibraryPath);\n putProcessEnv(Environment.DYLD_LIBRARY_PATH, ldLibraryPath);\n\n // if we're running under accumulo.start, we forward these env vars\n String hadoopPrefix = System.getenv(Environment.HADOOP_PREFIX);\n putProcessEnv(Environment.HADOOP_PREFIX, hadoopPrefix);\n putProcessEnv(Environment.ZOOKEEPER_HOME, System.getenv(Environment.ZOOKEEPER_HOME));\n\n // hadoop-2.2 puts error messages in the logs if this is not set\n putProcessEnv(Environment.HADOOP_HOME, hadoopPrefix);\n putProcessEnv(Environment.HADOOP_CONF_DIR, hadoopPrefix);\n }\n\n private void putProcessEnv(String name, String value){\n if( value != null && !value.isEmpty() ){\n processEnv.put(name, value);\n } else {\n LOGGER.warn(\"Found empty or null value for process environment variable: {}\", name);\n }\n }\n\n private void addLogWriter(String accumuloLogDir, InputStream stream, String className, int hash, String ext) throws IOException {\n File f = new File(accumuloLogDir, className + \"_\" + hash + ext);\n logWriters.add(new LogWriter(stream,f)); \n }\n \n private String getClasspath() throws IOException {\n\n try {\n ArrayList<ClassLoader> classloaders = new ArrayList<ClassLoader>();\n\n ClassLoader cl = this.getClass().getClassLoader();\n\n while (cl != null) {\n classloaders.add(cl);\n cl = cl.getParent();\n }\n\n Collections.reverse(classloaders);\n\n StringBuilder classpathBuilder = new StringBuilder();\n classpathBuilder.append(getProcessEnvPath(Environment.ACCUMULO_CONF_DIR));\n\n if (processEnv.get(Environment.HADOOP_CONF_DIR) != null) {\n classpathBuilder.append(File.pathSeparator).append(getProcessEnvPath(Environment.HADOOP_CONF_DIR));\n }\n\n //if (config.getClasspathItems() == null) { // JLK - classpathItems is not needed here. Only ever used in accumulo tests\n\n // assume 0 is the system classloader and skip it\n for (int i = 1; i < classloaders.size(); i++) {\n ClassLoader classLoader = classloaders.get(i);\n\n if (classLoader instanceof URLClassLoader) {\n\n for (URL u : ((URLClassLoader) classLoader).getURLs()) {\n append(classpathBuilder, u);\n }\n\n } else if (classLoader instanceof VFSClassLoader) {\n\n VFSClassLoader vcl = (VFSClassLoader) classLoader;\n for (FileObject f : vcl.getFileObjects()) {\n append(classpathBuilder, f.getURL());\n }\n } else {\n throw new IllegalArgumentException(\"Unknown classloader type : \" + classLoader.getClass().getName());\n }\n }\n /*\n } else {\n for (Object s : config.getClasspathItems())\n classpathBuilder.append(File.pathSeparator).append(s.toString());\n }\n */\n\n LOGGER.info(\"Creating classpath: \" + classpathBuilder.toString());\n\n return classpathBuilder.toString();\n\n } catch (URISyntaxException e) {\n throw new IOException(e);\n }\n }\n\n private String getProcessEnvPath(final String envVar){\n return new File(\n processEnv.get(envVar)\n ).getAbsolutePath();\n }\n\n private void append(StringBuilder classpathBuilder, URL url) throws URISyntaxException {\n File file = new File(url.toURI());\n // do not include dirs containing hadoop or accumulo site files\n if (!containsSiteFile(file))\n classpathBuilder.append(File.pathSeparator).append(file.getAbsolutePath());\n }\n\n private boolean containsSiteFile(File f) {\n return f.isDirectory() && f.listFiles(new FileFilter() {\n\n @Override\n public boolean accept(File pathname) {\n return pathname.getName().endsWith(\"site.xml\");\n }\n }).length > 0;\n }\n\n public static class LogWriter extends Thread {\n private BufferedReader in;\n private BufferedWriter out;\n\n public LogWriter(InputStream stream, File logFile) throws IOException {\n setDaemon(true);\n this.in = new BufferedReader(new InputStreamReader(stream));\n this.out = new BufferedWriter(new FileWriter(logFile));\n\n new Timer().schedule(new TimerTask() {public void run() {\n try {\n flush();\n } catch (IOException e) {\n LOGGER.error(\"Exception while attempting to flush.\", e);\n } \n }}, 1000,1000);\n start();\n }\n\n public synchronized void flush() throws IOException {\n if (out != null)\n out.flush();\n }\n\n @Override\n public void run() {\n String line;\n\n try {\n while ((line = in.readLine()) != null) {\n out.append(line);\n out.append(\"\\n\");\n }\n\n synchronized (this) {\n out.close();\n out = null;\n in.close();\n }\n\n } catch (IOException e) {}\n }\n }\n\n}"
] | import aredee.mesos.frameworks.accumulo.configuration.Environment;
import aredee.mesos.frameworks.accumulo.initialize.AccumuloInitializer;
import aredee.mesos.frameworks.accumulo.initialize.AccumuloSiteXml;
import aredee.mesos.frameworks.accumulo.model.ServerProfile;
import aredee.mesos.frameworks.accumulo.process.AccumuloProcessFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.mesos.Executor;
import org.apache.mesos.ExecutorDriver;
import org.apache.mesos.Protos;
import org.apache.mesos.Protos.TaskID;
import org.apache.mesos.Protos.TaskState;
import org.apache.mesos.Protos.TaskStatus;
import org.apache.mesos.SchedulerDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask; | package aredee.mesos.frameworks.accumulo.executor;
public class AccumuloStartExecutor implements Executor {
private static final Logger LOGGER = LoggerFactory.getLogger(AccumuloStartExecutor.class);
private static final ObjectMapper mapper = new ObjectMapper();
private Process serverProcess = null;
private Protos.ExecutorInfo executorInfo = null;
private Protos.FrameworkInfo frameworkInfo = null;
private Protos.SlaveInfo slaveInfo = null;
private Protos.TaskInfo taskInfo = null;
public AccumuloStartExecutor(){
}
/**
* Invoked once the executor driver has been able to successfully
* connect with Mesos. In particular, a scheduler can pass some
* data to it's executors through the {@link Protos.ExecutorInfo#getData()}
* field.
*
* @param executorDriver
* @param executorInfo Describes information about the executor that was
* registered.
* @param frameworkInfo Describes the framework that was registered.
* @param slaveInfo Describes the slave that will be used to launch
* the tasks for this executor.
* @see org.apache.mesos.ExecutorDriver
* @see org.apache.mesos.MesosSchedulerDriver
*/
@Override
public void registered(ExecutorDriver executorDriver, Protos.ExecutorInfo executorInfo, Protos.FrameworkInfo frameworkInfo, Protos.SlaveInfo slaveInfo) {
LOGGER.info("Executor Registered: " + executorInfo.getName());
this.executorInfo = executorInfo;
this.frameworkInfo = frameworkInfo;
this.slaveInfo = slaveInfo;
}
/**
* Invoked when the executor re-registers with a restarted slave.
*
* @param executorDriver
* @param slaveInfo Describes the slave that will be used to launch
* the tasks for this executor.
* @see org.apache.mesos.ExecutorDriver
*/
@Override
public void reregistered(ExecutorDriver executorDriver, Protos.SlaveInfo slaveInfo) {
LOGGER.info("Re-registered with mesos slave: " + slaveInfo.getHostname());
}
/**
* Invoked when the executor becomes "disconnected" from the slave
* (e.g., the slave is being restarted due to an upgrade).
*
* @param executorDriver
*/
@Override
public void disconnected(ExecutorDriver executorDriver) {
// TODO set timer and destroy server if slave doesn't come back?
LOGGER.info("Disconnected from Mesos slave");
}
/**
* Invoked when a task has been launched on this executor (initiated
* via {@link SchedulerDriver#launchTasks}. Note that this task can be
* realized with a thread, a process, or some simple computation,
* however, no other callbacks will be invoked on this executor
* until this callback has returned.
*
* @param executorDriver
* @param taskInfo
* @see org.apache.mesos.ExecutorDriver
* @see org.apache.mesos.Protos.TaskInfo
*/
@Override
public void launchTask(ExecutorDriver executorDriver, Protos.TaskInfo taskInfo) {
LOGGER.info("Launch TaskInfo " + taskInfo);
LOGGER.info("Launch Task Requested: " + taskInfo.getCommand());
this.taskInfo = taskInfo;
// If there is another executor then exit?!
checkForRunningExecutor();
// get server profile
byte[] profileBytes = taskInfo.getData().toByteArray();
ServerProfile profile = null;
try {
profile = mapper.readValue(profileBytes, ServerProfile.class);
} catch (IOException e) {
LOGGER.error("Unable to deserialze ServerProfile");
// TODO what do?
e.printStackTrace();
}
//TODO get jvmArgs and args from protobuf?
List<String> jvmArgs = new ArrayList<>();
String[] args = new String[0];
try {
// accumulo-site.xml is sent in from scheduler
// reify the xml and add in the tserver memory settings before writing | AccumuloSiteXml siteXml = new AccumuloSiteXml(); | 2 |
dnbn/smbtv | app/src/main/java/com/smbtv/ui/activity/fragment/MainFragmentUIBuilder.java | [
"public class SMBShareDelegate {\n\n private SMBShareDAO mDao;\n\n public SMBShareDelegate() {\n\n Context context = ApplicationDelegate.getContext();\n this.mDao = new SMBShareDAO(context);\n }\n\n public void delete(SMBShare share) {\n\n mDao.delete(share);\n }\n\n public void insert(SMBShare share) {\n\n mDao.insert(share);\n }\n\n public List<SMBShare> findAll() {\n\n return mDao.findAll();\n }\n\n public SMBShare findById(int idShare) {\n\n return mDao.findById(idShare);\n }\n\n public void update(SMBShare share) {\n\n mDao.update(share);\n }\n}",
"public class SMBShare {\n\n public enum AccessMode {\n READ_ONLY(0),\n WRITEABLE(1);\n\n private final int value;\n\n AccessMode(int value) {\n\n this.value = value;\n }\n\n public String toStringValue() {\n\n return Integer.toString(this.value);\n }\n }\n\n private int id;\n private String path;\n private String name;\n private AccessMode accessMode;\n\n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n public String getPath() {\n return path;\n }\n\n public void setPath(String path) {\n this.path = path;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public AccessMode getAccessMode() {\n return accessMode;\n }\n\n public void setAccessMode(AccessMode accessMode) {\n this.accessMode = accessMode;\n }\n}",
"public class SMBServerDelegate {\n\n private static final String TAG = SMBServerDelegate.class.getName();\n private static SMBServerDelegate INSTANCE = null;\n\n private PersistentServerConfiguration mCfg;\n private SMBServer mSmbServer;\n private InternalServerListener mSMBListener;\n private int mSMBServerState = -1;\n\n private SMBServerDelegate() {\n\n try {\n mCfg = new PersistentServerConfiguration();\n } catch (Exception e) {\n\n Log.e(TAG, Log.getStackTraceString(e));\n throw new ServiceInstancationException(e);\n }\n }\n\n public static SMBServerDelegate getInstance() {\n\n if (INSTANCE == null) {\n INSTANCE = new SMBServerDelegate();\n }\n return INSTANCE;\n }\n\n public void startServer(ServerListener listener) {\n\n try {\n mSMBListener = new InternalServerListener(listener);\n\n NetBIOSNameServer netBIOSNameServer = new NetBIOSNameServer(mCfg);\n\n mCfg.addServer(netBIOSNameServer);\n mSmbServer = new SMBServer(mCfg);\n mCfg.addServer(mSmbServer);\n\n mSmbServer.addServerListener(mSMBListener);\n\n for (int i = 0; i < mCfg.numberOfServers(); i++) {\n NetworkServer server = mCfg.getServer(i);\n server.startServer();\n }\n\n } catch (Exception e) {\n\n Log.e(TAG, Log.getStackTraceString(e));\n throw new ServiceInstancationException(e);\n }\n }\n\n public ServerInfo getServerInfo() {\n\n ServerInfo serverInfo = new ServerInfo();\n\n serverInfo.setName(mSmbServer.getServerName());\n serverInfo.setPort(mSmbServer.getCIFSConfiguration().getTcpipSMBPort());\n serverInfo.setDomain(mSmbServer.getCIFSConfiguration().getDomainName());\n serverInfo.setAddresses(mSmbServer.getServerAddresses());\n\n return serverInfo;\n }\n\n public boolean isServerStarting() {\n\n return mSMBServerState == ServerListener.ServerStartup;\n }\n\n public boolean isServerActive() {\n\n return mSmbServer != null && mSmbServer.isActive();\n }\n\n public void restartServer() {\n\n ServerListener listener = null;\n\n if (isServerActive()) {\n stopServer();\n listener = mSMBListener;\n }\n\n startServer(listener);\n }\n\n public void stopServer() {\n\n for (int i = 0; i < mCfg.numberOfServers(); i++) {\n NetworkServer server = mCfg.getServer(i);\n server.shutdownServer(true);\n }\n }\n\n public void registerShare(SMBShare share) {\n\n mCfg.registerShare(share);\n }\n\n public void removeShare(SMBShare share) {\n\n mCfg.unregisterShare(share);\n }\n\n public void renameShare(int id, String newName) {\n\n mCfg.renameShare(id, newName);\n }\n\n private class InternalServerListener implements ServerListener {\n\n private ServerListener mDelegate;\n\n public InternalServerListener(ServerListener listener) {\n\n this.mDelegate = listener;\n }\n\n @Override\n public void serverStatusEvent(NetworkServer networkServer, int state) {\n\n mSMBServerState = state;\n\n if (this.mDelegate != null) {\n this.mDelegate.serverStatusEvent(networkServer, state);\n }\n }\n }\n}",
"public enum MenuAction {\n\n Settings,\n StartServer,\n StopServer,\n AddShare,\n Share\n}",
"public class MenuItem {\n\n private MenuAction mAction;\n private String mTitle;\n private String mDetail;\n private int mIcon;\n private Object mElement;\n\n public MenuItem() {\n\n super();\n }\n\n public MenuItem(MenuAction action, String title, int icon) {\n this.mAction = action;\n this.mTitle = title;\n this.mIcon = icon;\n }\n\n public String getTitle() {\n return mTitle;\n }\n\n public void setTitle(String text) {\n this.mTitle = text;\n }\n\n public MenuAction getAction() {\n return mAction;\n }\n\n public void setAction(MenuAction action) {\n this.mAction = action;\n }\n\n public String getDetail() {\n return mDetail;\n }\n\n public void setDetail(String mDetail) {\n this.mDetail = mDetail;\n }\n\n public int getIcon() {\n return mIcon;\n }\n\n public void setIcon(int icon) {\n this.mIcon = icon;\n }\n\n public Object getElement() {\n return mElement;\n }\n\n public void setElement(Object mElement) {\n this.mElement = mElement;\n }\n}",
"public class MenuItemPresenter extends Presenter {\n\n private static final String TAG = MenuItemPresenter.class.getName();\n\n private static final int IMAGE_WIDTH = 350;\n private static final int IMAGE_HEIGHT = 400;\n\n private Drawable mDefaultCardImage;\n\n @Override\n public ViewHolder onCreateViewHolder(ViewGroup parent) {\n\n Log.d(TAG, \"onCreateViewHolder\");\n\n final Context context = parent.getContext();\n final IconCardView iconCardView = new IconCardView(context, R.style.IconCardStyle);\n\n iconCardView.setFocusable(true);\n iconCardView.setFocusableInTouchMode(true);\n iconCardView.setMainImageDimensions(IMAGE_WIDTH, IMAGE_HEIGHT);\n\n return new ViewHolder(iconCardView);\n }\n\n @Override\n public void onBindViewHolder(Presenter.ViewHolder viewHolder, Object item) {\n\n Log.d(TAG, \"onBindViewHolder\");\n\n if (!(item instanceof MenuItem)) {\n\n throw new IllegalArgumentException(\"item must be instance of MenuItem, not \" + item.getClass().getName());\n }\n\n IconCardView iconCardView = (IconCardView) viewHolder.view;\n\n MenuItem menuItem = (MenuItem) item;\n iconCardView.setTitleText(menuItem.getTitle());\n iconCardView.setDetailText(menuItem.getDetail());\n\n final Context context = iconCardView.getContext();\n final Drawable icon = ContextCompat.getDrawable(context, menuItem.getIcon());\n iconCardView.setIcon(icon);\n }\n\n @Override\n public void onUnbindViewHolder(Presenter.ViewHolder viewHolder) {\n\n Log.d(TAG, \"onUnbindViewHolder\");\n }\n}"
] | import android.app.Activity;
import android.support.v17.leanback.widget.ArrayObjectAdapter;
import android.support.v17.leanback.widget.HeaderItem;
import android.support.v17.leanback.widget.ListRow;
import android.util.Log;
import com.smbtv.R;
import com.smbtv.delegate.SMBShareDelegate;
import com.smbtv.model.SMBShare;
import com.smbtv.delegate.SMBServerDelegate;
import com.smbtv.ui.components.MenuAction;
import com.smbtv.ui.components.MenuItem;
import com.smbtv.ui.components.MenuItemPresenter;
import java.util.List; | package com.smbtv.ui.activity.fragment;
public class MainFragmentUIBuilder {
private static final String TAG = MainFragmentUIBuilder.class.getSimpleName();
private Activity mParent;
private int cpt;
public MainFragmentUIBuilder(Activity parent) {
this.mParent = parent;
}
public ListRow buildShares() {
Log.d(TAG, "buildShares");
ArrayObjectAdapter rowAdapter = new ArrayObjectAdapter(new MenuItemPresenter());
| rowAdapter.add(new MenuItem(MenuAction.AddShare, getLabel(R.string.add), R.drawable.ic_add)); | 3 |
EBIvariation/eva-ws | eva-release/src/main/java/uk/ac/ebi/eva/release/services/ReleaseStatsService.java | [
"public class ReleaseStatsPerSpeciesDto {\n\n @Id\n private int taxonomyId;\n\n @Id\n private int releaseVersion;\n\n private String scientificName;\n\n private String releaseFolder;\n\n private Long currentRs;\n\n private Long multiMappedRs;\n\n private Long mergedRs;\n\n private Long deprecatedRs;\n\n private Long mergedDeprecatedRs;\n\n private Long unmappedRs;\n\n private Long newCurrentRs;\n\n private Long newMultiMappedRs;\n\n private Long newMergedRs;\n\n private Long newDeprecatedRs;\n\n private Long newMergedDeprecatedRs;\n\n private Long newUnmappedRs;\n\n private Long newSsClustered;\n\n private String releaseLink;\n\n private String taxonomyLink;\n\n public ReleaseStatsPerSpeciesDto() {\n }\n\n public int getTaxonomyId() {\n return taxonomyId;\n }\n\n public void setTaxonomyId(int taxonomyId) {\n this.taxonomyId = taxonomyId;\n }\n\n public int getReleaseVersion() {\n return releaseVersion;\n }\n\n public void setReleaseVersion(int releaseVersion) {\n this.releaseVersion = releaseVersion;\n }\n\n public String getScientificName() {\n return scientificName;\n }\n\n public void setScientificName(String scientificName) {\n this.scientificName = scientificName;\n }\n\n public String getReleaseFolder() {\n return releaseFolder;\n }\n\n public void setReleaseFolder(String releaseFolder) {\n this.releaseFolder = releaseFolder;\n }\n\n public Long getCurrentRs() {\n return currentRs;\n }\n\n public void setCurrentRs(Long currentRs) {\n this.currentRs = currentRs;\n }\n\n public Long getMultiMappedRs() {\n return multiMappedRs;\n }\n\n public void setMultiMappedRs(Long multiMappedRs) {\n this.multiMappedRs = multiMappedRs;\n }\n\n public Long getMergedRs() {\n return mergedRs;\n }\n\n public void setMergedRs(Long mergedRs) {\n this.mergedRs = mergedRs;\n }\n\n public Long getDeprecatedRs() {\n return deprecatedRs;\n }\n\n public void setDeprecatedRs(Long deprecatedRs) {\n this.deprecatedRs = deprecatedRs;\n }\n\n public Long getMergedDeprecatedRs() {\n return mergedDeprecatedRs;\n }\n\n public void setMergedDeprecatedRs(Long mergedDeprecatedRs) {\n this.mergedDeprecatedRs = mergedDeprecatedRs;\n }\n\n public Long getUnmappedRs() {\n return unmappedRs;\n }\n\n public void setUnmappedRs(Long unmappedRs) {\n this.unmappedRs = unmappedRs;\n }\n\n public Long getNewCurrentRs() {\n return newCurrentRs;\n }\n\n public void setNewCurrentRs(Long newCurrentRs) {\n this.newCurrentRs = newCurrentRs;\n }\n\n public Long getNewMultiMappedRs() {\n return newMultiMappedRs;\n }\n\n public void setNewMultiMappedRs(Long newMultiMappedRs) {\n this.newMultiMappedRs = newMultiMappedRs;\n }\n\n public Long getNewMergedRs() {\n return newMergedRs;\n }\n\n public void setNewMergedRs(Long newMergedRs) {\n this.newMergedRs = newMergedRs;\n }\n\n public Long getNewDeprecatedRs() {\n return newDeprecatedRs;\n }\n\n public void setNewDeprecatedRs(Long newDeprecatedRs) {\n this.newDeprecatedRs = newDeprecatedRs;\n }\n\n public Long getNewMergedDeprecatedRs() {\n return newMergedDeprecatedRs;\n }\n\n public void setNewMergedDeprecatedRs(Long newMergedDeprecatedRs) {\n this.newMergedDeprecatedRs = newMergedDeprecatedRs;\n }\n\n public Long getNewUnmappedRs() {\n return newUnmappedRs;\n }\n\n public void setNewUnmappedRs(Long newUnmappedRs) {\n this.newUnmappedRs = newUnmappedRs;\n }\n\n public Long getNewSsClustered() {\n return newSsClustered;\n }\n\n public void setNewSsClustered(Long newSsClustered) {\n this.newSsClustered = newSsClustered;\n }\n\n public String getReleaseLink() {\n return releaseLink;\n }\n\n public void setReleaseLink(String releaseLink) {\n this.releaseLink = releaseLink;\n }\n\n public String getTaxonomyLink() {\n return taxonomyLink;\n }\n\n public void setTaxonomyLink(String taxonomyLink) {\n this.taxonomyLink = taxonomyLink;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n ReleaseStatsPerSpeciesDto that = (ReleaseStatsPerSpeciesDto) o;\n return taxonomyId == that.taxonomyId &&\n releaseVersion == that.releaseVersion &&\n Objects.equals(scientificName, that.scientificName) &&\n Objects.equals(releaseFolder, that.releaseFolder) &&\n Objects.equals(currentRs, that.currentRs) &&\n Objects.equals(multiMappedRs, that.multiMappedRs) &&\n Objects.equals(mergedRs, that.mergedRs) &&\n Objects.equals(deprecatedRs, that.deprecatedRs) &&\n Objects.equals(mergedDeprecatedRs, that.mergedDeprecatedRs) &&\n Objects.equals(unmappedRs, that.unmappedRs) &&\n Objects.equals(newCurrentRs, that.newCurrentRs) &&\n Objects.equals(newMultiMappedRs, that.newMultiMappedRs) &&\n Objects.equals(newMergedRs, that.newMergedRs) &&\n Objects.equals(newDeprecatedRs, that.newDeprecatedRs) &&\n Objects.equals(newMergedDeprecatedRs, that.newMergedDeprecatedRs) &&\n Objects.equals(newUnmappedRs, that.newUnmappedRs) &&\n Objects.equals(newSsClustered, that.newSsClustered) &&\n Objects.equals(releaseLink, that.releaseLink) &&\n Objects.equals(taxonomyLink, that.taxonomyLink);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(taxonomyId, releaseVersion, scientificName, releaseFolder, currentRs, multiMappedRs,\n mergedRs,\n deprecatedRs, mergedDeprecatedRs, unmappedRs, newCurrentRs, newMultiMappedRs, newMergedRs,\n newDeprecatedRs, newMergedDeprecatedRs, newUnmappedRs, newSsClustered, releaseLink,\n taxonomyLink);\n }\n\n @Override\n public String toString() {\n return \"ReleaseStatsPerSpeciesDto{\" +\n \"taxonomyId=\" + taxonomyId +\n \", releaseVersion=\" + releaseVersion +\n \", scientificName='\" + scientificName + '\\'' +\n \", releaseFolder='\" + releaseFolder + '\\'' +\n \", currentRs=\" + currentRs +\n \", multiMappedRs=\" + multiMappedRs +\n \", mergedRs=\" + mergedRs +\n \", deprecatedRs=\" + deprecatedRs +\n \", mergedDeprecatedRs=\" + mergedDeprecatedRs +\n \", unmappedRs=\" + unmappedRs +\n \", newCurrentRs=\" + newCurrentRs +\n \", newMultiMappedRs=\" + newMultiMappedRs +\n \", newMergedRs=\" + newMergedRs +\n \", newDeprecatedRs=\" + newDeprecatedRs +\n \", newMergedDeprecatedRs=\" + newMergedDeprecatedRs +\n \", newUnmappedRs=\" + newUnmappedRs +\n \", newSsClustered=\" + newSsClustered +\n \", releaseLink='\" + releaseLink + '\\'' +\n \", taxonomyLink='\" + taxonomyLink + '\\'' +\n '}';\n }\n}",
"@Entity\n@Table(name = \"release_rs\")\npublic class ReleaseInfo {\n\n @Id\n private int releaseVersion;\n\n private LocalDateTime releaseDate;\n\n private String releaseDescription;\n\n private String releaseFtp;\n\n public ReleaseInfo() {\n }\n\n public int getReleaseVersion() {\n return releaseVersion;\n }\n\n public void setReleaseVersion(int releaseVersion) {\n this.releaseVersion = releaseVersion;\n }\n\n public LocalDateTime getReleaseDate() {\n return releaseDate;\n }\n\n public void setReleaseDate(LocalDateTime releaseDate) {\n this.releaseDate = releaseDate;\n }\n\n public String getReleaseDescription() {\n return releaseDescription;\n }\n\n public void setReleaseDescription(String releaseDescription) {\n this.releaseDescription = releaseDescription;\n }\n\n public String getReleaseFtp() {\n return releaseFtp;\n }\n\n public void setReleaseFtp(String releaseFtp) {\n this.releaseFtp = releaseFtp;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n ReleaseInfo that = (ReleaseInfo) o;\n return releaseVersion == that.releaseVersion &&\n Objects.equals(releaseDate, that.releaseDate) &&\n Objects.equals(releaseDescription, that.releaseDescription) &&\n Objects.equals(releaseFtp, that.releaseFtp);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(releaseVersion, releaseDate, releaseDescription, releaseFtp);\n }\n\n @Override\n public String toString() {\n return \"ReleaseInfo{\" +\n \"releaseVersion=\" + releaseVersion +\n \", releaseDate=\" + releaseDate +\n \", releaseDescription='\" + releaseDescription + '\\'' +\n \", releaseFtp='\" + releaseFtp + '\\'' +\n '}';\n }\n}",
"@Entity\n@IdClass(ReleaseStartsPerSpeciesPK.class)\n@Table(name = \"release_rs_statistics_per_species\")\npublic class ReleaseStatsPerSpecies {\n\n @Id\n private int taxonomyId;\n\n @Id\n private int releaseVersion;\n\n private String scientificName;\n\n private String releaseFolder;\n\n private Long currentRs;\n\n private Long multiMappedRs;\n\n private Long mergedRs;\n\n private Long deprecatedRs;\n\n private Long mergedDeprecatedRs;\n\n private Long unmappedRs;\n\n private Long newCurrentRs;\n\n private Long newMultiMappedRs;\n\n private Long newMergedRs;\n\n private Long newDeprecatedRs;\n\n private Long newMergedDeprecatedRs;\n\n private Long newUnmappedRs;\n\n private Long newSsClustered;\n\n public ReleaseStatsPerSpecies() {\n }\n\n public int getTaxonomyId() {\n return taxonomyId;\n }\n\n public void setTaxonomyId(int taxonomyId) {\n this.taxonomyId = taxonomyId;\n }\n\n public int getReleaseVersion() {\n return releaseVersion;\n }\n\n public void setReleaseVersion(int releaseVersion) {\n this.releaseVersion = releaseVersion;\n }\n\n public String getScientificName() {\n return scientificName;\n }\n\n public void setScientificName(String scientificName) {\n this.scientificName = scientificName;\n }\n\n public String getReleaseFolder() {\n return releaseFolder;\n }\n\n public void setReleaseFolder(String releaseFolder) {\n this.releaseFolder = releaseFolder;\n }\n\n public Long getCurrentRs() {\n return currentRs;\n }\n\n public void setCurrentRs(Long currentRs) {\n this.currentRs = currentRs;\n }\n\n public Long getMultiMappedRs() {\n return multiMappedRs;\n }\n\n public void setMultiMappedRs(Long multiMappedRs) {\n this.multiMappedRs = multiMappedRs;\n }\n\n public Long getMergedRs() {\n return mergedRs;\n }\n\n public void setMergedRs(Long mergedRs) {\n this.mergedRs = mergedRs;\n }\n\n public Long getDeprecatedRs() {\n return deprecatedRs;\n }\n\n public void setDeprecatedRs(Long deprecatedRs) {\n this.deprecatedRs = deprecatedRs;\n }\n\n public Long getMergedDeprecatedRs() {\n return mergedDeprecatedRs;\n }\n\n public void setMergedDeprecatedRs(Long mergedDeprecatedRs) {\n this.mergedDeprecatedRs = mergedDeprecatedRs;\n }\n\n public Long getUnmappedRs() {\n return unmappedRs;\n }\n\n public void setUnmappedRs(Long unmappedRs) {\n this.unmappedRs = unmappedRs;\n }\n\n public Long getNewCurrentRs() {\n return newCurrentRs;\n }\n\n public void setNewCurrentRs(Long newCurrentRs) {\n this.newCurrentRs = newCurrentRs;\n }\n\n public Long getNewMultiMappedRs() {\n return newMultiMappedRs;\n }\n\n public void setNewMultiMappedRs(Long newMultiMappedRs) {\n this.newMultiMappedRs = newMultiMappedRs;\n }\n\n public Long getNewMergedRs() {\n return newMergedRs;\n }\n\n public void setNewMergedRs(Long newMergedRs) {\n this.newMergedRs = newMergedRs;\n }\n\n public Long getNewDeprecatedRs() {\n return newDeprecatedRs;\n }\n\n public void setNewDeprecatedRs(Long newDeprecatedRs) {\n this.newDeprecatedRs = newDeprecatedRs;\n }\n\n public Long getNewMergedDeprecatedRs() {\n return newMergedDeprecatedRs;\n }\n\n public void setNewMergedDeprecatedRs(Long newMergedDeprecatedRs) {\n this.newMergedDeprecatedRs = newMergedDeprecatedRs;\n }\n\n public Long getNewUnmappedRs() {\n return newUnmappedRs;\n }\n\n public void setNewUnmappedRs(Long newUnmappedRs) {\n this.newUnmappedRs = newUnmappedRs;\n }\n\n public Long getNewSsClustered() {\n return newSsClustered;\n }\n\n public void setNewSsClustered(Long newSsClustered) {\n this.newSsClustered = newSsClustered;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n ReleaseStatsPerSpecies that = (ReleaseStatsPerSpecies) o;\n return taxonomyId == that.taxonomyId &&\n releaseVersion == that.releaseVersion &&\n Objects.equals(scientificName, that.scientificName) &&\n Objects.equals(releaseFolder, that.releaseFolder) &&\n Objects.equals(currentRs, that.currentRs) &&\n Objects.equals(multiMappedRs, that.multiMappedRs) &&\n Objects.equals(mergedRs, that.mergedRs) &&\n Objects.equals(deprecatedRs, that.deprecatedRs) &&\n Objects.equals(mergedDeprecatedRs, that.mergedDeprecatedRs) &&\n Objects.equals(unmappedRs, that.unmappedRs) &&\n Objects.equals(newCurrentRs, that.newCurrentRs) &&\n Objects.equals(newMultiMappedRs, that.newMultiMappedRs) &&\n Objects.equals(newMergedRs, that.newMergedRs) &&\n Objects.equals(newDeprecatedRs, that.newDeprecatedRs) &&\n Objects.equals(newMergedDeprecatedRs, that.newMergedDeprecatedRs) &&\n Objects.equals(newUnmappedRs, that.newUnmappedRs) &&\n Objects.equals(newSsClustered, that.newSsClustered);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(taxonomyId, releaseVersion, scientificName, releaseFolder, currentRs, multiMappedRs,\n mergedRs,\n deprecatedRs, mergedDeprecatedRs, unmappedRs, newCurrentRs, newMultiMappedRs, newMergedRs,\n newDeprecatedRs, newMergedDeprecatedRs, newUnmappedRs, newSsClustered);\n }\n\n @Override\n public String toString() {\n return \"ReleaseStatsPerSpecies{\" +\n \"taxonomyId=\" + taxonomyId +\n \", releaseVersion=\" + releaseVersion +\n \", scientificName='\" + scientificName + '\\'' +\n \", releaseFolder='\" + releaseFolder + '\\'' +\n \", currentRs=\" + currentRs +\n \", multiMappedRs=\" + multiMappedRs +\n \", mergedRs=\" + mergedRs +\n \", deprecatedRs=\" + deprecatedRs +\n \", mergedDeprecatedRs=\" + mergedDeprecatedRs +\n \", unmappedRs=\" + unmappedRs +\n \", newCurrentRs=\" + newCurrentRs +\n \", newMultiMappedRs=\" + newMultiMappedRs +\n \", newMergedRs=\" + newMergedRs +\n \", newDeprecatedRs=\" + newDeprecatedRs +\n \", newMergedDeprecatedRs=\" + newMergedDeprecatedRs +\n \", newUnmappedRs=\" + newUnmappedRs +\n \", newSsClustered=\" + newSsClustered +\n '}';\n }\n}",
"@Repository\npublic interface ReleaseInfoRepository extends CrudRepository<ReleaseInfo, Integer> {\n\n Optional<ReleaseInfo> findFirstByOrderByReleaseDateDesc();\n}",
"@Repository\npublic interface ReleaseStatsPerSpeciesRepository extends CrudRepository<ReleaseStatsPerSpecies,\n ReleaseStartsPerSpeciesPK> {\n\n Iterable<ReleaseStatsPerSpecies> findAllByReleaseVersion(int releaseVersion);\n\n //All release data excluding rows with only unmapped data\n Iterable<ReleaseStatsPerSpecies> findByCurrentRsNotAndMultiMappedRsNotAndMergedRsNotAndDeprecatedRsNotAndMergedDeprecatedRsNotAndUnmappedRsGreaterThan(\n long currentRs, long multiMappedRs, long mergedRs, long deprecatedRs, long mergedDeprecatedRs,\n long unmappedRs);\n\n //Data by release version excluding rows with only unmapped data\n Iterable<ReleaseStatsPerSpecies> findByReleaseVersionAndCurrentRsNotAndMultiMappedRsNotAndMergedRsNotAndDeprecatedRsNotAndMergedDeprecatedRsNotAndUnmappedRsGreaterThan(\n int releaseVersion, long currentRs, long multiMappedRs, long mergedRs, long deprecatedRs,\n long mergedDeprecatedRs, long unmappedRs);\n\n Iterable<ReleaseStatsPerSpecies> findByNewCurrentRsGreaterThan(long currentRs);\n\n Iterable<ReleaseStatsPerSpecies> findByReleaseVersionAndNewCurrentRsGreaterThan(int releaseVersion, long currentRs);\n}"
] | import org.springframework.stereotype.Service;
import uk.ac.ebi.eva.release.dto.ReleaseStatsPerSpeciesDto;
import uk.ac.ebi.eva.release.models.ReleaseInfo;
import uk.ac.ebi.eva.release.models.ReleaseStatsPerSpecies;
import uk.ac.ebi.eva.release.repositories.ReleaseInfoRepository;
import uk.ac.ebi.eva.release.repositories.ReleaseStatsPerSpeciesRepository;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; | /*
* Copyright 2020 EMBL - European Bioinformatics Institute
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.ac.ebi.eva.release.services;
@Service
public class ReleaseStatsService {
private static final String SPECIES_DIRECTORY = "by_species/";
private static final String TAXONOMY_URL = "https://www.ebi.ac.uk/ena/browser/view/Taxon:";
| private final ReleaseStatsPerSpeciesRepository releaseStatsPerSpeciesRepository; | 4 |
ypresto/miniguava | miniguava-collect-immutables/src/main/java/net/ypresto/miniguava/collect/immutables/InternalUtils.java | [
"public static <T> T checkNotNull(T reference) {\n if (reference == null) {\n throw new NullPointerException();\n }\n return reference;\n}",
"public class Joiner {\n /**\n * Returns a joiner which automatically places {@code separator} between consecutive elements.\n */\n @CheckReturnValue\n public static Joiner on(String separator) {\n return new Joiner(separator);\n }\n\n /**\n * Returns a joiner which automatically places {@code separator} between consecutive elements.\n */\n @CheckReturnValue\n public static Joiner on(char separator) {\n return new Joiner(String.valueOf(separator));\n }\n\n private final String separator;\n\n private Joiner(String separator) {\n this.separator = checkNotNull(separator);\n }\n\n private Joiner(Joiner prototype) {\n this.separator = prototype.separator;\n }\n\n /**\n * Appends the string representation of each of {@code parts}, using the previously configured\n * separator between each, to {@code appendable}.\n */\n public <A extends Appendable> A appendTo(A appendable, Iterable<?> parts) throws IOException {\n return appendTo(appendable, parts.iterator());\n }\n\n /**\n * Appends the string representation of each of {@code parts}, using the previously configured\n * separator between each, to {@code appendable}.\n *\n * @since 11.0\n */\n public <A extends Appendable> A appendTo(A appendable, Iterator<?> parts) throws IOException {\n checkNotNull(appendable);\n if (parts.hasNext()) {\n appendable.append(toString(parts.next()));\n while (parts.hasNext()) {\n appendable.append(separator);\n appendable.append(toString(parts.next()));\n }\n }\n return appendable;\n }\n\n /**\n * Appends the string representation of each of {@code parts}, using the previously configured\n * separator between each, to {@code appendable}.\n */\n public final <A extends Appendable> A appendTo(A appendable, Object[] parts) throws IOException {\n return appendTo(appendable, Arrays.asList(parts));\n }\n\n /**\n * Appends to {@code appendable} the string representation of each of the remaining arguments.\n */\n public final <A extends Appendable> A appendTo(\n A appendable, @Nullable Object first, @Nullable Object second, Object... rest)\n throws IOException {\n return appendTo(appendable, iterable(first, second, rest));\n }\n\n /**\n * Appends the string representation of each of {@code parts}, using the previously configured\n * separator between each, to {@code builder}. Identical to {@link #appendTo(Appendable,\n * Iterable)}, except that it does not throw {@link IOException}.\n */\n public final StringBuilder appendTo(StringBuilder builder, Iterable<?> parts) {\n return appendTo(builder, parts.iterator());\n }\n\n /**\n * Appends the string representation of each of {@code parts}, using the previously configured\n * separator between each, to {@code builder}. Identical to {@link #appendTo(Appendable,\n * Iterable)}, except that it does not throw {@link IOException}.\n *\n * @since 11.0\n */\n public final StringBuilder appendTo(StringBuilder builder, Iterator<?> parts) {\n try {\n appendTo((Appendable) builder, parts);\n } catch (IOException impossible) {\n throw new AssertionError(impossible);\n }\n return builder;\n }\n\n /**\n * Appends the string representation of each of {@code parts}, using the previously configured\n * separator between each, to {@code builder}. Identical to {@link #appendTo(Appendable,\n * Iterable)}, except that it does not throw {@link IOException}.\n */\n public final StringBuilder appendTo(StringBuilder builder, Object[] parts) {\n return appendTo(builder, Arrays.asList(parts));\n }\n\n /**\n * Appends to {@code builder} the string representation of each of the remaining arguments.\n * Identical to {@link #appendTo(Appendable, Object, Object, Object...)}, except that it does not\n * throw {@link IOException}.\n */\n public final StringBuilder appendTo(\n StringBuilder builder, @Nullable Object first, @Nullable Object second, Object... rest) {\n return appendTo(builder, iterable(first, second, rest));\n }\n\n /**\n * Returns a string containing the string representation of each of {@code parts}, using the\n * previously configured separator between each.\n */\n @CheckReturnValue\n public final String join(Iterable<?> parts) {\n return join(parts.iterator());\n }\n\n /**\n * Returns a string containing the string representation of each of {@code parts}, using the\n * previously configured separator between each.\n *\n * @since 11.0\n */\n @CheckReturnValue\n public final String join(Iterator<?> parts) {\n return appendTo(new StringBuilder(), parts).toString();\n }\n\n /**\n * Returns a string containing the string representation of each of {@code parts}, using the\n * previously configured separator between each.\n */\n @CheckReturnValue\n public final String join(Object[] parts) {\n return join(Arrays.asList(parts));\n }\n\n /**\n * Returns a string containing the string representation of each argument, using the previously\n * configured separator between each.\n */\n @CheckReturnValue\n public final String join(@Nullable Object first, @Nullable Object second, Object... rest) {\n return join(iterable(first, second, rest));\n }\n\n /**\n * Returns a joiner with the same behavior as this one, except automatically substituting {@code\n * nullText} for any provided null elements.\n */\n @CheckReturnValue\n public Joiner useForNull(final String nullText) {\n checkNotNull(nullText);\n return new Joiner(this) {\n @Override\n CharSequence toString(@Nullable Object part) {\n return (part == null) ? nullText : Joiner.this.toString(part);\n }\n\n @Override\n public Joiner useForNull(String nullText) {\n throw new UnsupportedOperationException(\"already specified useForNull\");\n }\n\n @Override\n public Joiner skipNulls() {\n throw new UnsupportedOperationException(\"already specified useForNull\");\n }\n };\n }\n\n /**\n * Returns a joiner with the same behavior as this joiner, except automatically skipping over any\n * provided null elements.\n */\n @CheckReturnValue\n public Joiner skipNulls() {\n return new Joiner(this) {\n @Override\n public <A extends Appendable> A appendTo(A appendable, Iterator<?> parts) throws IOException {\n checkNotNull(appendable, \"appendable\");\n checkNotNull(parts, \"parts\");\n while (parts.hasNext()) {\n Object part = parts.next();\n if (part != null) {\n appendable.append(Joiner.this.toString(part));\n break;\n }\n }\n while (parts.hasNext()) {\n Object part = parts.next();\n if (part != null) {\n appendable.append(separator);\n appendable.append(Joiner.this.toString(part));\n }\n }\n return appendable;\n }\n\n @Override\n public Joiner useForNull(String nullText) {\n throw new UnsupportedOperationException(\"already specified skipNulls\");\n }\n\n @Override\n public MapJoiner withKeyValueSeparator(String kvs) {\n throw new UnsupportedOperationException(\"can't use .skipNulls() with maps\");\n }\n };\n }\n\n /**\n * Returns a {@code MapJoiner} using the given key-value separator, and the same configuration as\n * this {@code Joiner} otherwise.\n */\n @CheckReturnValue\n public MapJoiner withKeyValueSeparator(String keyValueSeparator) {\n return new MapJoiner(this, keyValueSeparator);\n }\n\n /**\n * An object that joins map entries in the same manner as {@code Joiner} joins iterables and\n * arrays. Like {@code Joiner}, it is thread-safe and immutable.\n *\n * <p>In addition to operating on {@code Map} instances, {@code MapJoiner} can operate on {@code\n * Multimap} entries in two distinct modes:\n *\n * <ul>\n * <li>To output a separate entry for each key-value pair, pass {@code multimap.entries()} to a\n * {@code MapJoiner} method that accepts entries as input, and receive output of the form\n * {@code key1=A&key1=B&key2=C}.\n * <li>To output a single entry for each key, pass {@code multimap.asMap()} to a {@code MapJoiner}\n * method that accepts a map as input, and receive output of the form {@code\n * key1=[A, B]&key2=C}.\n * </ul>\n *\n * @since 2.0\n */\n public static final class MapJoiner {\n private final Joiner joiner;\n private final String keyValueSeparator;\n\n private MapJoiner(Joiner joiner, String keyValueSeparator) {\n this.joiner = joiner; // only \"this\" is ever passed, so don't checkNotNull\n this.keyValueSeparator = checkNotNull(keyValueSeparator);\n }\n\n /**\n * Appends the string representation of each entry of {@code map}, using the previously\n * configured separator and key-value separator, to {@code appendable}.\n */\n public <A extends Appendable> A appendTo(A appendable, Map<?, ?> map) throws IOException {\n return appendTo(appendable, map.entrySet());\n }\n\n /**\n * Appends the string representation of each entry of {@code map}, using the previously\n * configured separator and key-value separator, to {@code builder}. Identical to {@link\n * #appendTo(Appendable, Map)}, except that it does not throw {@link IOException}.\n */\n public StringBuilder appendTo(StringBuilder builder, Map<?, ?> map) {\n return appendTo(builder, map.entrySet());\n }\n\n /**\n * Returns a string containing the string representation of each entry of {@code map}, using the\n * previously configured separator and key-value separator.\n */\n @CheckReturnValue\n public String join(Map<?, ?> map) {\n return join(map.entrySet());\n }\n\n /**\n * Appends the string representation of each entry in {@code entries}, using the previously\n * configured separator and key-value separator, to {@code appendable}.\n *\n * @since 10.0\n */\n @Beta\n public <A extends Appendable> A appendTo(A appendable, Iterable<? extends Entry<?, ?>> entries)\n throws IOException {\n return appendTo(appendable, entries.iterator());\n }\n\n /**\n * Appends the string representation of each entry in {@code entries}, using the previously\n * configured separator and key-value separator, to {@code appendable}.\n *\n * @since 11.0\n */\n @Beta\n public <A extends Appendable> A appendTo(A appendable, Iterator<? extends Entry<?, ?>> parts)\n throws IOException {\n checkNotNull(appendable);\n if (parts.hasNext()) {\n Entry<?, ?> entry = parts.next();\n appendable.append(joiner.toString(entry.getKey()));\n appendable.append(keyValueSeparator);\n appendable.append(joiner.toString(entry.getValue()));\n while (parts.hasNext()) {\n appendable.append(joiner.separator);\n Entry<?, ?> e = parts.next();\n appendable.append(joiner.toString(e.getKey()));\n appendable.append(keyValueSeparator);\n appendable.append(joiner.toString(e.getValue()));\n }\n }\n return appendable;\n }\n\n /**\n * Appends the string representation of each entry in {@code entries}, using the previously\n * configured separator and key-value separator, to {@code builder}. Identical to {@link\n * #appendTo(Appendable, Iterable)}, except that it does not throw {@link IOException}.\n *\n * @since 10.0\n */\n @Beta\n public StringBuilder appendTo(StringBuilder builder, Iterable<? extends Entry<?, ?>> entries) {\n return appendTo(builder, entries.iterator());\n }\n\n /**\n * Appends the string representation of each entry in {@code entries}, using the previously\n * configured separator and key-value separator, to {@code builder}. Identical to {@link\n * #appendTo(Appendable, Iterable)}, except that it does not throw {@link IOException}.\n *\n * @since 11.0\n */\n @Beta\n public StringBuilder appendTo(StringBuilder builder, Iterator<? extends Entry<?, ?>> entries) {\n try {\n appendTo((Appendable) builder, entries);\n } catch (IOException impossible) {\n throw new AssertionError(impossible);\n }\n return builder;\n }\n\n /**\n * Returns a string containing the string representation of each entry in {@code entries}, using\n * the previously configured separator and key-value separator.\n *\n * @since 10.0\n */\n @Beta\n @CheckReturnValue\n public String join(Iterable<? extends Entry<?, ?>> entries) {\n return join(entries.iterator());\n }\n\n /**\n * Returns a string containing the string representation of each entry in {@code entries}, using\n * the previously configured separator and key-value separator.\n *\n * @since 11.0\n */\n @Beta\n @CheckReturnValue\n public String join(Iterator<? extends Entry<?, ?>> entries) {\n return appendTo(new StringBuilder(), entries).toString();\n }\n\n /**\n * Returns a map joiner with the same behavior as this one, except automatically substituting\n * {@code nullText} for any provided null keys or values.\n */\n @CheckReturnValue\n public MapJoiner useForNull(String nullText) {\n return new MapJoiner(joiner.useForNull(nullText), keyValueSeparator);\n }\n }\n\n CharSequence toString(Object part) {\n checkNotNull(part); // checkNotNull for GWT (do not optimize).\n return (part instanceof CharSequence) ? (CharSequence) part : part.toString();\n }\n\n private static Iterable<Object> iterable(\n final Object first, final Object second, final Object[] rest) {\n checkNotNull(rest);\n return new AbstractList<Object>() {\n @Override\n public int size() {\n return rest.length + 2;\n }\n\n @Override\n public Object get(int index) {\n switch (index) {\n case 0:\n return first;\n case 1:\n return second;\n default:\n return rest[index - 2];\n }\n }\n };\n }\n}",
"public static final class MapJoiner {\n private final Joiner joiner;\n private final String keyValueSeparator;\n\n private MapJoiner(Joiner joiner, String keyValueSeparator) {\n this.joiner = joiner; // only \"this\" is ever passed, so don't checkNotNull\n this.keyValueSeparator = checkNotNull(keyValueSeparator);\n }\n\n /**\n * Appends the string representation of each entry of {@code map}, using the previously\n * configured separator and key-value separator, to {@code appendable}.\n */\n public <A extends Appendable> A appendTo(A appendable, Map<?, ?> map) throws IOException {\n return appendTo(appendable, map.entrySet());\n }\n\n /**\n * Appends the string representation of each entry of {@code map}, using the previously\n * configured separator and key-value separator, to {@code builder}. Identical to {@link\n * #appendTo(Appendable, Map)}, except that it does not throw {@link IOException}.\n */\n public StringBuilder appendTo(StringBuilder builder, Map<?, ?> map) {\n return appendTo(builder, map.entrySet());\n }\n\n /**\n * Returns a string containing the string representation of each entry of {@code map}, using the\n * previously configured separator and key-value separator.\n */\n @CheckReturnValue\n public String join(Map<?, ?> map) {\n return join(map.entrySet());\n }\n\n /**\n * Appends the string representation of each entry in {@code entries}, using the previously\n * configured separator and key-value separator, to {@code appendable}.\n *\n * @since 10.0\n */\n @Beta\n public <A extends Appendable> A appendTo(A appendable, Iterable<? extends Entry<?, ?>> entries)\n throws IOException {\n return appendTo(appendable, entries.iterator());\n }\n\n /**\n * Appends the string representation of each entry in {@code entries}, using the previously\n * configured separator and key-value separator, to {@code appendable}.\n *\n * @since 11.0\n */\n @Beta\n public <A extends Appendable> A appendTo(A appendable, Iterator<? extends Entry<?, ?>> parts)\n throws IOException {\n checkNotNull(appendable);\n if (parts.hasNext()) {\n Entry<?, ?> entry = parts.next();\n appendable.append(joiner.toString(entry.getKey()));\n appendable.append(keyValueSeparator);\n appendable.append(joiner.toString(entry.getValue()));\n while (parts.hasNext()) {\n appendable.append(joiner.separator);\n Entry<?, ?> e = parts.next();\n appendable.append(joiner.toString(e.getKey()));\n appendable.append(keyValueSeparator);\n appendable.append(joiner.toString(e.getValue()));\n }\n }\n return appendable;\n }\n\n /**\n * Appends the string representation of each entry in {@code entries}, using the previously\n * configured separator and key-value separator, to {@code builder}. Identical to {@link\n * #appendTo(Appendable, Iterable)}, except that it does not throw {@link IOException}.\n *\n * @since 10.0\n */\n @Beta\n public StringBuilder appendTo(StringBuilder builder, Iterable<? extends Entry<?, ?>> entries) {\n return appendTo(builder, entries.iterator());\n }\n\n /**\n * Appends the string representation of each entry in {@code entries}, using the previously\n * configured separator and key-value separator, to {@code builder}. Identical to {@link\n * #appendTo(Appendable, Iterable)}, except that it does not throw {@link IOException}.\n *\n * @since 11.0\n */\n @Beta\n public StringBuilder appendTo(StringBuilder builder, Iterator<? extends Entry<?, ?>> entries) {\n try {\n appendTo((Appendable) builder, entries);\n } catch (IOException impossible) {\n throw new AssertionError(impossible);\n }\n return builder;\n }\n\n /**\n * Returns a string containing the string representation of each entry in {@code entries}, using\n * the previously configured separator and key-value separator.\n *\n * @since 10.0\n */\n @Beta\n @CheckReturnValue\n public String join(Iterable<? extends Entry<?, ?>> entries) {\n return join(entries.iterator());\n }\n\n /**\n * Returns a string containing the string representation of each entry in {@code entries}, using\n * the previously configured separator and key-value separator.\n *\n * @since 11.0\n */\n @Beta\n @CheckReturnValue\n public String join(Iterator<? extends Entry<?, ?>> entries) {\n return appendTo(new StringBuilder(), entries).toString();\n }\n\n /**\n * Returns a map joiner with the same behavior as this one, except automatically substituting\n * {@code nullText} for any provided null keys or values.\n */\n @CheckReturnValue\n public MapJoiner useForNull(String nullText) {\n return new MapJoiner(joiner.useForNull(nullText), keyValueSeparator);\n }\n}",
"public abstract class UnmodifiableIterator<E> implements Iterator<E> {\n /** Constructor for use by subclasses. */\n protected UnmodifiableIterator() {}\n\n /**\n * Guaranteed to throw an exception and leave the underlying data unmodified.\n *\n * @throws UnsupportedOperationException always\n * @deprecated Unsupported operation.\n */\n @Deprecated\n @Override\n public final void remove() {\n throw new UnsupportedOperationException();\n }\n}",
"@MiniGuavaSpecific(value = MiniGuavaSpecific.Reason.MOVED, from = \"collect package\")\npublic abstract class AbstractMapEntry<K, V> implements Entry<K, V> {\n\n @Override\n public abstract K getKey();\n\n @Override\n public abstract V getValue();\n\n @Override\n public V setValue(V value) {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public boolean equals(@Nullable Object object) {\n if (object instanceof Entry) {\n Entry<?, ?> that = (Entry<?, ?>) object;\n return Objects.equal(this.getKey(), that.getKey())\n && Objects.equal(this.getValue(), that.getValue());\n }\n return false;\n }\n\n @Override\n public int hashCode() {\n K k = getKey();\n V v = getValue();\n return ((k == null) ? 0 : k.hashCode()) ^ ((v == null) ? 0 : v.hashCode());\n }\n\n /**\n * Returns a string representation of the form {@code {key}={value}}.\n */\n @Override\n public String toString() {\n return getKey() + \"=\" + getValue();\n }\n}"
] | import static net.ypresto.miniguava.base.Preconditions.checkNotNull;
import net.ypresto.miniguava.annotations.MiniGuavaSpecific;
import net.ypresto.miniguava.base.Joiner;
import net.ypresto.miniguava.base.Joiner.MapJoiner;
import net.ypresto.miniguava.collect.UnmodifiableIterator;
import net.ypresto.miniguava.collect.internal.AbstractMapEntry;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import javax.annotation.Nullable; | /*
* Copyright (C) 2016 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.ypresto.miniguava.collect.immutables;
// miniguava: A collection of helper methods used in this module.
@MiniGuavaSpecific
class InternalUtils {
private InternalUtils() {}
/**
* The largest power of two that can be represented as an {@code int}.
*
* @since 10.0
*/
@MiniGuavaSpecific(value = MiniGuavaSpecific.Reason.COPIED, from = "primitives.Ints")
public static final int MAX_POWER_OF_TWO = 1 << (Integer.SIZE - 2);
// miniguava: From Sets.java, original method name: hashCodeImpl
/**
* An implementation for {@link Set#hashCode()}.
*/
static int setsHashCodeImpl(Set<?> s) {
int hashCode = 0;
for (Object o : s) {
hashCode += o != null ? o.hashCode() : 0;
hashCode = ~~hashCode;
// Needed to deal with unusual integer overflow in GWT.
}
return hashCode;
}
/**
* An implementation for {@link Set#equals(Object)}.
*/
@MiniGuavaSpecific(value = MiniGuavaSpecific.Reason.COPIED, from = "collect.Sets#equalsImpl")
static boolean setsEqualsImpl(Set<?> s, @Nullable Object object) {
if (s == object) {
return true;
}
if (object instanceof Set) {
Set<?> o = (Set<?>) object;
try {
return s.size() == o.size() && s.containsAll(o);
} catch (NullPointerException ignored) {
return false;
} catch (ClassCastException ignored) {
return false;
}
}
return false;
}
/**
* An implementation of {@link Map#equals}.
*/
@MiniGuavaSpecific(value = MiniGuavaSpecific.Reason.COPIED, from = "collect.Maps#equalsImpl")
static boolean mapsEqualsImpl(Map<?, ?> map, Object object) {
if (map == object) {
return true;
} else if (object instanceof Map) {
Map<?, ?> o = (Map<?, ?>) object;
return map.entrySet().equals(o.entrySet());
}
return false;
}
/**
* Returns best-effort-sized StringBuilder based on the given collection size.
*/
@MiniGuavaSpecific(value = MiniGuavaSpecific.Reason.COPIED, from = "collect.Collections2")
static StringBuilder newStringBuilderForCollection(int size) {
checkNonnegative(size, "size");
return new StringBuilder((int) Math.min(size * 8L, MAX_POWER_OF_TWO));
}
@MiniGuavaSpecific(value = MiniGuavaSpecific.Reason.COPIED, from = "collect.Collections2") | static final Joiner STANDARD_JOINER = Joiner.on(", ").useForNull("null"); | 1 |
iChun/Sync | src/main/java/me/ichun/mods/sync/common/tileentity/TileEntityDualVertical.java | [
"@SideOnly(Side.CLIENT)\npublic class SyncSkinManager {\n //Cache skins throughout TEs to avoid hitting the rate limit for skin session servers\n //Hold values for a longer time, so they are loaded fast if many TEs with the same player are loaded, or when loading other chunks with the same player\n //Skin loading priority: Cache(fastest), NetworkPlayer(only available when player is only and in same dim as shell, fast), SessionService(slow) and only available if UUID has been set\n private static final Cache<String, ResourceLocation> skinCache = CacheBuilder.newBuilder().expireAfterAccess(15, TimeUnit.MINUTES).build();\n private static final Cache<String, Set<Consumer<ResourceLocation>>> callbackMap = CacheBuilder.newBuilder().expireAfterWrite(15, TimeUnit.SECONDS).build();\n\n public static void get(String playerName, UUID playerUUID, Consumer<ResourceLocation> callback) {\n ResourceLocation loc = skinCache.getIfPresent(playerName);\n if (loc != null) {\n callback.accept(loc);\n return;\n }\n NetHandlerPlayClient networkHandler = Minecraft.getMinecraft().getConnection();\n NetworkPlayerInfo playerInfo = networkHandler == null ? null : networkHandler.getPlayerInfo(playerName);\n if (playerInfo != null) { //load from network player\n loc = playerInfo.getLocationSkin();\n if (loc != DefaultPlayerSkin.getDefaultSkin(playerInfo.getGameProfile().getId())) {\n callback.accept(loc);\n skinCache.put(playerName, loc);\n return;\n }\n }\n if (playerUUID == null) return; //Not much we can do here :(\n synchronized (callbackMap) {\n Set<Consumer<ResourceLocation>> consumers = callbackMap.getIfPresent(playerName);\n if (consumers == null) {\n //Make one call per user - again rate limit protection\n GameProfile profile = EntityHelper.getGameProfile(playerUUID, playerName); //This also queries auth server for details\n Minecraft.getMinecraft().getSkinManager().loadProfileTextures(profile, (type, location, profileTexture) -> {\n if (type == MinecraftProfileTexture.Type.SKIN) {\n synchronized (callbackMap) {\n Set<Consumer<ResourceLocation>> consumerSet = callbackMap.getIfPresent(playerName);\n if (consumerSet != null)\n consumerSet.forEach(consumer -> consumer.accept(location));\n callbackMap.invalidate(playerName);\n callbackMap.cleanUp();\n }\n skinCache.put(playerName, location);\n }\n }, true);\n HashSet<Consumer<ResourceLocation>> newSet = new HashSet<>();\n newSet.add(callback);\n callbackMap.put(playerName, newSet);\n } else {\n consumers.add(callback);\n }\n }\n }\n\n public static void invalidateCaches()\n {\n skinCache.invalidateAll();\n skinCache.cleanUp();\n callbackMap.invalidateAll();\n callbackMap.cleanUp();\n }\n}",
"@Mod(modid = Sync.MOD_ID, name = Sync.MOD_NAME,\n version = Sync.VERSION,\n certificateFingerprint = iChunUtil.CERT_FINGERPRINT,\n guiFactory = iChunUtil.GUI_CONFIG_FACTORY,\n dependencies = \"required-after:ichunutil@[\" + iChunUtil.VERSION_MAJOR + \".2.0,\" + (iChunUtil.VERSION_MAJOR + 1) + \".0.0);after:waila\",\n acceptableRemoteVersions = \"[\" + iChunUtil.VERSION_MAJOR +\".1.0,\" + iChunUtil.VERSION_MAJOR + \".2.0)\",\n acceptedMinecraftVersions = iChunUtil.MC_VERSION_RANGE\n)\npublic class Sync\n{\n public static final String VERSION = iChunUtil.VERSION_MAJOR +\".1.0\";\n\n public static final String MOD_NAME = \"Sync\";\n public static final String MOD_ID = \"sync\";\n\n @Instance(MOD_ID)\n public static Sync instance;\n\n @SidedProxy(clientSide = \"me.ichun.mods.sync.client.core.ProxyClient\", serverSide = \"me.ichun.mods.sync.common.core.ProxyCommon\")\n public static ProxyCommon proxy;\n\n public static final Logger LOGGER = LogManager.getLogger(MOD_NAME);\n\n public static final HashMap<Class, Integer> TREADMILL_ENTITY_HASH_MAP = new HashMap<>();\n\n public static EventHandlerServer eventHandlerServer;\n public static EventHandlerClient eventHandlerClient;\n\n public static CreativeTabs creativeTabSync;\n\n public static Config config;\n\n public static Block blockDualVertical;\n\n public static PacketChannel channel;\n public static Item itemShellConstructor, itemShellStorage, itemTreadmill;\n\n public static Item itemSyncCore;\n\n @EventHandler\n public void preLoad(FMLPreInitializationEvent event)\n {\n config = ConfigHandler.registerConfig(new Config(event.getSuggestedConfigurationFile()));\n\n proxy.preInitMod();\n\n UpdateChecker.registerMod(new UpdateChecker.ModVersionInfo(MOD_NAME, iChunUtil.VERSION_OF_MC, VERSION, false));\n\n FMLInterModComms.sendMessage(\"backtools\", \"blacklist\", new ItemStack(itemShellConstructor, 1));\n FMLInterModComms.sendMessage(\"backtools\", \"blacklist\", new ItemStack(itemShellStorage, 1));\n FMLInterModComms.sendMessage(\"backtools\", \"blacklist\", new ItemStack(itemTreadmill, 1));\n }\n\n @EventHandler\n public void load(FMLInitializationEvent event)\n {\n ForgeChunkManager.setForcedChunkLoadingCallback(this, new ChunkLoadHandler());\n\n FMLInterModComms.sendMessage(\"AppliedEnergistics\", \"movabletile\", TileEntityDualVertical.class.getName());\n FMLInterModComms.sendMessage(\"AppliedEnergistics\", \"movabletile\", TileEntityTreadmill.class.getName());\n FMLInterModComms.sendMessage(\"waila\", \"register\", \"me.ichun.mods.sync.client.HUDHandlerWaila.callbackRegister\");\n FMLInterModComms.sendFunctionMessage(\"theoneprobe\", \"getTheOneProbe\", \"me.ichun.mods.sync.client.HUDHandlerTheOneProbe\");\n\n TREADMILL_ENTITY_HASH_MAP.put(EntityWolf.class, 4);\n TREADMILL_ENTITY_HASH_MAP.put(EntityPig.class, 2);\n }\n\n @EventHandler\n public void serverStarting(FMLServerStartingEvent event) {\n event.registerServerCommand(new CommandSync());\n }\n\n @EventHandler\n public void serverStopped(FMLServerStoppedEvent event)\n {\n ChunkLoadHandler.shellTickets.clear();\n ShellHandler.syncInProgress.clear();\n ShellHandler.playerShells.clear();\n }\n\n @EventHandler\n public void processIMC(FMLInterModComms.IMCEvent event) {\n for (FMLInterModComms.IMCMessage message : event.getMessages())\n {\n if (message.isStringMessage())\n {\n if (message.key.equals(\"treadmill\"))\n {\n String[] s = message.getStringValue().split(\":\");\n if (s.length != 2)\n {\n LOGGER.log(Level.WARN, \"Invalid IMC treadmill register (incorrect length) received from \" + message.getSender());\n }\n else\n {\n try\n {\n String entityClassName = s[0];\n int entityPower = Integer.valueOf(s[1]);\n Class entityClass = Class.forName(entityClassName);\n\n if (EntityPlayer.class.isAssignableFrom(entityClass)) LOGGER.log(Level.WARN, \"Seriously? You're gonna try that?\");\n else {\n TREADMILL_ENTITY_HASH_MAP.put(entityClass, entityPower);\n LOGGER.info(String.format(\"Registered IMC treadmill register from %s for %s with power %s\", message.getSender(), entityClassName, entityPower));\n }\n } catch (NumberFormatException e)\n {\n LOGGER.log(Level.WARN, \"Invalid IMC treadmill register (power not integer) received from \" + message.getSender());\n } catch (ClassNotFoundException e)\n {\n LOGGER.log(Level.WARN, \"Invalid IMC treadmill register (class not found) received from \" + message.getSender());\n }\n }\n }\n }\n }\n }\n}",
"public class BlockDualVertical extends BlockContainer {\n\n public static int renderPass;\n private static final AxisAlignedBB TREADMILL_AABB = new AxisAlignedBB(0.0D, 0.0D, 0.0D, 1.0D, 0.4D, 1.0D);\n private static final AxisAlignedBB TOP_AABB = new AxisAlignedBB(0.0F, 1.0F - 0.05F / 2, 0.0F, 1.0F, 1.0F, 1.0F);\n private static final AxisAlignedBB WALL_NORTH_AABB = new AxisAlignedBB(0.0D, 0.0D, 0.0D, 1.0D, 1.0D, 0.05D);\n private static final AxisAlignedBB WALL_EAST_AABB = new AxisAlignedBB(1D - 0.05D, 0.0D, 0.0D, 1.0D, 1.0D, 1.0D);\n private static final AxisAlignedBB WALL_SOUTH_AABB = new AxisAlignedBB(0.0D, 0.0D, 1.0D - 0.05D, 1.0D, 1.0D, 1.0D);\n private static final AxisAlignedBB WALL_WEST_AABB = new AxisAlignedBB(0.0D, 0.0D, 0.0D, 0.05D, 1.0D, 1.0D);\n\n public static final PropertyEnum<EnumType> TYPE = PropertyEnum.create(\"type\", EnumType.class);\n\n public BlockDualVertical() {\n super(Material.IRON);\n this.setDefaultState(this.blockState.getBaseState().withProperty(TYPE, EnumType.CONSTRUCTOR));\n }\n\n @Override\n public TileEntity createNewTileEntity(World world, int meta)\n {\n switch (meta) {\n case 0: {\n return new TileEntityShellConstructor();\n }\n case 1: {\n return new TileEntityShellStorage();\n }\n case 2: {\n return new TileEntityTreadmill();\n }\n default: {\n return this.createNewTileEntity(world, meta);\n }\n }\n }\n\n @Override\n public boolean isFullCube(IBlockState state)\n {\n return false;\n }\n\n @Override\n public boolean isNormalCube(IBlockState state, IBlockAccess world, BlockPos pos)\n {\n return false;\n }\n\n @Override\n public boolean isOpaqueCube(IBlockState state)\n {\n return false;\n }\n\n @Override\n public int quantityDropped(Random random) {\n return 0;\n }\n\n\n\n @Override\n public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, EntityPlayer player, EnumHand hand, EnumFacing side, float hitX, float hitY, float hitZ) {\n TileEntity tileEntity = world.getTileEntity(pos);\n if (tileEntity instanceof TileEntityDualVertical && !(player instanceof FakePlayer)) {\n TileEntityDualVertical dualVertical = (TileEntityDualVertical) tileEntity;\n boolean top = dualVertical.top;\n if (top) {\n TileEntity tileEntityPair = world.getTileEntity(pos.down());\n if (tileEntityPair instanceof TileEntityDualVertical) {\n dualVertical = (TileEntityDualVertical) tileEntityPair;\n }\n }\n\n //Shell Constructor\n if (dualVertical instanceof TileEntityShellConstructor) {\n TileEntityShellConstructor shellConstructor = (TileEntityShellConstructor) dualVertical;\n\n //If nothing is there\n if (shellConstructor.getPlayerName().equalsIgnoreCase(\"\")) {\n if (iChunUtil.hasMorphMod() && MorphApi.getApiImpl().hasMorph(player.getName(), Side.SERVER)) {\n player.sendMessage(new TextComponentTranslation(\"sync.isMorphed\"));\n return true;\n }\n shellConstructor.setPlayerName(player);\n\n if (!world.isRemote && !player.isCreative()) {\n String name = DamageSource.OUT_OF_WORLD.damageType;\n DamageSource.OUT_OF_WORLD.damageType = \"shellConstruct\";\n player.attackEntityFrom(DamageSource.OUT_OF_WORLD, (float)Sync.config.damageGivenOnShellConstruction);\n DamageSource.OUT_OF_WORLD.damageType = name;\n }\n\n notifyThisAndAbove(state, EnumType.CONSTRUCTOR, pos, world, top);\n return true;\n }\n else if (shellConstructor.matchesPlayer(player) && player.isCreative()) {\n if (!world.isRemote) {\n shellConstructor.constructionProgress = Sync.config.shellConstructionPowerRequirement;\n ShellHandler.updatePlayerOfShells(player, null, true);\n notifyThisAndAbove(state, EnumType.CONSTRUCTOR, pos, world, top);\n }\n return true;\n }\n\n }\n //Shell Storage\n else if (dualVertical instanceof TileEntityShellStorage) {\n TileEntityShellStorage shellStorage = (TileEntityShellStorage) dualVertical;\n ItemStack itemStack = player.getHeldItem(hand);\n\n if (!itemStack.isEmpty()) {\n //Set storage name\n if (itemStack.getItem() instanceof ItemNameTag) {\n //Don't do anything if name is the same\n if ((!itemStack.hasDisplayName() && dualVertical.getName().equalsIgnoreCase(\"\")) || (itemStack.hasDisplayName() && dualVertical.getName().equalsIgnoreCase(itemStack.getDisplayName()))) {\n return false;\n }\n dualVertical.setName(itemStack.hasDisplayName() ? itemStack.getDisplayName() : \"\");\n itemStack.shrink(1);\n\n if (!player.isCreative() && itemStack.isEmpty()) {\n player.setItemStackToSlot(hand == EnumHand.MAIN_HAND ? EntityEquipmentSlot.MAINHAND : EntityEquipmentSlot.OFFHAND, ItemStack.EMPTY);\n }\n notifyThisAndAbove(state, EnumType.STORAGE, pos, world, top);\n\n if (!world.isRemote) {\n EntityPlayerMP entityPlayerMP = dualVertical.getPlayerIfAvailable();\n if (entityPlayerMP != null) {\n ShellHandler.updatePlayerOfShells(entityPlayerMP, null, true);\n }\n }\n return true;\n }\n //Set Home Shell\n else if (itemStack.getItem() instanceof ItemBed) {\n //Changes state\n shellStorage.isHomeUnit = !shellStorage.isHomeUnit;\n\n notifyThisAndAbove(state, EnumType.STORAGE, pos, world, top);\n\n if (!world.isRemote) {\n EntityPlayerMP entityPlayerMP = dualVertical.getPlayerIfAvailable();\n if (entityPlayerMP != null) {\n ShellHandler.updatePlayerOfShells(entityPlayerMP, null, true);\n }\n }\n return true;\n }\n }\n }\n }\n else if (tileEntity instanceof TileEntityTreadmill) {\n TileEntityTreadmill treadmill = (TileEntityTreadmill)tileEntity;\n\n if (treadmill.back) {\n treadmill = treadmill.pair;\n }\n\n if (treadmill != null && treadmill.latchedEnt == null) {\n double radius = 7D; //Radius\n List<EntityLiving> list = world.getEntitiesWithinAABB(EntityLiving.class, new AxisAlignedBB(pos.getX() - radius, pos.getY() - radius, pos.getZ() - radius, (double)pos.getX() + radius, pos.getY() + radius, pos.getZ() + radius));\n\n if (!list.isEmpty()) {\n for (EntityLiving obj : list) {\n if (obj.getLeashed() && obj.getLeashHolder() == player && TileEntityTreadmill.isEntityValidForTreadmill(obj)) {\n if (!world.isRemote) {\n treadmill.latchedEnt = obj;\n treadmill.latchedHealth = obj.getHealth();\n obj.setLocationAndAngles(treadmill.getMidCoord(0), pos.getY() + 0.175D, treadmill.getMidCoord(1), treadmill.face.getOpposite().getHorizontalAngle(), 0.0F);\n world.notifyBlockUpdate(pos, state, state.withProperty(TYPE, EnumType.TREADMILL), 3);\n obj.clearLeashed(true, !player.isCreative());\n }\n return true;\n }\n }\n }\n\n ItemStack itemStack = player.getHeldItem(hand);\n //Allow easier creative testing. Only works for pig and wolves cause easier\n if (!world.isRemote && !itemStack.isEmpty() && itemStack.getItem() instanceof ItemMonsterPlacer) {\n ResourceLocation mob = ItemMonsterPlacer.getNamedIdFrom(itemStack);\n if (\"Pig\".equalsIgnoreCase(mob.getPath()) || \"Wolf\".equalsIgnoreCase(mob.getPath())) {\n Entity entity = ItemMonsterPlacer.spawnCreature(world, mob, treadmill.getMidCoord(0), pos.getY() + 0.175D, treadmill.getMidCoord(1));\n if (TileEntityTreadmill.isEntityValidForTreadmill(entity)) {\n treadmill.latchedEnt = (EntityLiving)entity;\n treadmill.latchedHealth = ((EntityLiving)entity).getHealth();\n entity.setLocationAndAngles(treadmill.getMidCoord(0), pos.getY() + 0.175D, treadmill.getMidCoord(1), treadmill.face.getOpposite().getHorizontalAngle(), 0.0F);\n world.notifyBlockUpdate(pos, state, state.withProperty(TYPE, EnumType.TREADMILL), 3);\n return true;\n }\n }\n }\n }\n }\n return false;\n }\n\n @Nonnull\n @Override\n public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess world, BlockPos pos) {\n if (state.getValue(TYPE) == EnumType.TREADMILL)\n return TREADMILL_AABB;\n return Block.FULL_BLOCK_AABB;\n }\n\n @SideOnly(Side.CLIENT)\n public double getDistance(BlockPos pos) {\n EntityPlayer player = Minecraft.getMinecraft().player;\n\n double d3 = player.posX - (pos.getX() + 0.5D);\n double d4 = player.getEntityBoundingBox().minY - pos.getY();\n double d5 = player.posZ - (pos.getZ() + 0.5D);\n\n return (double) MathHelper.sqrt(d3 * d3 + d4 * d4 + d5 * d5);\n }\n\n @Override\n public void onEntityCollision(World world, BlockPos pos, IBlockState state, Entity entity) {\n //Ignore non players and fake players\n if (!(entity instanceof EntityPlayer) || (entity instanceof FakePlayer)) {\n return;\n }\n\n TileEntity tileEntity = world.getTileEntity(pos);\n if (tileEntity instanceof TileEntityDualVertical) {\n TileEntityDualVertical dualVertical = (TileEntityDualVertical) tileEntity;\n if (dualVertical.top) {\n TileEntity tileEntityPair = world.getTileEntity(pos.down());\n if (tileEntityPair instanceof TileEntityDualVertical) {\n this.onEntityCollision(world, pos.down(), state, entity);\n }\n }\n else {\n if (dualVertical instanceof TileEntityShellStorage) {\n TileEntityShellStorage shellStorage = (TileEntityShellStorage) dualVertical;\n if (!shellStorage.occupied && !world.isRemote && !shellStorage.syncing && shellStorage.resyncPlayer <= -10) {\n double d3 = entity.posX - (pos.getX() + 0.5D);\n double d4 = entity.getEntityBoundingBox().minY - pos.getY();\n double d5 = entity.posZ - (pos.getZ() + 0.5D);\n double dist = (double) MathHelper.sqrt(d3 * d3 + d4 * d4 + d5 * d5);\n\n if (dist < 0.3D && shellStorage.isPowered()) {\n EntityPlayer player = (EntityPlayer)entity;\n\n if (iChunUtil.hasMorphMod() && MorphApi.getApiImpl().hasMorph(player.getName(), Side.SERVER)) {\n player.sendMessage(new TextComponentTranslation(\"sync.isMorphed\"));\n }\n else {\n Sync.channel.sendTo(new PacketPlayerEnterStorage(pos), player);\n player.setLocationAndAngles(pos.getX() + 0.5D, pos.getY(), pos.getZ() + 0.5D, shellStorage.face.getOpposite().getHorizontalAngle(), 0F);\n }\n\n //Mark this as in use\n shellStorage.setPlayerName(player);\n shellStorage.occupied = true;\n world.notifyBlockUpdate(pos, state, state, 3);\n }\n }\n }\n }\n }\n }\n\n @Override\n public void addCollisionBoxToList(IBlockState state, World world, BlockPos pos, AxisAlignedBB aabb, List<AxisAlignedBB> list, Entity entity, boolean p_185477_7_)\n {\n EnumType type = state.getValue(TYPE);\n if (type == EnumType.TREADMILL) {\n super.addCollisionBoxToList(state, world, pos, aabb, list, entity, p_185477_7_);\n return;\n }\n TileEntity te = world.getTileEntity(pos);\n boolean shouldAdd = false;\n if (te instanceof TileEntityShellStorage) {\n TileEntityShellStorage shellStorage = (TileEntityShellStorage) te;\n shouldAdd = (!shellStorage.occupied || (world.isRemote && this.isLocalPlayer(shellStorage.getPlayerName()))) && !shellStorage.syncing;\n }\n\n if (te instanceof TileEntityShellConstructor) {\n TileEntityShellConstructor shellConstructor = (TileEntityShellConstructor) te;\n shouldAdd = shellConstructor.doorOpen;\n }\n\n if (shouldAdd) {\n TileEntityDualVertical<?> dualVertical = (TileEntityDualVertical<?>) te;\n EnumFacing toCheck = dualVertical.face.getOpposite();\n if (toCheck != EnumFacing.WEST)\n addCollisionBoxToList(pos, aabb, list, WALL_WEST_AABB);\n if (toCheck != EnumFacing.NORTH)\n addCollisionBoxToList(pos, aabb, list, WALL_NORTH_AABB);\n if (toCheck != EnumFacing.EAST)\n addCollisionBoxToList(pos, aabb, list, WALL_EAST_AABB);\n if (toCheck != EnumFacing.SOUTH)\n addCollisionBoxToList(pos, aabb, list, WALL_SOUTH_AABB);\n if (dualVertical.top)\n addCollisionBoxToList(pos, aabb, list, TOP_AABB);\n } else\n super.addCollisionBoxToList(state, world, pos, aabb, list, entity, p_185477_7_);\n }\n\n @SideOnly(Side.CLIENT)\n public boolean isLocalPlayer(String playerName) {\n return playerName != null && Minecraft.getMinecraft().player != null && playerName.equalsIgnoreCase(Minecraft.getMinecraft().player.getName());\n }\n\n @Override\n public void neighborChanged(IBlockState state, World world, BlockPos pos, Block block, BlockPos fromPos)\n {\n TileEntity tileEntity = world.getTileEntity(pos);\n if (tileEntity instanceof TileEntityDualVertical) {\n TileEntityDualVertical dualVertical = (TileEntityDualVertical) tileEntity;\n if (!dualVertical.top && !world.getBlockState(pos.add(0, -1, 0)).isOpaqueCube()) {\n world.setBlockToAir(pos);\n }\n }\n if (tileEntity instanceof TileEntityTreadmill) {\n if (world.getTileEntity(pos.add(0, -1, 0)) instanceof TileEntityTreadmill) {\n world.setBlockToAir(pos);\n }\n }\n }\n\n\n\n @Override\n public boolean removedByPlayer(@Nonnull IBlockState state, World world, @Nonnull BlockPos pos, @Nonnull EntityPlayer player, boolean willHarvest) {\n if (!world.isRemote) {\n TileEntity tileEntity = world.getTileEntity(pos);\n if (tileEntity instanceof TileEntityDualVertical) {\n TileEntityDualVertical dualVertical = (TileEntityDualVertical) tileEntity;\n BlockPos newPos = dualVertical.top ? pos.down() : pos.up();\n TileEntity tileEntityPair = world.getTileEntity(newPos);\n if (tileEntityPair instanceof TileEntityDualVertical) {\n TileEntityDualVertical dualVerticalPair = (TileEntityDualVertical) tileEntityPair;\n if (dualVerticalPair.pair == dualVertical) {\n world.playEvent(2001, newPos, Block.getIdFromBlock(Sync.blockDualVertical));\n world.setBlockToAir(newPos);\n }\n TileEntityDualVertical bottom = dualVerticalPair.top ? dualVertical : dualVerticalPair;\n\n if (!bottom.getPlayerName().equalsIgnoreCase(\"\") && !bottom.matchesPlayer(player)) {\n FMLCommonHandler.instance().getMinecraftServerInstance().getPlayerList().sendMessage(new TextComponentTranslation(\"sync.breakShellUnit\", player.getName(), bottom.getPlayerName()));\n }\n\n if (!player.isCreative()) {\n float f = 0.5F;\n double d = (double)(world.rand.nextFloat() * f) + (double)(1.0F - f) * 0.5D;\n double d1 = (double)(world.rand.nextFloat() * f) + (double)(1.0F - f) * 0.5D;\n double d2 = (double)(world.rand.nextFloat() * f) + (double)(1.0F - f) * 0.5D;\n BlockPos dualVerticalPos = dualVertical.getPos();\n EntityItem entityitem = new EntityItem(world, (double)dualVerticalPos.getX() + d, (double)dualVerticalPos.getY() + d1, (double)dualVerticalPos.getZ() + d2, new ItemStack(dualVertical instanceof TileEntityShellConstructor ? Sync.itemShellConstructor : Sync.itemShellStorage, 1));\n entityitem.setPickupDelay(10);\n world.spawnEntity(entityitem);\n }\n }\n }\n }\n return super.removedByPlayer(state, world, pos, player, willHarvest);\n }\n\n @Override\n public void breakBlock(World world, @Nonnull BlockPos pos, @Nonnull IBlockState state) {\n TileEntity tileEntity = world.getTileEntity(pos);\n if (tileEntity instanceof TileEntityDualVertical) {\n TileEntityDualVertical dualVertical = (TileEntityDualVertical) tileEntity;\n BlockPos newPos = dualVertical.top ? pos.down() : pos.up();\n TileEntity tileEntityPair = world.getTileEntity(newPos);\n if (tileEntityPair instanceof TileEntityDualVertical) {\n TileEntityDualVertical dualVerticalPair = (TileEntityDualVertical) tileEntityPair;\n //Confirm they are linked then remove\n if (dualVerticalPair.pair == dualVertical) {\n world.playEvent(2001, newPos, Block.getIdFromBlock(Sync.blockDualVertical));\n world.setBlockToAir(newPos);\n }\n TileEntityDualVertical dualVerticalBottom = dualVerticalPair.top ? dualVertical : dualVerticalPair;\n\n if (!world.isRemote) {\n //TODO Should we treat this as an actual player death in terms of drops?\n if (dualVerticalBottom instanceof TileEntityShellStorage && dualVerticalBottom.resyncPlayer == -10 && ((TileEntityShellStorage) dualVerticalBottom).syncing && dualVerticalBottom.getPlayerNBT().hasKey(\"Inventory\")) {\n UUID playerUUID = dualVerticalBottom.getPlayerUUID();\n GameProfile profile = playerUUID == null ? EntityHelper.getGameProfile(dualVerticalBottom.getPlayerName()) : EntityHelper.getGameProfile(playerUUID, dualVerticalBottom.getPlayerName());\n FakePlayer fake = new FakePlayer((WorldServer)world, profile);\n fake.readFromNBT(dualVerticalBottom.getPlayerNBT());\n fake.setLocationAndAngles(pos.getX() + 0.5D, pos.getY(), pos.getZ() + 0.5D, dualVerticalBottom.face.getOpposite().getHorizontalAngle(), 0F);\n\n fake.captureDrops = true;\n fake.capturedDrops.clear();\n fake.inventory.dropAllItems();\n fake.captureDrops = false;\n\n PlayerDropsEvent event = new PlayerDropsEvent(fake, DamageSource.OUT_OF_WORLD, fake.capturedDrops, false);\n if (!MinecraftForge.EVENT_BUS.post(event)) {\n for (EntityItem item : fake.capturedDrops) {\n fake.dropItemAndGetStack(item);\n }\n }\n Sync.channel.sendToAllAround(new PacketShellDeath(dualVerticalBottom.getPos(), dualVerticalBottom.face), new NetworkRegistry.TargetPoint(dualVerticalBottom.getWorld().provider.getDimension(), pos.getX(), pos.getY(), pos.getZ(), 64D));\n }\n else if (dualVerticalBottom instanceof TileEntityShellConstructor) {\n TileEntityShellConstructor shellConstructor = (TileEntityShellConstructor) dualVerticalBottom;\n if (!shellConstructor.getPlayerName().equalsIgnoreCase(\"\") && shellConstructor.constructionProgress >= Sync.config.shellConstructionPowerRequirement) {\n Sync.channel.sendToAllAround(new PacketShellDeath(dualVerticalBottom.getPos(), dualVerticalBottom.face), new NetworkRegistry.TargetPoint(dualVerticalBottom.getWorld().provider.getDimension(), pos.getX(), pos.getY(), pos.getZ(), 64D));\n }\n }\n ShellHandler.removeShell(dualVerticalBottom.getPlayerName(), dualVerticalBottom);\n //If sync is in progress, cancel and kill the player syncing\n if (dualVerticalBottom.resyncPlayer > 25 && dualVerticalBottom.resyncPlayer < 120) {\n ShellHandler.syncInProgress.remove(dualVerticalBottom.getPlayerName());\n //Need to let dualVertical know sync is cancelled\n EntityPlayerMP syncingPlayer = dualVerticalBottom.getPlayerIfAvailable();\n if (syncingPlayer != null) {\n String name = DamageSource.OUT_OF_WORLD.damageType;\n DamageSource.OUT_OF_WORLD.damageType = \"syncFail\";\n syncingPlayer.attackEntityFrom(DamageSource.OUT_OF_WORLD, Float.MAX_VALUE);\n DamageSource.OUT_OF_WORLD.damageType = name;\n }\n }\n }\n }\n }\n else if (tileEntity instanceof TileEntityTreadmill) {\n TileEntityTreadmill treadmill = (TileEntityTreadmill) tileEntity;\n BlockPos toClean = new BlockPos(treadmill.back ? (treadmill.face == EnumFacing.WEST ? pos.getX() + 1 : treadmill.face == EnumFacing.EAST ? pos.getX() - 1 : pos.getX()) : (treadmill.face == EnumFacing.WEST ? pos.getX() - 1 : treadmill.face == EnumFacing.EAST ? pos.getX() + 1 : pos.getX()), pos.getY(), treadmill.back ? (treadmill.face == EnumFacing.SOUTH ? pos.getZ() - 1 : treadmill.face == EnumFacing.NORTH ? pos.getZ() + 1 : pos.getZ()) : (treadmill.face == EnumFacing.SOUTH ? pos.getZ() + 1 : treadmill.face == EnumFacing.NORTH ? pos.getZ() - 1 : pos.getZ()));\n TileEntity tileEntityPair = world.getTileEntity(toClean);\n\n if (tileEntityPair instanceof TileEntityTreadmill) {\n TileEntityTreadmill treadmillPair = (TileEntityTreadmill)tileEntityPair;\n if (treadmillPair.pair == treadmill) {\n world.playEvent(2001, pos, Block.getIdFromBlock(Sync.blockDualVertical));\n world.setBlockToAir(toClean);\n }\n\n if (!treadmillPair.back && !world.isRemote) {\n float f = 0.5F;\n double d = (double)(world.rand.nextFloat() * f) + (double)(1.0F - f) * 0.5D;\n double d1 = (double)(world.rand.nextFloat() * f) + (double)(1.0F - f) * 0.5D;\n double d2 = (double)(world.rand.nextFloat() * f) + (double)(1.0F - f) * 0.5D;\n EntityItem entityitem = new EntityItem(world, (double)pos.getX() + d, (double)pos.getY() + d1, (double)pos.getZ() + d2, new ItemStack(Sync.itemTreadmill, 1));\n entityitem.setPickupDelay(10);\n world.spawnEntity(entityitem);\n }\n }\n }\n super.breakBlock(world, pos, state);\n }\n\n @Override\n @Nonnull\n public ItemStack getPickBlock(@Nonnull IBlockState state, RayTraceResult target, @Nonnull World world, @Nonnull BlockPos pos, EntityPlayer player) {\n return new ItemStack(EnumType.getItemForType(world.getBlockState(pos).getValue(BlockDualVertical.TYPE)));\n }\n\n @Override\n public boolean hasComparatorInputOverride(IBlockState state) {\n return true;\n }\n\n @Override\n public int getComparatorInputOverride(IBlockState blockState, World world, BlockPos pos) {\n if (world.getTileEntity(pos) instanceof TileEntityDualVertical) {\n TileEntityDualVertical tileEntityDualVertical = (TileEntityDualVertical) world.getTileEntity(pos);\n return (int) Math.floor(tileEntityDualVertical.getBuildProgress() / (Sync.config.shellConstructionPowerRequirement / 15F));\n }\n else return 0;\n }\n\n @Override\n public boolean isSideSolid(IBlockState base_state, @Nonnull IBlockAccess world, @Nonnull BlockPos pos, EnumFacing side) {\n TileEntity tileEntity = world.getTileEntity(pos);\n if (tileEntity instanceof TileEntityDualVertical) {\n TileEntityDualVertical dualVertical = (TileEntityDualVertical) tileEntity;\n if (side == EnumFacing.DOWN || side == EnumFacing.UP) return true;\n if (!(tileEntity instanceof TileEntityShellConstructor)) {\n return side == dualVertical.face;\n }\n }\n return false;\n }\n\n @Override\n protected BlockStateContainer createBlockState() {\n return new BlockStateContainer(this, TYPE);\n }\n\n @Override\n public int getMetaFromState(IBlockState state) {\n switch (state.getValue(TYPE)) {\n case CONSTRUCTOR:\n return 0;\n case STORAGE:\n return 1;\n case TREADMILL:\n return 2;\n default:\n throw new RuntimeException(\"Unknown state value \" + state.getValue(TYPE));\n }\n }\n\n @Override\n public IBlockState getStateFromMeta(int meta) {\n switch (meta) {\n case 0:\n return this.getDefaultState().withProperty(TYPE, EnumType.CONSTRUCTOR);\n case 1:\n return this.getDefaultState().withProperty(TYPE, EnumType.STORAGE);\n case 2:\n return this.getDefaultState().withProperty(TYPE, EnumType.TREADMILL);\n default:\n throw new RuntimeException(\"Don't know how to convert \" + meta + \" to state\");\n }\n }\n\n @Override\n public boolean hasCustomBreakingProgress(IBlockState state)\n {\n return state.getValue(TYPE) != EnumType.TREADMILL;\n }\n\n private static void notifyThisAndAbove(IBlockState oldState, EnumType newType, BlockPos thisPos, World world, boolean isTop) {\n BlockPos other = isTop ? thisPos.down() : thisPos.up();\n IBlockState above = world.getBlockState(other);\n world.notifyBlockUpdate(thisPos, oldState, oldState.withProperty(TYPE, newType), 3);\n world.notifyBlockUpdate(other, above, above.withProperty(TYPE, newType), 3);\n }\n\n}",
"public class PacketNBT extends AbstractPacket\n{\n public NBTTagCompound tag;\n\n public PacketNBT(){}\n\n public PacketNBT(NBTTagCompound tag)\n {\n this.tag = tag;\n }\n\n @Override\n public void writeTo(ByteBuf buffer)\n {\n ByteBufUtils.writeTag(buffer, tag);\n }\n\n @Override\n public void readFrom(ByteBuf buffer)\n {\n tag = ByteBufUtils.readTag(buffer);\n }\n\n @Override\n public void execute(Side side, EntityPlayer player)\n {\n handleClient();\n }\n\n @Override\n public Side receivingSide()\n {\n return Side.CLIENT;\n }\n\n @SideOnly(Side.CLIENT)\n public void handleClient()\n {\n Minecraft mc = Minecraft.getMinecraft();\n mc.player.readFromNBT(tag);\n if(mc.player.isEntityAlive())\n {\n mc.player.deathTime = 0;\n }\n\n mc.playerController.setGameType(GameType.getByID(tag.getInteger(\"sync_playerGameMode\")));\n }\n}",
"public class PacketZoomCamera extends AbstractPacket\n{\n public BlockPos pos;\n public int dimID;\n public int zoomFace;\n public boolean zoom;\n public boolean zoomDeath;\n\n public PacketZoomCamera(){}\n\n public PacketZoomCamera(BlockPos pos, int dimID, EnumFacing zoomFace, boolean zoom, boolean zoomDeath)\n {\n this.pos = pos;\n this.dimID = dimID;\n this.zoomFace = zoomFace.getIndex();\n this.zoom = zoom;\n this.zoomDeath = zoomDeath;\n }\n\n\n @Override\n public void writeTo(ByteBuf buffer)\n {\n buffer.writeLong(pos.toLong());\n buffer.writeInt(dimID);\n buffer.writeInt(zoomFace);\n buffer.writeBoolean(zoom);\n buffer.writeBoolean(zoomDeath);\n }\n\n @Override\n public void readFrom(ByteBuf buffer)\n {\n //zoom state\n Sync.eventHandlerClient.zoomPos = BlockPos.fromLong(buffer.readLong());\n\n Sync.eventHandlerClient.zoomDimension = buffer.readInt();\n\n Sync.eventHandlerClient.zoomFace = EnumFacing.byIndex(buffer.readInt());\n Sync.eventHandlerClient.zoom = buffer.readBoolean();\n\n Sync.eventHandlerClient.zoomTimer = 60;\n\n Sync.eventHandlerClient.zoomDeath = buffer.readBoolean();\n\n }\n\n @Override\n public void execute(Side side, EntityPlayer player){}\n\n @Override\n public Side receivingSide()\n {\n return Side.CLIENT;\n }\n}",
"public class ShellHandler {\n\n public static SetMultimap<String, TileEntityDualVertical> playerShells = HashMultimap.create();\n public static HashMap<String, TileEntityDualVertical> syncInProgress = new HashMap<>();\n\n public static void addShell(String playerName, TileEntityDualVertical dualVertical, boolean shouldChunkLoad) {\n if (!playerShells.containsEntry(playerName, dualVertical)) {\n playerShells.put(playerName, dualVertical);\n if (shouldChunkLoad && !ChunkLoadHandler.isAlreadyChunkLoaded(dualVertical)) ChunkLoadHandler.addShellAsChunkloader(dualVertical);\n }\n }\n\n public static void removeShell(String playerName, TileEntityDualVertical dualVertical) {\n if (playerName != null && dualVertical != null) {\n playerShells.remove(playerName, dualVertical);\n ChunkLoadHandler.removeShellAsChunkloader(dualVertical);\n dualVertical.reset();\n IBlockState state = dualVertical.getWorld().getBlockState(dualVertical.getPos());\n IBlockState state1 = dualVertical.getWorld().getBlockState(dualVertical.getPos().add(0, 1, 0));\n dualVertical.getWorld().notifyBlockUpdate(dualVertical.getPos(), state, state, 3);\n dualVertical.getWorld().notifyBlockUpdate(dualVertical.getPos().add(0, 1, 0), state1, state1, 3);\n }\n else Sync.LOGGER.log(Level.WARN, String.format(\"Attempted to remove a shell but something was null for %s at %s\", playerName, dualVertical));\n }\n\n public static boolean isShellAlreadyRegistered(TileEntityDualVertical dualVertical) {\n return playerShells.containsValue(dualVertical);\n }\n\n public static void updatePlayerOfShells(EntityPlayer player, TileEntityDualVertical dv, boolean all) {\n ArrayList<TileEntityDualVertical> dvs = new ArrayList<>();\n ArrayList<TileEntityDualVertical> remove = new ArrayList<>();\n\n if (all) {\n //Tell player client to clear current list\n Sync.channel.sendTo(new PacketClearShellList(), player);\n\n for (Map.Entry<String, TileEntityDualVertical> e : playerShells.entries()) {\n if (e.getKey().equalsIgnoreCase(player.getName())) {\n TileEntityDualVertical dualVertical = e.getValue();\n if (dualVertical.getWorld().getTileEntity(dualVertical.getPos()) == dualVertical) {\n dvs.add(dualVertical);\n }\n else {\n remove.add(dualVertical);\n }\n }\n }\n }\n else if (dv != null) {\n //This is never used due to issues synching to the point I gave up.\n dvs.add(dv);\n }\n\n for (TileEntityDualVertical dv1 : dvs) {\n if (dv1.top) continue;\n Sync.channel.sendTo(new PacketShellState(dv1, false), player);\n }\n\n for (TileEntityDualVertical dv1 : remove) {\n removeShell(dv1.getPlayerName(), dv1);\n }\n }\n\n public static void updatePlayerOfShellRemoval(EntityPlayer player, TileEntityDualVertical dv) {\n if (dv.top) return;\n Sync.channel.sendTo(new PacketShellState(dv, true), player);\n }\n}",
"public class TeleporterShell extends Teleporter \n{\n\n public int dimension;\n public BlockPos pos;\n public float playerYaw;\n public float playerPitch;\n\n public TeleporterShell(WorldServer par1WorldServer)\n {\n super(par1WorldServer);\n }\n\n public TeleporterShell(WorldServer server, int dimensionId, BlockPos pos, float yaw, float pitch) {\n this(server);\n this.dimension = dimensionId;\n this.pos = pos;\n this.playerYaw = yaw;\n this.playerPitch = pitch;\n }\n\n @Override\n public void placeInPortal(Entity entityIn, float rotationYaw)\n {\n entityIn.setLocationAndAngles((double)pos.getX() + 0.5D, (double)pos.getY(), (double)pos.getZ() + 0.5D, playerYaw, playerPitch);\n entityIn.motionX = entityIn.motionY = entityIn.motionZ = 0.0D;\n }\n \n @Override\n public void removeStalePortalLocations(long par1)\n {\n }\n\n}"
] | import io.netty.buffer.ByteBuf;
import me.ichun.mods.ichunutil.common.core.util.EntityHelper;
import me.ichun.mods.sync.client.core.SyncSkinManager;
import me.ichun.mods.sync.common.Sync;
import me.ichun.mods.sync.common.block.BlockDualVertical;
import me.ichun.mods.sync.common.packet.PacketNBT;
import me.ichun.mods.sync.common.packet.PacketZoomCamera;
import me.ichun.mods.sync.common.shell.ShellHandler;
import me.ichun.mods.sync.common.shell.TeleporterShell;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.play.server.SPacketUpdateTileEntity;
import net.minecraft.server.management.PlayerInteractionManager;
import net.minecraft.server.management.PlayerList;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.*;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.GameType;
import net.minecraft.world.WorldServer;
import net.minecraftforge.common.util.Constants;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.network.ByteBufUtils;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.apache.commons.lang3.StringUtils;
import javax.annotation.Nullable;
import java.util.List;
import java.util.Set;
import java.util.UUID; | }
//Beginning of kicking the player out
if (this.resyncPlayer == 40) {
this.vacating = true;
if (this.getClass() == TileEntityShellStorage.class) {
TileEntityShellStorage shellStorage = (TileEntityShellStorage) this;
shellStorage.occupied = true;
shellStorage.occupationTime = animationTime;
}
else if (this.getClass() == TileEntityShellConstructor.class) {
TileEntityShellConstructor shellConstructor = (TileEntityShellConstructor) this;
shellConstructor.doorOpen = true;
}
IBlockState state = world.getBlockState(getPos());
IBlockState state1 = world.getBlockState(getPos().add(0, 1, 0));
world.notifyBlockUpdate(getPos(), state, state, 3);
world.notifyBlockUpdate(getPos().add(0, 1, 0), state1, state1, 3);
}
//This is where we begin to sync the data aka point of no return
if (this.resyncPlayer == 30) {
EntityPlayerMP player = getPlayerIfAvailable();
if (player != null && player.isEntityAlive()) {
//Clear active potion effects before syncing
player.clearActivePotions();
if (Sync.config.transferPersistentItems == 1)
{
if (wasDead)
{
//copy new items that are given on death, like the key to a tombstone
EntityPlayerMP deadDummy = setupDummy(player);
mergeStoredInv(deadDummy.inventory);
}
//Copy data needed from player
NBTTagCompound tag = new NBTTagCompound();
EntityPlayerMP dummy = setupDummy(player);
//Set data
dummy.writeToNBT(tag);
if (resyncOrigin != null) //deduplicate items
{
//Strip items from the old inv that have been transferred to the new inventory
deleteItemsFrom(player.inventory.mainInventory, dummy.inventory.mainInventory);
deleteItemsFrom(player.inventory.armorInventory, dummy.inventory.armorInventory);
deleteItemsFrom(player.inventory.offHandInventory, dummy.inventory.offHandInventory);
//Write the changes to the old inventory
resyncOrigin.getPlayerNBT().setTag("Inventory", player.inventory.writeToNBT(new NBTTagList()));
resyncOrigin.markDirty();
if (getPlayerNBT().hasKey("Inventory")) //try inserting persistent items by merging
{
mergeStoredInv(dummy.inventory);
}
}
else
{
dummy.inventory.clear();
}
if (!getPlayerNBT().hasKey("Inventory"))
{
tag.setInteger("sync_playerGameMode", player.interactionManager.getGameType().getID());
this.setPlayerNBT(tag); //Write the new data
}
}
else if (!getPlayerNBT().hasKey("Inventory")) //just go this way if configured
{
//Copy data needed from player
NBTTagCompound tag = new NBTTagCompound();
//Setup location for dummy
EntityPlayerMP dummy = setupDummy(player);
dummy.inventory.clear();
//Set data
dummy.writeToNBT(tag);
tag.setInteger("sync_playerGameMode", player.interactionManager.getGameType().getID());
this.setPlayerNBT(tag);
}
wasDead = false;
//Sync Forge persistent data as it's supposed to carry over on death
NBTTagCompound persistentData = player.getEntityData();
if (persistentData != null) {
NBTTagCompound forgeData = playerNBT.getCompoundTag("ForgeData");
forgeData.setTag(EntityPlayer.PERSISTED_NBT_TAG, player.getEntityData().getCompoundTag(EntityPlayer.PERSISTED_NBT_TAG));
persistentData.setBoolean("isDeathSyncing", false);
forgeData.setBoolean("isDeathSyncing", false);
playerNBT.setTag("ForgeData", forgeData);
}
NBTTagCompound persistent = player.getEntityData().getCompoundTag(EntityPlayer.PERSISTED_NBT_TAG);
int healthReduction = persistent.getInteger("Sync_HealthReduction");
//Also sync ender chest.
playerNBT.setTag("EnderItems", player.getInventoryEnderChest().saveInventoryToNBT());
//Update the players NBT stuff
player.readFromNBT(this.getPlayerNBT());
if(healthReduction > 0)
{
double curMaxHealth = player.getEntityAttribute(SharedMonsterAttributes.MAX_HEALTH).getBaseValue();
double morphMaxHealth = curMaxHealth - healthReduction;
if(morphMaxHealth < 1D)
{
morphMaxHealth = 1D;
}
if(morphMaxHealth != curMaxHealth)
{
player.getEntityAttribute(SharedMonsterAttributes.MAX_HEALTH).setBaseValue(morphMaxHealth);
}
}
player.interactionManager.initializeGameType(GameType.getByID(this.getPlayerNBT().getInteger("sync_playerGameMode"))); | Sync.channel.sendTo(new PacketNBT(this.getPlayerNBT()), player); | 3 |
docbleach/DocBleach | module/module-pdf/src/main/java/xyz/docbleach/module/pdf/PdfBleachSession.java | [
"public class BleachSession implements Serializable {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(BleachSession.class);\n private static final int MAX_ONGOING_TASKS = 10;\n private final transient Bleach bleach;\n private final Collection<Threat> threats = new ArrayList<>();\n /**\n * Counts ongoing tasks, to prevent fork bombs when handling zip archives for instance)\n */\n private int ongoingTasks = 0;\n\n public BleachSession(Bleach bleach) {\n this.bleach = bleach;\n }\n\n /**\n * The BleachSession is able to record threats encountered by the bleach.\n *\n * @param threat The removed threat object, containing the threat type and more information\n */\n public void recordThreat(Threat threat) {\n if (threat == null) {\n return;\n }\n LOGGER.trace(\"Threat recorded: \" + threat);\n threats.add(threat);\n }\n\n public Collection<Threat> getThreats() {\n return threats;\n }\n\n public int threatCount() {\n return threats.size();\n }\n\n /**\n * @return The bleach used in this session\n */\n public Bleach getBleach() {\n return bleach;\n }\n\n public void sanitize(InputStream is, OutputStream os) throws BleachException {\n try {\n if (ongoingTasks++ >= MAX_ONGOING_TASKS) {\n throw new RecursionBleachException(ongoingTasks);\n }\n if (!bleach.handlesMagic(is)) {\n return;\n }\n bleach.sanitize(is, os, this);\n } finally {\n ongoingTasks--;\n }\n }\n}",
"public class BleachException extends Exception {\n\n public BleachException(Throwable e) {\n super(e);\n }\n\n public BleachException(String message) {\n super(message);\n }\n}",
"@AutoValue\npublic abstract class Threat {\n\n public static Builder builder() {\n return new AutoValue_Threat.Builder();\n }\n\n @AutoValue.Builder\n public abstract static class Builder {\n\n public abstract Builder type(ThreatType value);\n\n public abstract Builder severity(ThreatSeverity value);\n\n public abstract Builder action(ThreatAction value);\n\n public abstract Builder location(String value);\n\n public abstract Builder details(String value);\n\n public abstract Threat build();\n }\n\n public abstract ThreatType type();\n\n public abstract ThreatSeverity severity();\n\n public abstract ThreatAction action();\n\n public abstract String location();\n\n public abstract String details();\n}",
"public enum ThreatAction {\n /**\n * No actions had to be taken, for instance if the threat is innocuous.\n */\n NOTHING,\n\n /**\n * The potential threat has been replaced by an innocuous content. ie: HTML file replaced by a\n * screenshot of the page\n */\n DISARM,\n\n /**\n * No actions were taken because of the configuration\n */\n IGNORE,\n\n /**\n * The threat has been removed.\n */\n REMOVE;\n}",
"public enum ThreatSeverity {\n LOW,\n MEDIUM,\n HIGH,\n EXTREME;\n}",
"public enum ThreatType {\n /**\n * Macros, JavaScript, ActiveX, AcroForms, DDEAUTO\n */\n ACTIVE_CONTENT,\n\n /**\n * Word Template linking to an external \"thing\", ...\n */\n EXTERNAL_CONTENT,\n\n /**\n * OLE Objects, ...\n */\n BINARY_CONTENT,\n\n /**\n * OLE Objects, strange image in a document ...\n */\n UNRECOGNIZED_CONTENT\n}"
] | import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.pdfbox.io.MemoryUsageSetting;
import org.apache.pdfbox.io.RandomAccessRead;
import org.apache.pdfbox.io.ScratchFile;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentCatalog;
import org.apache.pdfbox.pdmodel.PDDocumentNameDictionary;
import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException;
import org.apache.pdfbox.pdmodel.encryption.StandardProtectionPolicy;
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDDocumentOutline;
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.docbleach.api.BleachSession;
import xyz.docbleach.api.exception.BleachException;
import xyz.docbleach.api.threat.Threat;
import xyz.docbleach.api.threat.ThreatAction;
import xyz.docbleach.api.threat.ThreatSeverity;
import xyz.docbleach.api.threat.ThreatType; | package xyz.docbleach.module.pdf;
class PdfBleachSession {
private static final Logger LOGGER = LoggerFactory.getLogger(PdfBleachSession.class);
private static final String[] COMMON_PASSWORDS =
new String[]{null, "", "test", "example", "sample", "malware", "infected", "password"};
private static final MemoryUsageSetting MEMORY_USAGE_SETTING =
MemoryUsageSetting.setupMixed(1024 * 100);
private final BleachSession session;
private final COSObjectBleach cosObjectBleach;
PdfBleachSession(BleachSession session) {
this.session = session;
cosObjectBleach = new COSObjectBleach(this);
}
void sanitize(RandomAccessRead source, OutputStream outputStream)
throws IOException, BleachException {
final PDDocument doc = getDocument(source);
final PDDocumentCatalog docCatalog = doc.getDocumentCatalog();
sanitizeNamed(doc, docCatalog.getNames());
PDDocumentCatalogBleach catalogBleach = new PDDocumentCatalogBleach(this);
catalogBleach.sanitize(docCatalog);
sanitizeDocumentOutline(doc.getDocumentCatalog().getDocumentOutline());
cosObjectBleach.sanitizeObjects(doc.getDocument().getObjects());
doc.save(outputStream);
doc.close();
}
private void sanitizeDocumentOutline(PDDocumentOutline documentOutline) {
if (documentOutline == null) {
return;
}
documentOutline.children().forEach(this::sanitizeDocumentOutlineItem);
}
private void sanitizeDocumentOutlineItem(PDOutlineItem item) {
if (item.getAction() == null) {
return;
}
LOGGER.debug("Found&removed action on outline item (was {})", item.getAction());
item.setAction(null);
recordJavascriptThreat("DocumentOutline Item Action", "Action");
}
private void sanitizeNamed(PDDocument doc, PDDocumentNameDictionary names) {
if (names == null) {
return;
}
new PDEmbeddedFileBleach(this, doc).sanitize(names.getEmbeddedFiles());
if (names.getJavaScript() != null) {
recordJavascriptThreat("Named JavaScriptAction", "Action");
names.setJavascript(null);
}
}
private PDDocument getDocument(RandomAccessRead source) throws IOException, BleachException {
PDDocument doc;
for (String pwd : COMMON_PASSWORDS) {
ScratchFile scratchFile = new ScratchFile(MEMORY_USAGE_SETTING);
doc = testPassword(scratchFile, source, pwd);
if (doc != null) {
LOGGER.debug("Password was guessed: '{}'", pwd);
doc.protect(new StandardProtectionPolicy(pwd, pwd, doc.getCurrentAccessPermission()));
return doc;
}
scratchFile.close();
}
// @TODO: fetch password from config?
throw new BleachException("PDF is protected with an unknown password");
}
@SuppressFBWarnings(
value = "EXS_EXCEPTION_SOFTENING_RETURN_FALSE",
justification = "This method is an helper to check the password")
private PDDocument testPassword(ScratchFile inFile, RandomAccessRead source, String password)
throws IOException {
PDFParser parser = new PDFParser(source, password, inFile);
try {
parser.parse();
return parser.getPDDocument();
} catch (InvalidPasswordException e) {
LOGGER.error("The tested password is invalid");
return null;
} finally {
source.rewind((int) source.getPosition());
}
}
void recordJavascriptThreat(String location, String details) {
Threat threat = Threat.builder()
.type(ThreatType.ACTIVE_CONTENT)
.severity(ThreatSeverity.HIGH)
.details(details)
.location(location) | .action(ThreatAction.REMOVE) | 3 |
misberner/duzzt | processor/src/main/java/com/github/misberner/duzzt/processor/Duzzt.java | [
"public interface DuzztDiagnosticListener {\n\t\n\t/**\n\t * Called if an expression could not be parsed.\n\t * <p>\n\t * If the parse error occurred while parsing a named subexpression, the name\n\t * of the subexpression will also be passed as the <tt>exprName</tt> parameter.\n\t * Otherwise (that is, if the main expression could not be parsed), <tt>exprName</tt>\n\t * will be <tt>null</tt>.\n\t * \n\t * @param parseException the exception that was thrown while trying to parse\n\t * @param exprName the name of the named subexpression, or <tt>null</tt> if the parse\n\t * error occurred while parsing the main expression.\n\t */\n\tvoid unparseableExpression(Exception parseException, String exprName);\n\t\n\t/**\n\t * Called if an undefined identifier was referenced.\n\t * \n\t * @param id the undefined identifier that was referenced\n\t * @param exprName the name of the named subexpression, or <tt>null</tt> if the parse\n\t * error occurred while parsing the main expression.\n\t */\n\tvoid undefinedIdentifier(String id, String exprName);\n\t\n\t/**\n\t * Called if an undefined subexpression was referenced.\n\t * \n\t * @param subExprName the name of the undefined subexpression that was referenced\n\t * @param exprName the name of the named subexpression, or <tt>null</tt> if the parse\n\t * error occurred while parsing the main expression.\n\t */\n\tvoid undefinedSubExpression(String subExprName, String exprName);\n\t\n\t/**\n\t * Called if a subexpression was defined recursively.\n\t * \n\t * @param subExprName the name of the subexpression that was defined recursively\n\t */\n\tvoid recursiveSubExpression(String subExprName);\n\t\n\t/**\n\t * Called if a defined named subexpression was never used.\n\t * \n\t * @param subExprName the name of the subexpression that was never used\n\t */\n\tvoid unusedSubExpression(String subExprName);\n\t\n\t\n\t/**\n\t * Called when a generic information message is emitted.\n\t * \n\t * @param args the constituents of the message\n\t */\n\tvoid info(Object... args);\n\t\n\t/**\n\t * Called when a generic warning message is emitted.\n\t * \n\t * @param args the constituents of the message\n\t */\n\tvoid warning(Object... args);\n\t\n\t/**\n\t * Called when a generic error message is emitted.\n\t * \n\t * @param args the constituents of the message\n\t */\n\tvoid error(Object... args);\n}",
"public class DuzztAutomaton {\n\t\n\tprivate final List<DuzztState> states;\n\tprivate final DuzztState init;\n\t\n\t\n\t/**\n\t * Constructor. Initializes a Duzzt automaton from a collection of states\n\t * and an initial states.\n\t * \n\t * @param states the states of the automaton\n\t * @param init the initial state of the automaton, must be part of {@code states}\n\t * @throws IllegalArgumentException if {@code states} does not contain {@code init}.\n\t */\n\tpublic DuzztAutomaton(Collection<? extends DuzztState> states, DuzztState init)\n\t\t\tthrows IllegalArgumentException {\n\t\tif(!states.contains(init)) {\n\t\t\tthrow new IllegalArgumentException(\"Initial state not contained in state set\");\n\t\t}\n\t\tthis.states = new ArrayList<>(states);\n\t\tthis.init = init;\n\t\tthis.init.setInitial(true);\n\t}\n\n\n\tpublic void reassignStateIds(Types types) {\n\t\tfor(DuzztState s : states) {\n\t\t\ts.setId(-1);\n\t\t}\n\n\t\tList<DuzztAction> sortedActions = new ArrayList<>(getAllActions());\n\t\tComparator<DuzztAction> actionCmp = new DuzztAction.ActionComparator(types);\n\t\tCollections.sort(sortedActions, actionCmp);\n\n\t\tQueue<DuzztState> queue = new ArrayDeque<>();\n\n\t\tint id = 0;\n\t\tqueue.add(init);\n\t\tinit.setId(0);\n\n\t\twhile(!queue.isEmpty()) {\n\t\t\tDuzztState curr = queue.poll();\n\n\t\t\tfor(DuzztAction a : sortedActions) {\n\t\t\t\tDuzztState succ = curr.getSuccessor(a);\n\t\t\t\tif(succ != null && succ.getId() == -1) {\n\t\t\t\t\tqueue.add(succ);\n\t\t\t\t\tsucc.setId(id++);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\t/**\n\t * Retrieves the initial state.\n\t * @return the initial state\n\t */\n\tpublic DuzztState getInitialState() {\n\t\treturn init;\n\t}\n\t\n\t/**\n\t * Retrieves a list of all states.\n\t * @return the list of all states\n\t */\n\tpublic List<DuzztState> getStates() {\n\t\treturn states;\n\t}\n\n\tpublic Set<DuzztAction> getAllActions() {\n\t\tSet<DuzztAction> result = new HashSet<>();\n\t\tfor(DuzztState s : states) {\n\t\t\tresult.addAll(s.getActions());\n\t\t}\n\t\treturn result;\n\t}\n}",
"public class BricsCompiler implements DuzztCompiler {\n\t\n\tprivate class RETranslator implements DuzztREVisitor<Void, StringBuilder> {\n\t\t@Override\n\t\tpublic Void visit(DuzztREAlt re, StringBuilder sb) {\n\t\t\tsb.append('(');\n\t\t\tIterator<? extends DuzztRegExp> childIt = re.getChildren().iterator();\n\t\t\tchildIt.next().accept(this, sb);\n\t\t\twhile(childIt.hasNext()) {\n\t\t\t\tsb.append('|');\n\t\t\t\tchildIt.next().accept(this, sb);\n\t\t\t}\n\t\t\tsb.append(')');\n\t\t\treturn null;\n\t\t}\n\t\t@Override\n\t\tpublic Void visit(DuzztREConcat re, StringBuilder sb) {\n\t\t\tfor(DuzztRegExp child : re.getChildren()) {\n\t\t\t\tchild.accept(this, sb);\n\t\t\t}\n\t\t\treturn null;\n\t\t}\n\t\t@Override\n\t\tpublic Void visit(DuzztREIdentifier re, StringBuilder sb) {\n\t\t\tCharRange range = id2range.get(re.getName());\n\t\t\tif(range == null) {\n\t\t\t\tthrow new UndefinedIdentifierException(re.getName());\n\t\t\t}\n\t\t\tappendRange(range.getLow(), range.getHigh(), sb);\n\t\t\treturn null;\n\t\t}\n\t\t@Override\n\t\tpublic Void visit(DuzztREModifier re, StringBuilder sb) {\n\t\t\tsb.append('(');\n\t\t\tre.getSub().accept(this, sb);\n\t\t\tsb.append(')');\n\t\t\tsb.append(re.getModChar());\n\t\t\treturn null;\n\t\t}\n\t\t@Override\n\t\tpublic Void visit(DuzztRESubexpr re, StringBuilder sb) {\n\t\t\tsb.append('<');\n\t\t\tsb.append(re.getSubexprName());\n\t\t\tsb.append('>');\n\t\t\treturn null;\n\t\t}\n\t\t@Override\n\t\tpublic Void visit(DuzztRENonEmpty re, StringBuilder sb) {\n\t\t\tsb.append(\"((\");\n\t\t\tre.getSub().accept(this, sb);\n\t\t\tsb.append(\")&~())\");\n\t\t\treturn null;\n\t\t}\n\t\t@Override\n\t\tpublic Void visit(DuzztREStart re, StringBuilder sb) {\n\t\t\tappendRaw(startChar, sb);\n\t\t\treturn null;\n\t\t}\n\t\t@Override\n\t\tpublic Void visit(DuzztREEnd re, StringBuilder sb) {\n\t\t\tappendRaw(endChar, sb);\n\t\t\treturn null;\n\t\t}\n\t\t@Override\n\t\tpublic Void visit(DuzztREInner re, StringBuilder sb) {\n\t\t\tappendRaw(innerChar, sb);\n\t\t\treturn null;\n\t\t}\n\t\t\n\t}\n\t\n\tprivate final ImplementationModel impl;\n\t\n\tprivate final Map<String,CharRange> id2range\n\t\t= new HashMap<>();\n\tprivate final DuzztAction[] actions;\n\t\n\tprivate final char[] globalActionCodes;\n\t\n\tprivate final char overallLow, overallHigh;\n\tprivate final char startChar, endChar, innerChar;\n\t\n\tpublic BricsCompiler(ImplementationModel impl) {\n\t\tthis.impl = impl;\n\t\tint numActions = impl.getAllActions().size();\n\t\tthis.actions = new DuzztAction[numActions];\n\t\tthis.globalActionCodes = new char[impl.getGlobalActions().size()];\n\t\tthis.overallLow = Character.MIN_VALUE;\n\t\tthis.overallHigh = (char)(this.overallLow + numActions - 1);\n\t\tthis.startChar = (char)(overallHigh + 1);\n\t\tthis.endChar = (char)(overallHigh + 2);\n\t\tthis.innerChar = (char)(overallHigh + 3);\n\t\tassignActionCodes();\n\t}\n\t\n\tpublic DuzztAction getAction(char c) {\n\t\tif(c < overallLow || c > overallHigh) {\n\t\t\treturn null;\n\t\t}\n\t\tint ofs = c - overallLow;\n\t\tassert ofs < actions.length;\n\t\t\n\t\treturn actions[ofs];\n\t}\n\t\n\t\n\tpublic DuzztAutomaton compile(DuzztRegExp re, Map<String,SubExpression> subExpressions) {\n\t\tMap<String, Automaton> subexprAutomata = new HashMap<>();\n\t\t\n\t\tSubExpression rootSubExpr = new SubExpression(re);\n\t\t\n\t\tAutomaton bricsAutomaton = doCompile(rootSubExpr, subExpressions, subexprAutomata);\n\t\t\n\t\tbricsAutomaton = postProcess(bricsAutomaton);\n\t\t\n\t\treturn toDuzztAutomaton(bricsAutomaton);\n\t}\n\t\n\tprivate Automaton postProcess(Automaton bricsAutomaton) {\n\t\t// Determinize & mininimize in order to remove sinks\n\t\tbricsAutomaton.determinize();\n\t\tbricsAutomaton.minimize();\n\t\t\t\t\n\t\tfor(State s : bricsAutomaton.getStates()) {\n\t\t\t// Set accepting (make prefix closed)\n\t\t\ts.setAccept(true);\n\t\t\t// Add global actions\n\t\t\tfor(char c : globalActionCodes) {\n\t\t\t\tState succ = s.step(c);\n\t\t\t\tif(succ == null) {\n\t\t\t\t\t// add self-loop\n\t\t\t\t\ts.addTransition(new Transition(c, s));\n\t\t\t\t}\n\t\t\t}\n\t\t\tSet<Transition> transitions = s.getTransitions();\n\t\t\t// Turn terminator actions into self loops\n\t\t\tIterator<Transition> transIt = transitions.iterator();\n\t\t\tList<Transition> newTransitions = new ArrayList<>();\n\t\t\twhile(transIt.hasNext()) {\n\t\t\t\tTransition t = transIt.next();\n\n\t\t\t\tState succ = t.getDest();\n\t\t\t\tif(succ != s) {\n\t\t\t\t\tchar low = t.getMin();\n\t\t\t\t\tchar high = t.getMax();\n\n\t\t\t\t\tboolean removed = false;\n\t\t\t\t\tfor(char c = low; c <= high; c++) {\n\t\t\t\t\t\tDuzztAction act = getAction(c);\n\t\t\t\t\t\tif(act.isTerminator() || act == null) {\n\t\t\t\t\t\t\tif(!removed) {\n\t\t\t\t\t\t\t\ttransIt.remove();\n\t\t\t\t\t\t\t\tremoved = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tnewTransitions.add(new Transition(c, s));\n\t\t\t\t\t\t\tif(c > low) {\n\t\t\t\t\t\t\t\tnewTransitions.add(new Transition(low, (char)(c-1), succ));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tlow = (char)(c+1);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif(removed && low <= high) {\n\t\t\t\t\t\tnewTransitions.add(new Transition(low, high, succ));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\ttransitions.addAll(newTransitions);\n\t\t}\n\t\t\n\t\tbricsAutomaton.minimize();\n\t\treturn bricsAutomaton;\n\t}\n\t\n\tprivate DuzztAutomaton toDuzztAutomaton(Automaton bricsAutomaton) {\n\t\tMap<State,DuzztState> stateMap = new HashMap<>();\n\t\t\n\t\tint id = 0;\n\t\tfor(State bricsState : bricsAutomaton.getStates()) {\n\t\t\tif(!bricsState.getTransitions().isEmpty()) {\n\t\t\t\tDuzztState duzztState = new DuzztState(id++);\n\t\t\t\tstateMap.put(bricsState, duzztState);\n\t\t\t}\n\t\t}\n\t\t\n\t\tfor(Map.Entry<State,DuzztState> e : stateMap.entrySet()) {\n\t\t\tState bricsState = e.getKey();\n\t\t\tDuzztState duzztState = e.getValue();\n\t\t\t\n\t\t\tfor(Transition t : bricsState.getTransitions()) {\n\t\t\t\tState bricsDest = t.getDest();\n\t\t\t\tDuzztState duzztDest = stateMap.get(bricsDest);\n\t\t\t\t\n\t\t\t\tfor(char c = t.getMin(); c <= t.getMax(); c++) {\n\t\t\t\t\tDuzztAction act = getAction(c);\n\t\t\t\t\tif(act != null) {\n\t\t\t\t\t\tDuzztState succ = (act.isTerminator()) ? null : duzztDest;\n\t\t\t\t\t\tduzztState.addTransition(act, succ);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tDuzztState duzztInit = stateMap.get(bricsAutomaton.getInitialState());\n\t\t\n\t\treturn new DuzztAutomaton(stateMap.values(), duzztInit);\n\t}\n\t\n\tprivate Automaton doCompile(SubExpression expr, Map<String,SubExpression> subExpressions, Map<String,Automaton> subexprAutomata)\n\t\t\tthrows UndefinedSubExpressionException, RecursiveSubExpressionException {\n\t\tSet<String> subExprRefs = DuzztREUtil.findReferencedSubexprs(expr.getExpression());\n\t\t\n\t\tfor(String subExprRef : subExprRefs) {\n\t\t\tSubExpression subExpr = subExpressions.get(subExprRef);\n\t\t\tif(subExpr == null) {\n\t\t\t\tthrow new UndefinedSubExpressionException(subExprRef);\n\t\t\t}\n\t\t\t\n\t\t\tif(!subexprAutomata.containsKey(subExprRef)) {\n\t\t\t\tsubexprAutomata.put(subExprRef, null);\n\t\t\t\tAutomaton a = doCompile(subExpr, subExpressions, subexprAutomata);\n\t\t\t\tsubexprAutomata.put(subExprRef, a);\n\t\t\t}\n\t\t\telse if(subexprAutomata.get(subExprRef) == null) {\n\t\t\t\tthrow new RecursiveSubExpressionException(subExprRef);\n\t\t\t}\n\t\t}\n\t\t\n\t\tStringBuilder sb = new StringBuilder();\n\t\tif(expr.isOwnScope()) {\n\t\t\tsb.append('(');\n\t\t\tappendRaw(startChar, sb);\n\t\t\tsb.append(\"?(\");\n\t\t}\n\t\texpr.getExpression().accept(new RETranslator(), sb);\n\t\tif(expr.isOwnScope()) {\n\t\t\tsb.append(\"))?&(\");\n\t\t\tappendRaw(startChar, sb);\n\t\t\tsb.append(\"[^\");\n\t\t\tappendRaw(startChar, sb);\n\t\t\tsb.append(\"]*\");\n\t\t\tsb.append(')');\n\t\t}\n\t\tString bricsReStr = sb.toString();\n\t\t\n\t\tRegExp bricsRe = new RegExp(bricsReStr, RegExp.AUTOMATON | RegExp.INTERSECTION | RegExp.COMPLEMENT);\n\t\tAutomaton automaton = bricsRe.toAutomaton(subexprAutomata);\n\t\t\n\t\tif(expr.isOwnScope()) {\n\t\t\tautomaton = closeScope(automaton);\n\t\t}\n\t\treturn automaton;\n\t}\n\t\n\tprivate Automaton closeScope(Automaton automaton) {\n\t\t// Make sure automaton is deterministic\n\t\tautomaton.determinize();\n\t\t\n\t\t// Skip the starting character, as it is not part of the actual sequence\n\t\tState oldInit = automaton.getInitialState();\n\t\tState realInit = oldInit.step(startChar);\n\t\t\n\t\t// Duplicate the initial state, as it will *not* receive any epsilon-transitions\n\t\t// for the inner character\n\t\tState newInit = new State();\n\t\tnewInit.setAccept(true);\n\t\tnewInit.getTransitions().addAll(realInit.getTransitions());\n\t\t\n\t\tautomaton.setInitialState(newInit);\n\t\t\n\n\t\tautomaton.setDeterministic(false);\n\t\t\n\t\tfor(State s : automaton.getStates()) {\n\t\t\ts.setAccept(true);\n\t\t\tif(s.step(endChar) != null) {\n\t\t\t\ts.getTransitions().clear();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t\n\t\t\tif(s != newInit) {\n\t\t\t\tState innerSucc = s.step(innerChar);\n\t\t\t\tif(innerSucc != null) {\n\t\t\t\t\tautomaton.addEpsilons(Collections.singleton(new StatePair(s, innerSucc)));\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t// Remove all transitions with special characters\n\t\t\tList<Transition> newTransitions = new ArrayList<>();\n\t\t\tSet<Transition> transSet = s.getTransitions();\n\t\t\tIterator<Transition> transIt = transSet.iterator();\n\t\t\t\n\t\t\twhile(transIt.hasNext()) {\n\t\t\t\tTransition t = transIt.next();\n\t\t\t\tState succ = t.getDest();\n\t\t\t\t\n\t\t\t\tif(t.getMax() > overallHigh) {\n\t\t\t\t\ttransIt.remove();\n\t\t\t\t\tif(t.getMin() <= overallHigh) {\n\t\t\t\t\t\tnewTransitions.add(new Transition(t.getMin(), overallHigh, succ));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\ttransSet.addAll(newTransitions);\n\t\t}\n\t\t\n\t\tautomaton.determinize();\n\t\tautomaton.minimize();\n\t\t\n\t\treturn automaton;\n\t}\n\t\n\tprivate void assignActionCodes() {\n\t\tchar c = overallLow;\n\t\t\n\t\tint globalIdx = 0;\n\t\t\n\t\tfor(Map.Entry<String,List<DuzztAction>> entry : impl.getActionLists()) {\n\t\t\tString name = entry.getKey();\n\t\t\tList<DuzztAction> actions = entry.getValue();\n\t\t\t\n\t\t\tchar low = c;\n\t\t\t\n\t\t\tfor(DuzztAction a : actions) {\n\t\t\t\tif(a.isGlobal()) {\n\t\t\t\t\tglobalActionCodes[globalIdx++] = c;\n\t\t\t\t}\n\t\t\t\tthis.actions[c++ - overallLow] = a;\n\t\t\t}\n\t\t\tchar high = (char)(c - 1);\n\t\t\t\n\t\t\tid2range.put(name, new CharRange(low, high));\n\t\t}\n\t}\n\t\n\tprivate static void appendRaw(char c, StringBuilder sb) {\n\t\tsb.append('\\\\').append(c);\n\t}\n\t\n\tprivate static void appendRange(char low, char high, StringBuilder sb) {\n\t\tif(low == high) {\n\t\t\tappendRaw(low, sb);\n\t\t}\n\t\telse {\n\t\t\tsb.append('[');\n\t\t\tappendRaw(low, sb);\n\t\t\tsb.append('-');\n\t\t\tappendRaw(high, sb);\n\t\t\tsb.append(']');\n\t\t}\n\t}\n\n}",
"public class DuzztInitializationException extends Exception {\n\t\n\tprivate static final long serialVersionUID = 1L;\n\n\tpublic DuzztInitializationException() {\n\t\tsuper();\n\t}\n\n\tpublic DuzztInitializationException(String message, Throwable cause) {\n\t\tsuper(message, cause);\n\t}\n\n\tpublic DuzztInitializationException(String message) {\n\t\tsuper(message);\n\t}\n\n\tpublic DuzztInitializationException(Throwable cause) {\n\t\tsuper(cause);\n\t}\n\t\n\t\n\n}",
"public class DSLSettings {\n\t\n\tprivate static final Map<String,SubExpression> parseSubexpressions(SubExpr[] subExprs) {\n\t\tMap<String,SubExpression> result = new HashMap<>();\n\t\t\n\t\tfor(SubExpr se : subExprs) {\n\t\t\tSubExpression parsed = new SubExpression(se);\n\t\t\tresult.put(parsed.getName(), parsed);\n\t\t}\n\t\t\n\t\treturn result;\n\t}\n\n\tprivate final String name;\n\tprivate final String packageRef;\n\t\n\tprivate final DuzztRegExp syntax;\n\tprivate final Map<String,SubExpression> subExpressions; \n\t\n\tprivate final boolean enableAllMethods;\n\tprivate final boolean autoVarArgs;\n\tprivate final boolean forwardAllConstructors;\n\tprivate final boolean nonVoidTerminators;\n\t\n\tprivate final boolean includeInherited;\n\n\tprivate boolean classPublic;\n\tprivate AFModifier modifier;\n\t\n\tprivate final Visibility delegateConstructorVisibility;\n\tprivate final Visibility forwardConstructorVisibility;\n\n\tprivate final boolean skipGeneratedAnnotation;\n\t\n\tpublic DSLSettings(GenerateEmbeddedDSL annotation) {\n\t\tthis.name = annotation.name();\n\t\tthis.packageRef = annotation.packageName();\n\t\t\n\t\tthis.syntax = DuzztRegExpParser.parse(annotation.syntax());\n\t\tthis.subExpressions = parseSubexpressions(annotation.where());\n\t\t\n\t\tthis.autoVarArgs = annotation.autoVarArgs();\n\t\tthis.delegateConstructorVisibility = annotation.delegateConstructorVisibility();\n\t\tthis.forwardConstructorVisibility = annotation.forwardConstructorVisibility();\n\t\tthis.enableAllMethods = annotation.enableAllMethods();\n\t\tthis.forwardAllConstructors = annotation.forwardAllConstructors();\n\t\tthis.nonVoidTerminators = annotation.nonVoidTerminators();\n\t\t\n\t\tthis.includeInherited = annotation.includeInherited();\n\n\t\tthis.classPublic = annotation.classPublic();\n\t\tthis.modifier = annotation.modifier();\n\n\t\tthis.skipGeneratedAnnotation = annotation.skipGeneratedAnnotation();\n\t}\n\t\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\t\n\tpublic String getPackageRef() {\n\t\treturn packageRef;\n\t}\n\t\n\tpublic DuzztRegExp getSyntax() {\n\t\treturn syntax;\n\t}\n\t\n\tpublic boolean isAutoVarArgs() {\n\t\treturn autoVarArgs;\n\t}\n\t\n\tpublic boolean isEnableAllMethods() {\n\t\treturn enableAllMethods;\n\t}\n\t\n\tpublic boolean isForwardAllConstructors() {\n\t\treturn forwardAllConstructors;\n\t}\n\t\n\tpublic boolean isIncludeInherited() {\n\t\treturn includeInherited;\n\t}\n\t\n\tpublic Visibility getDelegateConstructorVisibility() {\n\t\treturn delegateConstructorVisibility;\n\t}\n\t\n\tpublic Map<String,SubExpression> getSubExpressions() {\n\t\treturn Collections.unmodifiableMap(subExpressions);\n\t}\n\t\n\tpublic Visibility getForwardConstructorVisibility() {\n\t\treturn forwardConstructorVisibility;\n\t}\n\t\n\t\n\tpublic boolean isDefaultAutoVarArgs(ExecutableElement method) {\n\t\tif(!autoVarArgs) {\n\t\t\treturn false;\n\t\t}\n\t\tif(method.isVarArgs()) {\n\t\t\treturn false;\n\t\t}\n\t\tif(method.getParameters().isEmpty()) {\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\t\n\tpublic boolean isDefaultTerminator(ExecutableElement method) {\n\t\tif(!nonVoidTerminators) {\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\treturn (method.getReturnType().getKind() == TypeKind.VOID);\n\t}\n\n\tpublic boolean isNonVoidTerminators() {\n\t\treturn nonVoidTerminators;\n\t}\n\n\tpublic boolean isClassPublic() {\n\t\treturn classPublic;\n\t}\n\n\tpublic AFModifier getModifier() {\n\t\treturn modifier;\n\t}\n\n\tpublic boolean isSkipGeneratedAnnotation() {\n\t\treturn skipGeneratedAnnotation;\n\t}\n}",
"public class DSLSpecification {\n\t\n\t\n\tpublic static DSLSpecification create(\n\t\t\tTypeElement type,\n\t\t\tDSLSettings settings,\n\t\t\tElements elementUtils,\n\t\t\tTypes typeUtils) {\n\t\tImplementationModel model = ImplementationModel.create(type, settings, elementUtils, typeUtils);\n\t\t\n\t\treturn new DSLSpecification(settings, model);\n\t}\n\t\n\tprivate final DSLSettings settings;\n\tprivate final String packageName;\n\tprivate final boolean samePackage;\n\t\n\tprivate final ImplementationModel implementation;\n\t\n\t\n\tprivate DSLSpecification(DSLSettings settings, ImplementationModel model) {\n\t\t\n\t\tthis.settings = settings;\n\t\tString implPackage = ElementUtils.getPackageName(model.getType());\n\t\tthis.packageName = NameUtils.resolvePackageName(settings.getPackageRef(), implPackage);\n\t\tthis.samePackage = implPackage.equals(packageName);\n\t\n\t\tthis.implementation = model;\n\t}\n\t\n\tpublic List<ForwardConstructor> getForwardConstructors() {\n\t\tVisibility minVis = (samePackage) ? Visibility.PACKAGE_PRIVATE : Visibility.PUBLIC;\n\t\treturn implementation.getForwardConstructors(minVis);\n\t}\n\t\n\t\n\tpublic DuzztRegExp getDSLSyntax() {\n\t\treturn settings.getSyntax();\n\t}\n\t\n\tpublic Map<String,SubExpression> getSubExpressions() {\n\t\treturn settings.getSubExpressions();\n\t}\n\t\n\tpublic Visibility getDelegateConstructorVisibility() {\n\t\treturn Visibility.of(implementation.getType()).meet(settings.getDelegateConstructorVisibility());\n\t}\n\t\n\tpublic ImplementationModel getImplementation() {\n\t\treturn implementation;\n\t}\n\t\n\t\n\tpublic String getClassName() {\n\t\treturn settings.getName();\n\t}\n\t\n\tpublic String getPackageName() {\n\t\treturn packageName;\n\t}\n\t\n\tpublic String getNonDefaultPackageName() {\n\t\treturn packageName.isEmpty() ? null : packageName;\n\t}\n\t\n\tpublic String getQualifiedClassName() {\n\t\tif(packageName.isEmpty()) {\n\t\t\treturn settings.getName();\n\t\t}\n\t\treturn packageName + \".\" + settings.getName();\n\t}\n\n\tpublic boolean isClassPublic() {\n\t\treturn settings.isClassPublic();\n\t}\n\n\tpublic AFModifier getModifier() {\n\t\treturn settings.getModifier();\n\t}\n\n\tpublic boolean isSkipGeneratedAnnotation() {\n\t\treturn settings.isSkipGeneratedAnnotation();\n\t}\n\n}",
"public class ImplementationModel {\n\t\n\tpublic static ImplementationModel create(\n\t\t\tTypeElement type,\n\t\t\tDSLSettings settings,\n\t\t\tElements elementUtils,\n\t\t\tTypes typeUtils) {\n\t\tImplementationModel model = new ImplementationModel(type);\n\t\tmodel.initialize(settings, elementUtils, typeUtils);\n\t\t\n\t\treturn model;\n\t}\n\t\n\tprivate final TypeElement type;\n\tprivate final Map<String,List<DuzztAction>> actionLists = new HashMap<>();\n\tprivate final List<DuzztAction> allActions = new ArrayList<>();\n\tprivate final List<DuzztAction> globalActions = new ArrayList<>();\n\tprivate final List<DuzztAction> terminatorActions = new ArrayList<>();\n\t\n\tprivate final List<ForwardConstructor> forwardConstructors = new ArrayList<>();\n\t\n\tprivate ImplementationModel(TypeElement type) {\n\t\tif(Visibility.of(type) == Visibility.PRIVATE) {\n\t\t\tthrow new IllegalArgumentException(\"Visibility of implementation class \"\n\t\t\t\t\t+ type + \" must not be private\");\n\t\t}\n\t\t\n\t\tthis.type = type;\n\t}\n\t\n\tprivate void initialize(DSLSettings settings, Elements elementUtils, Types typeUtils) {\n\t\tfindForwardConstructors(settings, typeUtils);\n\t\tfindActions(settings, elementUtils);\n\t}\n\t\n\tpublic TypeElement getType() {\n\t\treturn type;\n\t}\n\t\n\tpublic Visibility getVisibility() {\n\t\treturn Visibility.of(type);\n\t}\n\t\n\tpublic boolean isStandaloneInstantiable() {\n\t\treturn TypeUtils.isStandaloneInstantiable(type);\n\t}\n\t\n\tpublic List<? extends TypeParameterElement> getTypeParameters() {\n\t\treturn type.getTypeParameters();\n\t}\n\t\n\tpublic List<ForwardConstructor> getForwardConstructors(Visibility minVisibility) {\n\t\tif(minVisibility == Visibility.PACKAGE_PRIVATE) {\n\t\t\treturn Collections.unmodifiableList(forwardConstructors);\n\t\t}\n\t\tList<ForwardConstructor> result = new ArrayList<>();\n\t\t\n\t\tfor(ForwardConstructor fwdCtor : forwardConstructors) {\n\t\t\tif(fwdCtor.getOriginalVisibility().compareTo(minVisibility) >= 0) {\n\t\t\t\tresult.add(fwdCtor);\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn result;\n\t}\n\t\n\tpublic Set<String> getActionNames() {\n\t\treturn Collections.unmodifiableSet(actionLists.keySet());\n\t}\n\t\n\tpublic boolean hasActionName(String actName) {\n\t\treturn actionLists.containsKey(actName);\n\t}\n\t\n\tpublic Set<? extends Map.Entry<String,List<DuzztAction>>> getActionLists() {\n\t\treturn Collections.unmodifiableSet(actionLists.entrySet());\n\t}\n\t\n\tpublic List<DuzztAction> getAllActions() {\n\t\treturn Collections.unmodifiableList(allActions);\n\t}\n\t\n\tpublic List<DuzztAction> getGlobalActions() {\n\t\treturn Collections.unmodifiableList(globalActions);\n\t}\n\t\n\tpublic List<DuzztAction> getTerminatorActions() {\n\t\treturn Collections.unmodifiableList(terminatorActions);\n\t}\n\t\n\t\n\tprivate void findActions(DSLSettings settings, Elements elementUtils) {\n\t\tList<? extends Element> members;\n\t\tif(settings.isIncludeInherited()) {\n\t\t\tmembers = elementUtils.getAllMembers(type);\n\t\t}\n\t\telse {\n\t\t\tmembers = type.getEnclosedElements();\n\t\t}\n\t\tList<? extends ExecutableElement> methods = ElementFilter.methodsIn(members);\n\t\t\n\t\tfor(ExecutableElement m : methods) {\n\t\t\tDuzztAction a = DuzztAction.fromMethod(m, settings);\n\t\t\tif(a != null) {\n\t\t\t\tString name = a.getName();\n\t\t\t\tList<DuzztAction> lst = actionLists.get(name);\n\t\t\t\tif(lst == null) {\n\t\t\t\t\tlst = new ArrayList<>();\n\t\t\t\t\tactionLists.put(name, lst);\n\t\t\t\t}\n\t\t\t\tlst.add(a);\n\t\t\t\t\n\t\t\t\tallActions.add(a);\n\t\t\t\tif(a.isGlobal()) {\n\t\t\t\t\tglobalActions.add(a);\n\t\t\t\t}\n\t\t\t\tif(a.isTerminator()) {\n\t\t\t\t\tterminatorActions.add(a);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprivate void findForwardConstructors(DSLSettings settings, Types typeUtils) {\n\t\tif(!TypeUtils.isStandaloneInstantiable(type)) {\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tList<ExecutableElement> constructors = TypeUtils.getConstructors(type);\n\t\t\n\t\tfor(ExecutableElement ctor : constructors) {\n\t\t\tif(Visibility.of(ctor) == Visibility.PRIVATE) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t\n\t\t\tList<? extends VariableElement> params = ctor.getParameters();\n\t\t\t// Check if the erasure of this parameter list conflicts\n\t\t\t// with the delegate constructor\n\t\t\tif(params.size() == 1) {\n\t\t\t\tVariableElement param = params.get(0);\n\t\t\t\tTypeMirror erasedParamType = typeUtils.erasure(param.asType());\n\t\t\t\tTypeMirror erasedImplType = typeUtils.erasure(type.asType());\n\t\t\t\tif(erasedParamType.equals(erasedImplType)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tForwardConstructor fwd = ForwardConstructor.from(ctor, settings);\n\t\t\t\n\t\t\tif(fwd != null) {\n\t\t\t\tforwardConstructors.add(fwd);\n\t\t\t}\n\t\t}\n\t}\n\n}",
"public abstract class DuzztREUtil {\n\t\n\tprivate static final DuzztREVisitor<Void, Collection<? super String>> findIdentifiersVisitor\n\t\t= new AbstractDuzztREVisitor<Void,Collection<? super String>>() {\n\t\t\t@Override\n\t\t\tprotected Void defaultVisitComplex(DuzztComplexRegExp re,\n\t\t\t\t\tCollection<? super String> data) {\n\t\t\t\tvisitChildren(re, data);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\t@Override\n\t\t\tpublic Void visit(DuzztREIdentifier re,\n\t\t\t\t\tCollection<? super String> data) {\n\t\t\t\tdata.add(re.getName());\n\t\t\t\treturn null;\n\t\t\t}\n\t};\n\t\n\tprivate static final DuzztREVisitor<Void, Collection<? super String>> findSubexprsVisitor\n\t\t= new AbstractDuzztREVisitor<Void,Collection<? super String>>() {\n\t\t\t@Override\n\t\t\tprotected Void defaultVisitComplex(DuzztComplexRegExp re,\n\t\t\t\t\tCollection<? super String> data) {\n\t\t\t\tvisitChildren(re, data);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\t@Override\n\t\t\tpublic Void visit(DuzztRESubexpr re, Collection<? super String> data) {\n\t\t\t\tdata.add(re.getSubexprName());\n\t\t\t\treturn null;\n\t\t\t}\n\t};\n\n\t\n\tpublic static void findReferencedSubexprs(DuzztRegExp re, Collection<? super String> coll) {\n\t\tre.accept(findSubexprsVisitor, coll);\n\t}\n\t\n\tpublic static Set<String> findReferencedSubexprs(DuzztRegExp re) {\n\t\tSet<String> set = new HashSet<>();\n\t\tfindReferencedSubexprs(re, set);\n\t\treturn set;\t\n\t}\n\t\n\tpublic static void findIdentifiers(DuzztRegExp re, Collection<? super String> coll) {\n\t\tre.accept(findIdentifiersVisitor, coll);\n\t}\n\t\n\tpublic static Set<String> findIdentifiers(DuzztRegExp re) {\n\t\tSet<String> set = new HashSet<>();\n\t\tfindIdentifiers(re, set);\n\t\treturn set;\n\t}\n\t\n\tprivate DuzztREUtil() {}\n}",
"public interface DuzztRegExp {\n\t<R,D> R accept(DuzztREVisitor<R, D> visitor, D data);\n}"
] | import java.io.BufferedWriter;
import java.io.IOException;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import javax.annotation.processing.Filer;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.TypeElement;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
import javax.tools.JavaFileObject;
import org.stringtemplate.v4.AutoIndentWriter;
import org.stringtemplate.v4.ST;
import org.stringtemplate.v4.STGroup;
import org.stringtemplate.v4.STGroupFile;
import org.stringtemplate.v4.STWriter;
import com.github.misberner.apcommons.reporting.Reporter;
import com.github.misberner.apcommons.util.APUtils;
import com.github.misberner.apcommons.util.ElementUtils;
import com.github.misberner.duzzt.DuzztDiagnosticListener;
import com.github.misberner.duzzt.annotations.GenerateEmbeddedDSL;
import com.github.misberner.duzzt.automaton.DuzztAutomaton;
import com.github.misberner.duzzt.bricscompiler.BricsCompiler;
import com.github.misberner.duzzt.exceptions.DuzztInitializationException;
import com.github.misberner.duzzt.model.DSLSettings;
import com.github.misberner.duzzt.model.DSLSpecification;
import com.github.misberner.duzzt.model.ImplementationModel;
import com.github.misberner.duzzt.re.DuzztREUtil;
import com.github.misberner.duzzt.re.DuzztRegExp; | /*
*
* Copyright (c) 2014 by Malte Isberner (https://github.com/misberner).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.misberner.duzzt.processor;
public class Duzzt {
public static boolean checkExpressions(DuzztDiagnosticListener el, ImplementationModel im, DuzztRegExp re, Map<String,DuzztRegExp> subExpressions) {
return doCheck(el, im, re, null, subExpressions, new HashMap<String,Integer>());
}
private static boolean doCheck(DuzztDiagnosticListener el, ImplementationModel im, DuzztRegExp re, String reName,
Map<String,DuzztRegExp> subExpressions, Map<String,Integer> visited) {
visited.put(reName, 1);
boolean error = false;
Set<String> identifiers = DuzztREUtil.findIdentifiers(re);
for(String id : identifiers) {
if(!im.hasActionName(id)) {
el.undefinedIdentifier(id, reName);
error = true;
}
}
Set<String> subExprs = DuzztREUtil.findReferencedSubexprs(re);
for(String se : subExprs) {
DuzztRegExp seRe = subExpressions.get(se);
if(seRe == null) {
el.undefinedSubExpression(se, reName);
error = true;
}
else {
Integer state = visited.get(se);
if(state == null) {
error |= doCheck(el, im, seRe, se, subExpressions, visited);
}
else if(state == 1) {
el.recursiveSubExpression(se);
error = true;
}
}
}
visited.put(reName, 2);
return error;
}
private static final String ST_ENCODING = "UTF-8";
private static final char ST_DELIM_START_CHAR = '<';
private static final char ST_DELIM_STOP_CHAR = '>';
private static final String ST_RESOURCE_NAME = "/stringtemplates/edsl-source.stg";
private static final String ST_MAIN_TEMPLATE_NAME = "edsl_source";
private STGroup sourceGenGroup;
private boolean isJava9OrNewer;
/**
* Default constructor.
*/
public Duzzt() {
}
public boolean isInitialized() {
return (sourceGenGroup != null);
}
/**
* Initialize the Duzzt embedded DSL generator.
*
* @param utils the APUtils instance wrapping the {@link javax.annotation.processing.ProcessingEnvironment}
* @throws DuzztInitializationException if a fatal error occurs during initialization
*/ | public void init(APUtils utils) throws DuzztInitializationException { | 3 |
kakao/hbase-tools | hbase0.98/hbase-manager-0.98/src/main/java/com/kakao/hbase/manager/Manager.java | [
"public class ManagerArgs extends Args {\n public ManagerArgs(String[] args) throws IOException {\n super(args);\n }\n\n @Override\n protected OptionParser createOptionParser() {\n OptionParser optionParser = createCommonOptionParser();\n optionParser.accepts(OPTION_OPTIMIZE).withRequiredArg().ofType(String.class);\n optionParser.accepts(OPTION_BALANCE_FACTOR).withRequiredArg().ofType(String.class);\n optionParser.accepts(OPTION_REGION_SERVER).withRequiredArg().ofType(String.class);\n optionParser.accepts(OPTION_TURN_BALANCER_OFF);\n optionParser.accepts(OPTION_MOVE_ASYNC);\n optionParser.accepts(OPTION_MAX_ITERATION).withRequiredArg().ofType(Integer.class);\n optionParser.accepts(OPTION_SKIP_EXPORT);\n optionParser.accepts(OPTION_WAIT_UNTIL_FINISH);\n optionParser.accepts(OPTION_LOCALITY_THRESHOLD).withRequiredArg().ofType(Double.class);\n optionParser.accepts(OPTION_CF).withRequiredArg().ofType(String.class);\n optionParser.accepts(OPTION_INTERACTIVE);\n optionParser.accepts(OPTION_PHOENIX);\n return optionParser;\n }\n}",
"public abstract class Args {\n public static final String OPTION_REGION = \"region\";\n public static final String OPTION_OUTPUT = \"output\";\n public static final String OPTION_SKIP_EXPORT = \"skip-export\";\n public static final String OPTION_VERBOSE = \"verbose\";\n public static final String OPTION_DEBUG = \"debug\";\n public static final String OPTION_KERBEROS_CONFIG = \"krbconf\";\n public static final String OPTION_KEY_TAB = \"keytab\";\n public static final String OPTION_KEY_TAB_SHORT = \"k\";\n public static final String OPTION_REGION_SERVER = \"rs\";\n public static final String OPTION_PRINCIPAL = \"principal\";\n public static final String OPTION_PRINCIPAL_SHORT = \"p\";\n public static final String OPTION_REALM = \"realm\";\n public static final String OPTION_FORCE_PROCEED = \"force-proceed\";\n public static final String OPTION_KEEP = \"keep\";\n public static final String OPTION_DELETE_SNAPSHOT_FOR_NOT_EXISTING_TABLE = \"delete-snapshot-for-not-existing-table\";\n public static final String OPTION_SKIP_FLUSH = \"skip-flush\";\n public static final String OPTION_EXCLUDE = \"exclude\";\n public static final String OPTION_OVERRIDE = \"override\";\n public static final String OPTION_AFTER_FAILURE = \"after-failure\";\n public static final String OPTION_AFTER_SUCCESS = \"after-success\";\n public static final String OPTION_AFTER_FINISH = \"after-finish\";\n public static final String OPTION_CLEAR_WATCH_LEAK = \"clear-watch-leak\";\n public static final String OPTION_OPTIMIZE = \"optimize\";\n public static final String OPTION_TURN_BALANCER_OFF = \"turn-balancer-off\";\n public static final String OPTION_BALANCE_FACTOR = \"factor\";\n public static final String OPTION_TEST = \"test\"; // for test cases only\n public static final String OPTION_HTTP_PORT = \"port\";\n public static final String OPTION_INTERVAL = \"interval\";\n public static final String OPTION_MOVE_ASYNC = \"move-async\";\n public static final String OPTION_MAX_ITERATION = \"max-iteration\";\n public static final String OPTION_LOCALITY_THRESHOLD = \"locality\";\n public static final String OPTION_CF = \"cf\";\n public static final String OPTION_WAIT_UNTIL_FINISH = \"wait\";\n public static final String OPTION_INTERACTIVE = \"interactive\";\n public static final String OPTION_CONF = \"conf\";\n public static final String OPTION_CONF_SHORT = \"c\";\n public static final String OPTION_PHOENIX = \"phoenix-salting-table\";\n\n public static final String INVALID_ARGUMENTS = \"Invalid arguments\";\n public static final String ALL_TABLES = \"\";\n private static final int INTERVAL_DEFAULT_MS = 10 * 1000;\n protected final String zookeeperQuorum;\n protected final OptionSet optionSet;\n\n public Args(String[] args) throws IOException {\n OptionSet optionSetTemp = createOptionParser().parse(args);\n\n List<?> nonOptionArguments = optionSetTemp.nonOptionArguments();\n if (nonOptionArguments.size() < 1) throw new IllegalArgumentException(INVALID_ARGUMENTS);\n\n String arg = (String) nonOptionArguments.get(0);\n\n if (Util.isFile(arg)) {\n String[] newArgs = (String[]) ArrayUtils.addAll(parseArgsFile(arg), Arrays.copyOfRange(args, 1, args.length));\n this.optionSet = createOptionParser().parse(newArgs);\n this.zookeeperQuorum = (String) optionSet.nonOptionArguments().get(0);\n } else {\n this.optionSet = optionSetTemp;\n this.zookeeperQuorum = arg;\n }\n }\n\n public static String commonUsage() {\n return \" args file:\\n\"\n + \" Plain text file that contains args and options.\\n\"\n + \" common options:\\n\"\n + \" --\" + Args.OPTION_FORCE_PROCEED + \"\\n\"\n + \" Do not ask whether to proceed.\\n\"\n + \" --\" + Args.OPTION_DEBUG + \"\\n\"\n + \" Print debug log.\\n\"\n + \" --\" + Args.OPTION_VERBOSE + \"\\n\"\n + \" Print some more messages.\\n\"\n + \" -\" + Args.OPTION_CONF_SHORT + \"<key=value>, --\" + Args.OPTION_CONF + \"=<key=value>\\n\"\n + \" Set a configuration for HBase. Can be used many times for several configurations.\\n\"\n + \" --\" + Args.OPTION_AFTER_FAILURE + \"=<script>\\n\"\n + \" The script to run when this running is failed.\\n\"\n + \" The first argument of the script should be a message string.\\n\"\n + \" --\" + Args.OPTION_AFTER_SUCCESS + \"=<script>\\n\"\n + \" The script to run when this running is successfully finished.\\n\"\n + \" The first argument of the script should be a message string.\\n\"\n + \" --\" + Args.OPTION_AFTER_FINISH + \"=<script>\\n\"\n + \" The script to run when this running is successfully finished or failed.\\n\"\n + \" The first argument of the script should be a message string.\\n\"\n + \" -\" + Args.OPTION_KEY_TAB_SHORT + \"<keytab file>, --\" + Args.OPTION_KEY_TAB + \"=<keytab file>\\n\"\n + \" Kerberos keytab file. Use absolute path.\\n\"\n + \" -\" + Args.OPTION_PRINCIPAL_SHORT + \"<principal>, --\" + Args.OPTION_PRINCIPAL + \"=<principal>\\n\"\n + \" Kerberos principal.\\n\"\n + \" --\" + Args.OPTION_REALM + \"=<realm>\\n\"\n + \" Kerberos realm to use. Set this arg if it is not the default realm.\\n\"\n + \" --\" + Args.OPTION_KERBEROS_CONFIG + \"=<kerberos config file>\\n\"\n + \" Kerberos config file. Use absolute path.\\n\";\n }\n\n public static String[] parseArgsFile(String fileName) throws IOException {\n return parseArgsFile(fileName, false);\n }\n\n public static String[] parseArgsFile(String fileName, boolean fromResource) throws IOException {\n final String string;\n if (fromResource) {\n string = Util.readFromResource(fileName);\n } else {\n string = Util.readFromFile(fileName);\n }\n return string.split(\"[ \\n]\");\n }\n\n public static Set<String> tables(Args args, HBaseAdmin admin) throws IOException {\n return tables(args, admin, args.getTableName());\n }\n\n public static Set<String> tables(Args args, HBaseAdmin admin, String tableName) throws IOException {\n long startTimestamp = System.currentTimeMillis();\n Util.printVerboseMessage(args, Util.getMethodName() + \" - start\");\n if (tableName.equals(ALL_TABLES)) {\n Util.printVerboseMessage(args, Util.getMethodName() + \" - end\", startTimestamp);\n return null;\n } else {\n Set<String> tables = new TreeSet<>();\n HTableDescriptor[] hTableDescriptors = admin.listTables(tableName);\n if (hTableDescriptors == null) {\n return tables;\n } else {\n for (HTableDescriptor hTableDescriptor : hTableDescriptors) {\n // fixme\n // If hbase 1.0 client is connected to hbase 0.98,\n // admin.listTables(tableName) always returns all tables.\n // This is a workaround.\n String nameAsString = hTableDescriptor.getNameAsString();\n if (nameAsString.matches(tableName))\n tables.add(nameAsString);\n }\n }\n\n Util.printVerboseMessage(args, Util.getMethodName() + \" - end\", startTimestamp);\n return tables;\n }\n }\n\n @Override\n public String toString() {\n if (optionSet == null) return \"\";\n\n String nonOptionArgs = \"\";\n if (optionSet.nonOptionArguments() != null) {\n int i = 0;\n for (Object object : optionSet.nonOptionArguments()) {\n if (i > 0) nonOptionArgs += \" \";\n nonOptionArgs += \"\\\"\" + object.toString() + \"\\\"\";\n i++;\n }\n }\n\n String optionArgs = \"\";\n if (optionSet.asMap() != null) {\n int i = 0;\n for (Map.Entry<OptionSpec<?>, List<?>> entry : optionSet.asMap().entrySet()) {\n if (entry.getValue().size() > 0) {\n if (i > 0) optionArgs += \" \";\n optionArgs += \"--\" + entry.getKey().options().get(0) + \"=\\\"\" + entry.getValue().get(0) + \"\\\"\";\n i++;\n }\n }\n\n }\n\n return nonOptionArgs + \" \" + optionArgs;\n }\n\n public String getTableName() {\n if (optionSet.nonOptionArguments().size() > 1) {\n return (String) optionSet.nonOptionArguments().get(1);\n } else {\n return Args.ALL_TABLES;\n }\n }\n\n public String getZookeeperQuorum() {\n return zookeeperQuorum;\n }\n\n protected abstract OptionParser createOptionParser();\n\n protected OptionParser createCommonOptionParser() {\n OptionParser optionParser = new OptionParser();\n optionParser.accepts(OPTION_FORCE_PROCEED);\n optionParser.accepts(OPTION_TEST);\n optionParser.accepts(OPTION_DEBUG);\n optionParser.accepts(OPTION_VERBOSE);\n optionParser.accepts(OPTION_CONF).withRequiredArg().ofType(String.class);\n optionParser.accepts(OPTION_CONF_SHORT).withRequiredArg().ofType(String.class);\n optionParser.accepts(OPTION_KEY_TAB).withRequiredArg().ofType(String.class);\n optionParser.accepts(OPTION_KEY_TAB_SHORT).withRequiredArg().ofType(String.class);\n optionParser.accepts(OPTION_PRINCIPAL).withRequiredArg().ofType(String.class);\n optionParser.accepts(OPTION_PRINCIPAL_SHORT).withRequiredArg().ofType(String.class);\n optionParser.accepts(OPTION_REALM).withRequiredArg().ofType(String.class);\n optionParser.accepts(OPTION_KERBEROS_CONFIG).withRequiredArg().ofType(String.class);\n optionParser.accepts(OPTION_AFTER_FAILURE).withRequiredArg().ofType(String.class);\n optionParser.accepts(OPTION_AFTER_SUCCESS).withRequiredArg().ofType(String.class);\n optionParser.accepts(OPTION_AFTER_FINISH).withRequiredArg().ofType(String.class);\n return optionParser;\n }\n\n public Map<String, String> getConfigurations() {\n Map<String, String> result = new HashMap<>();\n if (optionSet.has(OPTION_CONF)) {\n result.putAll(parseConf(OPTION_CONF));\n }\n if (optionSet.has(OPTION_CONF_SHORT)) {\n result.putAll(parseConf(OPTION_CONF_SHORT));\n }\n return result;\n }\n\n private Map<String, String> parseConf(String option) {\n Map<String, String> result = new HashMap<>();\n List<?> objects = optionSet.valuesOf(option);\n for (Object confArg : objects) {\n String confStr = ((String) confArg);\n int splitPoint = confStr.indexOf(\"=\");\n String key = confStr.substring(0, splitPoint);\n String value = confStr.substring(splitPoint + 1);\n result.put(key, value);\n }\n return result;\n }\n\n public String getAfterFailureScript() {\n if (optionSet.has(OPTION_AFTER_FAILURE)) {\n return (String) optionSet.valueOf(OPTION_AFTER_FAILURE);\n } else {\n return null;\n }\n }\n\n public String getAfterSuccessScript() {\n if (optionSet.has(OPTION_AFTER_SUCCESS)) {\n return (String) optionSet.valueOf(OPTION_AFTER_SUCCESS);\n } else {\n return null;\n }\n }\n\n public String getAfterFinishScript() {\n if (optionSet.has(OPTION_AFTER_FINISH)) {\n return (String) optionSet.valueOf(OPTION_AFTER_FINISH);\n } else {\n return null;\n }\n }\n\n public int getIntervalMS() {\n if (optionSet.has(OPTION_INTERVAL))\n return (Integer) optionSet.valueOf(OPTION_INTERVAL) * 1000;\n else return INTERVAL_DEFAULT_MS;\n }\n\n public boolean has(String optionName) {\n return optionSet.has(optionName);\n }\n\n public boolean has(String optionLongName, String optionShortName) {\n return optionSet.has(optionLongName) || optionSet.has(optionShortName);\n }\n\n public Object valueOf(String optionName) {\n Object arg = optionSet.valueOf(optionName);\n if (arg != null && arg instanceof String) {\n String argString = ((String) arg).trim();\n return argString.length() == 0 ? null : argString;\n } else {\n return arg;\n }\n }\n\n public Object valueOf(String optionLongName, String optionShortName) {\n Object arg = optionSet.valueOf(optionName(optionLongName, optionShortName));\n if (arg != null && arg instanceof String) {\n String argString = ((String) arg).trim();\n return argString.length() == 0 ? null : argString;\n } else {\n return arg;\n }\n }\n\n private String optionName(String optionLongName, String optionShortName) {\n if (has(optionLongName)) return optionLongName;\n else return optionShortName;\n }\n\n public OptionSet getOptionSet() {\n return optionSet;\n }\n\n public boolean isForceProceed() {\n return optionSet.has(OPTION_FORCE_PROCEED);\n }\n\n public String hashStr() {\n return Integer.toHexString(optionSet.hashCode());\n }\n}",
"public class HBaseClient {\n private static String principal = null;\n private static String password = null;\n private static HBaseAdmin admin = null;\n\n private HBaseClient() {\n }\n\n private static String createJaasConfigFile(Args args) throws FileNotFoundException, UnsupportedEncodingException {\n // fixme hash collision may occur in args.hashStr()\n final String authConfFileName = \"/tmp/\" + \"hbase-client-\" + args.hashStr() + \".jaas\";\n File file = new File(authConfFileName);\n if (file.exists()) return authConfFileName;\n\n StringBuilder sb = new StringBuilder();\n sb.append(\"Client {\\n\");\n sb.append(\"com.sun.security.auth.module.Krb5LoginModule required\\n\");\n sb.append(\"useTicketCache=false\\n\");\n if (args.has(Args.OPTION_DEBUG)) {\n sb.append(\"debug=true\\n\");\n }\n if (args.has(Args.OPTION_KEY_TAB, Args.OPTION_KEY_TAB_SHORT)) {\n sb.append(\"useKeyTab=true\\n\");\n sb.append(\"keyTab=\\\"\").append(args.valueOf(Args.OPTION_KEY_TAB, Args.OPTION_KEY_TAB_SHORT)).append(\"\\\"\\n\");\n sb.append(\"principal=\\\"\").append(principal(args)).append(\"\\\"\\n\");\n } else {\n sb.append(\"useKeyTab=false\\n\");\n }\n sb.append(\";};\");\n\n try (PrintWriter writer = new PrintWriter(authConfFileName, Constant.CHARSET.name())) {\n writer.print(sb);\n }\n return authConfFileName;\n }\n\n private static String kerberosConfigFile(Args args) throws IOException {\n final String fileNameArg;\n if (args.has(Args.OPTION_KERBEROS_CONFIG)) {\n fileNameArg = (String) args.valueOf(Args.OPTION_KERBEROS_CONFIG);\n } else {\n fileNameArg = \"/etc/krb5.conf\";\n }\n System.out.println(\"Loading kerberos config from \" + fileNameArg);\n return fileNameArg;\n }\n\n private static void loginWithPassword(final Args args, Configuration conf) throws LoginException, IOException {\n LoginContext loginContext = new LoginContext(\"Client\", new CallbackHandler() {\n @Override\n public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {\n for (Callback callback : callbacks) {\n if (callback instanceof NameCallback) {\n NameCallback nameCallback = (NameCallback) callback;\n nameCallback.setName(principal(args));\n } else if (callback instanceof PasswordCallback) {\n PasswordCallback passwordCallback = (PasswordCallback) callback;\n passwordCallback.setPassword(askPassword().toCharArray());\n } else {\n throw new UnsupportedCallbackException(callback);\n }\n }\n }\n });\n loginContext.login();\n\n CommandAdapter.loginUserFromSubject(conf, loginContext.getSubject());\n }\n\n private static void updateConf(Configuration conf, String realm) throws IOException {\n conf.set(\"hadoop.security.authentication\", \"Kerberos\");\n conf.set(\"hbase.security.authentication\", \"Kerberos\");\n conf.set(\"hbase.master.kerberos.principal\", \"hbase/_HOST@\" + realm);\n conf.set(\"hbase.regionserver.kerberos.principal\", \"hbase/_HOST@\" + realm);\n }\n\n private static String principal(Args args) {\n if (principal == null) {\n if (args.has(Args.OPTION_PRINCIPAL, Args.OPTION_PRINCIPAL_SHORT)) {\n principal = (String) args.valueOf(Args.OPTION_PRINCIPAL, Args.OPTION_PRINCIPAL_SHORT);\n } else {\n System.out.print(\"Principal: \");\n Scanner scanner = new Scanner(System.in);\n principal = scanner.nextLine();\n }\n }\n\n return principal;\n }\n\n private static String askPassword() {\n if (password == null) {\n Console console = System.console();\n if (console == null) {\n System.out.print(\"Password: \");\n Scanner scanner = new Scanner(System.in);\n password = scanner.nextLine();\n } else {\n password = String.valueOf(console.readPassword(\"Password: \"));\n }\n }\n\n return password;\n }\n\n private static boolean isSecuredCluster(Args args) {\n return args.has(Args.OPTION_KERBEROS_CONFIG) || args.has(Args.OPTION_PRINCIPAL)\n || args.has(Args.OPTION_PRINCIPAL_SHORT);\n }\n\n private static Configuration createBaseConfiguration(Args args) {\n Configuration confDefault = new Configuration(true);\n Configuration conf = HBaseConfiguration.create(confDefault);\n\n conf.set(\"hbase.zookeeper.quorum\", args.getZookeeperQuorum());\n conf.set(\"zookeeper.recovery.retry\", \"1\");\n conf.set(\"hbase.client.retries.number\", \"2\");\n conf.set(\"hbase.meta.scanner.caching\", \"1000\");\n for (Map.Entry<String, String> config : args.getConfigurations().entrySet()) {\n conf.set(config.getKey(), config.getValue());\n }\n\n return conf;\n }\n\n private static void validateAuthentication() throws ZooKeeperConnectionException {\n try {\n // Is there something better?\n admin.isMasterRunning();\n } catch (MasterNotRunningException e) {\n System.out.println(\"Maybe you are connecting to the secured cluster without kerberos config.\\n\");\n }\n }\n\n private static synchronized void login(Args args, Configuration conf) throws Exception {\n if (args.has(Args.OPTION_DEBUG)) {\n System.setProperty(\"sun.security.krb5.debug\", \"true\");\n System.setProperty(\"sun.security.spnego.debug\", \"true\");\n }\n\n System.setProperty(\"java.security.auth.login.config\", createJaasConfigFile(args));\n System.setProperty(\"java.security.krb5.conf\", kerberosConfigFile(args));\n\n Config krbConfig = Config.getInstance();\n final String realm;\n if (args.has(Args.OPTION_REALM)) {\n realm = (String) args.valueOf(Args.OPTION_REALM);\n System.setProperty(\"java.security.krb5.realm\", realm);\n System.setProperty(\"java.security.krb5.kdc\", krbConfig.getKDCList(realm));\n Config.refresh();\n } else {\n realm = krbConfig.getDefaultRealm();\n }\n\n updateConf(conf, realm);\n\n if (args.has(Args.OPTION_KEY_TAB, Args.OPTION_KEY_TAB_SHORT)) {\n UserGroupInformation.setConfiguration(conf);\n UserGroupInformation.loginUserFromKeytab(principal(args), (String) args.valueOf(Args.OPTION_KEY_TAB, Args.OPTION_KEY_TAB_SHORT));\n } else {\n loginWithPassword(args, conf);\n }\n\n UserGroupInformation currentUser = UserGroupInformation.getCurrentUser();\n System.out.println(currentUser + \"\\n\");\n }\n\n public static HBaseAdmin getAdmin(Args args) throws Exception {\n System.out.println(\"Connecting to \" + args.getZookeeperQuorum());\n\n if (args.has(Args.OPTION_DEBUG)) Util.setLoggingThreshold(\"WARN\");\n\n if (admin == null) {\n Configuration conf = createBaseConfiguration(args);\n\n if (isSecuredCluster(args)) {\n login(args, conf);\n admin = new HBaseAdminWrapper(conf);\n } else {\n admin = new HBaseAdmin(conf);\n }\n }\n\n validateAuthentication();\n\n return admin;\n }\n\n @VisibleForTesting\n public static void setAdminForTesting(HBaseAdmin admin) {\n HBaseClient.admin = admin;\n }\n}",
"public class InvalidTableException extends IOException {\n public InvalidTableException(String message) {\n super(message);\n }\n}",
"public class Util {\n public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\");\n\n static {\n Util.setLoggingThreshold(\"ERROR\");\n }\n\n private Util() {\n }\n\n public static void setLoggingThreshold(String loggingLevel) {\n Properties props = new Properties();\n props.setProperty(\"log4j.threshold\", loggingLevel);\n PropertyConfigurator.configure(props);\n }\n\n public static void validateTable(HBaseAdmin admin, String tableName) throws IOException, InterruptedException {\n if (tableName.equals(Args.ALL_TABLES)) return;\n\n boolean tableExists = false;\n try {\n if (tableName.contains(Constant.TABLE_DELIMITER)) {\n String[] tables = tableName.split(Constant.TABLE_DELIMITER);\n for (String table : tables) {\n tableExists = admin.tableExists(table);\n }\n } else {\n tableExists = admin.listTables(tableName).length > 0;\n }\n } catch (Exception e) {\n Thread.sleep(1000);\n System.out.println();\n System.out.println(admin.getConfiguration().get(\"hbase.zookeeper.quorum\") + \" is invalid zookeeper quorum\");\n System.exit(1);\n }\n if (tableExists) {\n try {\n if (!admin.isTableEnabled(tableName)) {\n throw new InvalidTableException(\"Table is not enabled.\");\n }\n } catch (Exception ignore) {\n }\n } else {\n throw new InvalidTableException(\"Table does not exist.\");\n }\n }\n\n public static boolean isMoved(HBaseAdmin admin, String tableName, String regionName, String serverNameTarget) {\n try (HTable table = new HTable(admin.getConfiguration(), tableName)) {\n NavigableMap<HRegionInfo, ServerName> regionLocations = table.getRegionLocations();\n for (Map.Entry<HRegionInfo, ServerName> regionLocation : regionLocations.entrySet()) {\n if (regionLocation.getKey().getEncodedName().equals(regionName)) {\n return regionLocation.getValue().getServerName().equals(serverNameTarget);\n }\n }\n\n if (!existsRegion(regionName, regionLocations.keySet()))\n return true; // skip moving\n } catch (IOException e) {\n return false;\n }\n return false;\n }\n\n public static boolean existsRegion(String regionName, Set<HRegionInfo> regionLocations) {\n boolean regionExists = false;\n for (HRegionInfo hRegionInfo : regionLocations) {\n if (hRegionInfo.getEncodedName().equals(regionName))\n regionExists = true;\n }\n return regionExists;\n }\n\n public static boolean askProceed() {\n System.out.print(\"Proceed (Y or N)? \");\n Scanner scanner = new Scanner(System.in);\n String s = scanner.nextLine();\n return s.toUpperCase().equals(\"Y\");\n }\n\n public static long printVerboseMessage(Args args, String message, long startTimestamp) {\n long currentTimestamp = System.currentTimeMillis();\n if (args != null && args.has(Args.OPTION_VERBOSE)) {\n System.out.println(now() + \" - \" + message + \" - Duration(ms) - \" + (currentTimestamp - startTimestamp));\n }\n return currentTimestamp;\n }\n\n public static void printVerboseMessage(Args args, String message) {\n if (args != null && args.has(Args.OPTION_VERBOSE))\n System.out.println(now() + \" - \" + message);\n }\n\n public static void printMessage(String message) {\n System.out.println(now() + \" - \" + message);\n }\n\n private static String now() {\n return DATE_FORMAT.format(System.currentTimeMillis());\n }\n\n public static String getResource(String rsc) throws IOException {\n StringBuilder sb = new StringBuilder();\n\n ClassLoader cLoader = Util.class.getClassLoader();\n try (InputStream i = cLoader.getResourceAsStream(rsc)) {\n BufferedReader r = new BufferedReader(new InputStreamReader(i));\n\n String l;\n while ((l = r.readLine()) != null) {\n sb.append(l).append(\"\\n\");\n }\n }\n return sb.toString();\n }\n\n private static String readString(Reader reader) throws IOException {\n StringBuilder sb = new StringBuilder();\n try (BufferedReader bufferedReader = new BufferedReader(reader)) {\n char[] buffer = new char[1000];\n int read;\n while ((read = bufferedReader.read(buffer)) != -1) {\n sb.append(buffer, 0, read);\n }\n }\n return sb.toString();\n }\n\n public static String readFromResource(String fileName) throws IOException {\n try (InputStream in = Util.class.getClassLoader().getResourceAsStream(fileName)) {\n return readString(new InputStreamReader(in));\n }\n }\n\n public static String readFromFile(String fileName) throws IOException {\n return readString(new FileReader(fileName));\n }\n\n public static boolean isFile(String path) {\n File file = new File(path);\n return file.exists() && !file.isDirectory();\n }\n\n public static Set<String> parseTableSet(HBaseAdmin admin, Args args) throws IOException {\n Set<String> tableSet = new HashSet<>();\n String tableArg = (String) args.getOptionSet().nonOptionArguments().get(1);\n if (tableArg.contains(Constant.TABLE_DELIMITER)) {\n String[] tableArgs = tableArg.split(Constant.TABLE_DELIMITER);\n for (String arg : tableArgs) {\n for (HTableDescriptor hTableDescriptor : admin.listTables(arg)) {\n tableSet.add(hTableDescriptor.getNameAsString());\n }\n }\n } else {\n for (HTableDescriptor hTableDescriptor : admin.listTables(tableArg)) {\n String tableName = hTableDescriptor.getNameAsString();\n if (args.has(Args.OPTION_TEST) && !tableName.startsWith(\"UNIT_TEST_\")) {\n continue;\n }\n tableSet.add(tableName);\n }\n }\n return tableSet;\n }\n\n @SuppressWarnings(\"deprecation\")\n public static String getRegionInfoString(HRegionInfo regionA) {\n return \"{TABLE => \" + Bytes.toString(regionA.getTableName())\n + \", ENCODED => \" + regionA.getEncodedName()\n + \", STARTKEY => '\" + Bytes.toStringBinary(regionA.getStartKey())\n + \"', ENDKEY => '\" + Bytes.toStringBinary(regionA.getEndKey()) + \"'\";\n }\n\n public static void sendAlertAfterFailed(Args args, Class clazz, String message) {\n if (args != null && args.getAfterFailureScript() != null)\n AlertSender.send(args.getAfterFailureScript(),\n \"FAIL - \" + clazz.getSimpleName()\n + \" - \" + message\n + \" - \" + args.toString());\n sendAlertAfterFinish(args, clazz, message, false);\n }\n\n public static void sendAlertAfterSuccess(Args args, Class clazz) {\n sendAlertAfterSuccess(args, clazz, null);\n }\n\n public static void sendAlertAfterSuccess(Args args, Class clazz, String message) {\n if (args != null && args.getAfterSuccessScript() != null)\n AlertSender.send(args.getAfterSuccessScript(),\n \"SUCCESS - \" + clazz.getSimpleName()\n + (message == null || message.equals(\"\") ? \"\" : \" - \" + message)\n + \" - \" + args.toString());\n sendAlertAfterFinish(args, clazz, message, true);\n }\n\n public static void sendAlertAfterFinish(Args args, Class clazz, String message, boolean success) {\n if (args != null && args.getAfterFinishScript() != null)\n AlertSender.send(args.getAfterFinishScript(),\n (success ? \"SUCCESS - \" : \"FAIL - \") + clazz.getSimpleName()\n + (message == null || message.equals(\"\") ? \"\" : \" - \" + message)\n + \" - \" + args.toString());\n }\n\n public static String getMethodName() {\n StackTraceElement current = Thread.currentThread().getStackTrace()[2];\n return current.getClassName() + \".\" + current.getMethodName();\n }\n\n public static long parseTimestamp(String timestampString) {\n try {\n Date date = Constant.DATE_FORMAT_ARGS.parse(timestampString);\n if (date.compareTo(new Date(System.currentTimeMillis())) > 0)\n throw new IllegalArgumentException(Constant.MESSAGE_INVALID_DATE_FORMAT);\n return date.getTime();\n } catch (ParseException e) {\n throw new IllegalArgumentException(Constant.MESSAGE_INVALID_DATE_FORMAT);\n }\n }\n\n public static boolean askProceedInteractively(Args args, boolean printNewLine) {\n if (args.has(Args.OPTION_INTERACTIVE)) {\n if (args.has(Args.OPTION_FORCE_PROCEED)) {\n if (printNewLine) System.out.println();\n } else {\n System.out.print(\" - \");\n if (!askProceed()) return false;\n }\n } else {\n if (printNewLine) System.out.println();\n }\n return true;\n }\n}",
"public interface Command {\n void run() throws Exception;\n}"
] | import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
import com.google.common.annotations.VisibleForTesting;
import com.kakao.hbase.ManagerArgs;
import com.kakao.hbase.common.Args;
import com.kakao.hbase.common.HBaseClient;
import com.kakao.hbase.common.InvalidTableException;
import com.kakao.hbase.common.util.Util;
import com.kakao.hbase.manager.command.Command;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.reflections.Reflections;
import org.reflections.scanners.ResourcesScanner;
import org.reflections.scanners.SubTypesScanner;
import org.reflections.util.ClasspathHelper;
import org.reflections.util.ConfigurationBuilder;
import org.reflections.util.FilterBuilder; | /*
* Copyright 2015 Kakao Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kakao.hbase.manager;
public class Manager {
public static final String INVALID_COMMAND = "Invalid command";
public static final String INVALID_ZOOKEEPER = "Invalid zookeeper quorum";
private static final Set<Class<? extends Command>> commandSet;
static {
Util.setLoggingThreshold("ERROR");
Reflections reflections = createReflections();
commandSet = reflections.getSubTypesOf(Command.class);
}
private final Args args;
private final String commandName;
public Manager(Args args, String commandName) throws Exception {
this.args = args;
this.commandName = commandName;
}
public static void main(String[] args) throws Exception {
String commandName = "";
Args argsObject;
try {
if (args.length > 0)
commandName = args[0];
argsObject = parseArgs(args);
} catch (IllegalArgumentException e) {
if (commandExists(commandName)) {
printError(INVALID_ZOOKEEPER);
printUsage(commandName);
System.exit(1);
} else {
printError(INVALID_COMMAND);
printUsage();
System.exit(1);
}
throw e;
}
try {
new Manager(argsObject, commandName).run();
} catch (InvocationTargetException e) {
printError(e.getCause().getMessage() + "\n");
printUsage(commandName);
System.exit(1);
} catch (InvalidTableException e) {
printError(e.getMessage());
System.exit(1);
}
}
private static void printError(String message) {
System.out.println("ERROR - " + message + "\n");
}
private static Reflections createReflections() {
List<ClassLoader> classLoadersList = new LinkedList<>();
classLoadersList.add(ClasspathHelper.contextClassLoader());
classLoadersList.add(ClasspathHelper.staticClassLoader());
return new Reflections(new ConfigurationBuilder()
.setScanners(new SubTypesScanner(false /* don't exclude Object.class */), new ResourcesScanner())
.setUrls(ClasspathHelper.forManifest(ClasspathHelper.forClassLoader(
classLoadersList.toArray(new ClassLoader[classLoadersList.size()]))))
.filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix("com.kakao.hbase.manager.command"))));
}
@VisibleForTesting
static Set<Class<? extends Command>> getCommandSet() {
return commandSet;
}
@VisibleForTesting
static String getCommandUsage(String commandName) throws Exception {
for (Class<? extends Command> c : commandSet) {
if (c.getSimpleName().toLowerCase().equals(commandName.toLowerCase())) {
Method usage = c.getDeclaredMethod("usage");
return (String) usage.invoke(null);
}
}
throw new IllegalArgumentException(INVALID_COMMAND);
}
private static boolean commandExists(String commandName) {
for (Class<? extends Command> c : commandSet) {
if (c.getSimpleName().toLowerCase().equals(commandName.toLowerCase())) {
return true;
}
}
return false;
}
private static List<String> getCommandNames() {
List<String> commandNames = new ArrayList<>();
for (Class<? extends Command> c : commandSet) {
commandNames.add(c.getSimpleName().toLowerCase());
}
Collections.sort(commandNames);
return commandNames;
}
private static void printUsage() {
System.out.println("Usage: " + Manager.class.getSimpleName()
+ " <command> (<zookeeper quorum>|<args file>) [args...]");
System.out.println(" commands:");
for (String c : getCommandNames()) System.out.println(" " + c);
System.out.println(Args.commonUsage());
}
@VisibleForTesting
static Args parseArgs(String[] argsParam) throws Exception {
if (argsParam.length == 0) throw new IllegalArgumentException(Args.INVALID_ARGUMENTS);
if (!commandExists(argsParam[0])) throw new IllegalArgumentException(INVALID_COMMAND);
return new ManagerArgs(Arrays.copyOfRange(argsParam, 1, argsParam.length));
}
private static void printUsage(String commandName) throws Exception {
String usage = getCommandUsage(commandName);
if (usage == null) {
System.out.println("Usage is not implemented");
} else {
System.out.println(usage);
}
}
public void run() throws Exception { | try (HBaseAdmin admin = HBaseClient.getAdmin(args)) { | 2 |
didi/VirtualAPK | CoreLibrary/src/main/java/com/didi/virtualapk/internal/VAInstrumentation.java | [
"public class Instrumentation {\n \n public Application newApplication(ClassLoader cl, String className, Context context) throws InstantiationException, IllegalAccessException, ClassNotFoundException {\n throw new RuntimeException(\"Stub!\");\n }\n \n public void callApplicationOnCreate(Application app) {\n throw new RuntimeException(\"Stub!\");\n }\n \n public Activity newActivity(ClassLoader cl, String className, Intent intent) throws InstantiationException, IllegalAccessException, ClassNotFoundException {\n throw new RuntimeException(\"Stub!\");\n }\n \n public void callActivityOnCreate(Activity activity, Bundle icicle) {\n throw new RuntimeException(\"Stub!\");\n }\n \n public void callActivityOnCreate(Activity activity, Bundle icicle, PersistableBundle persistentState) {\n throw new RuntimeException(\"Stub!\");\n }\n \n public ActivityResult execStartActivity(Context who, IBinder contextThread, IBinder token, Activity target, Intent intent, int requestCode) {\n throw new RuntimeException(\"Stub!\");\n }\n \n public ActivityResult execStartActivity(Context who, IBinder contextThread, IBinder token, Activity target, Intent intent, int requestCode, Bundle options) {\n throw new RuntimeException(\"Stub!\");\n }\n \n public ActivityResult execStartActivity(Context who, IBinder contextThread, IBinder token, Fragment target, Intent intent, int requestCode, Bundle options) {\n throw new RuntimeException(\"Stub!\");\n }\n \n public ActivityResult execStartActivity(Context who, IBinder contextThread, IBinder token, String target, Intent intent, int requestCode, Bundle options) {\n throw new RuntimeException(\"Stub!\");\n }\n \n public Context getContext() {\n throw new RuntimeException(\"Stub!\");\n }\n \n public Context getTargetContext() {\n throw new RuntimeException(\"Stub!\");\n }\n \n public ComponentName getComponentName() {\n throw new RuntimeException(\"Stub!\");\n }\n \n public static final class ActivityResult {\n public ActivityResult(int resultCode, Intent resultData) {\n throw new RuntimeException(\"Stub!\");\n }\n }\n}",
"public class PluginManager {\n\n public static final String TAG = Constants.TAG_PREFIX + \"PluginManager\";\n\n private static volatile PluginManager sInstance = null;\n\n // Context of host app\n protected final Context mContext;\n protected final Application mApplication;\n protected ComponentsHandler mComponentsHandler;\n protected final Map<String, LoadedPlugin> mPlugins = new ConcurrentHashMap<>();\n protected final List<Callback> mCallbacks = new ArrayList<>();\n\n protected VAInstrumentation mInstrumentation; // Hooked instrumentation\n protected IActivityManager mActivityManager; // Hooked IActivityManager binder\n protected IContentProvider mIContentProvider; // Hooked IContentProvider binder\n\n public static PluginManager getInstance(Context base) {\n if (sInstance == null) {\n synchronized (PluginManager.class) {\n if (sInstance == null) {\n sInstance = createInstance(base);\n }\n }\n }\n\n return sInstance;\n }\n \n private static PluginManager createInstance(Context context) {\n try {\n Bundle metaData = context.getPackageManager()\n .getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA)\n .metaData;\n \n if (metaData == null) {\n return new PluginManager(context);\n }\n \n String factoryClass = metaData.getString(\"VA_FACTORY\");\n \n if (factoryClass == null) {\n return new PluginManager(context);\n }\n \n PluginManager pluginManager = Reflector.on(factoryClass).method(\"create\", Context.class).call(context);\n \n if (pluginManager != null) {\n Log.d(TAG, \"Created a instance of \" + pluginManager.getClass());\n return pluginManager;\n }\n \n } catch (Exception e) {\n Log.w(TAG, \"Created the instance error!\", e);\n }\n \n return new PluginManager(context);\n }\n\n protected PluginManager(Context context) {\n if (context instanceof Application) {\n this.mApplication = (Application) context;\n this.mContext = mApplication.getBaseContext();\n } else {\n final Context app = context.getApplicationContext();\n if (app == null) {\n this.mContext = context;\n this.mApplication = ActivityThread.currentApplication();\n } else {\n this.mApplication = (Application) app;\n this.mContext = mApplication.getBaseContext();\n }\n }\n \n mComponentsHandler = createComponentsHandler();\n hookCurrentProcess();\n }\n\n protected void hookCurrentProcess() {\n hookInstrumentationAndHandler();\n hookSystemServices();\n hookDataBindingUtil();\n }\n\n public void init() {\n RunUtil.getThreadPool().execute(new Runnable() {\n @Override\n public void run() {\n doInWorkThread();\n }\n });\n }\n\n protected void doInWorkThread() {\n }\n \n public Application getHostApplication() {\n return this.mApplication;\n }\n \n protected ComponentsHandler createComponentsHandler() {\n return new ComponentsHandler(this);\n }\n \n protected VAInstrumentation createInstrumentation(Instrumentation origin) throws Exception {\n return new VAInstrumentation(this, origin);\n }\n \n protected ActivityManagerProxy createActivityManagerProxy(IActivityManager origin) throws Exception {\n return new ActivityManagerProxy(this, origin);\n }\n \n protected LoadedPlugin createLoadedPlugin(File apk) throws Exception {\n return new LoadedPlugin(this, this.mContext, apk);\n }\n \n protected void hookDataBindingUtil() {\n Reflector.QuietReflector reflector = Reflector.QuietReflector.on(\"android.databinding.DataBindingUtil\").field(\"sMapper\");\n Object old = reflector.get();\n if (old != null) {\n try {\n Callback callback = Reflector.on(\"android.databinding.DataBinderMapperProxy\").constructor().newInstance();\n reflector.set(callback);\n addCallback(callback);\n Log.d(TAG, \"hookDataBindingUtil succeed : \" + callback);\n } catch (Reflector.ReflectedException e) {\n Log.w(TAG, e);\n }\n }\n }\n \n public void addCallback(Callback callback) {\n if (callback == null) {\n return;\n }\n synchronized (mCallbacks) {\n if (mCallbacks.contains(callback)) {\n throw new RuntimeException(\"Already added \" + callback + \"!\");\n }\n mCallbacks.add(callback);\n }\n }\n \n public void removeCallback(Callback callback) {\n synchronized (mCallbacks) {\n mCallbacks.remove(callback);\n }\n }\n\n /**\n * hookSystemServices, but need to compatible with Android O in future.\n */\n protected void hookSystemServices() {\n try {\n Singleton<IActivityManager> defaultSingleton;\n \n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {\n defaultSingleton = Reflector.on(ActivityManager.class).field(\"IActivityManagerSingleton\").get();\n } else {\n defaultSingleton = Reflector.on(ActivityManagerNative.class).field(\"gDefault\").get();\n }\n IActivityManager origin = defaultSingleton.get();\n IActivityManager activityManagerProxy = (IActivityManager) Proxy.newProxyInstance(mContext.getClassLoader(), new Class[] { IActivityManager.class },\n createActivityManagerProxy(origin));\n\n // Hook IActivityManager from ActivityManagerNative\n Reflector.with(defaultSingleton).field(\"mInstance\").set(activityManagerProxy);\n\n if (defaultSingleton.get() == activityManagerProxy) {\n this.mActivityManager = activityManagerProxy;\n Log.d(TAG, \"hookSystemServices succeed : \" + mActivityManager);\n }\n } catch (Exception e) {\n Log.w(TAG, e);\n }\n }\n \n protected void hookInstrumentationAndHandler() {\n try {\n ActivityThread activityThread = ActivityThread.currentActivityThread();\n Instrumentation baseInstrumentation = activityThread.getInstrumentation();\n// if (baseInstrumentation.getClass().getName().contains(\"lbe\")) {\n// // reject executing in paralell space, for example, lbe.\n// System.exit(0);\n// }\n \n final VAInstrumentation instrumentation = createInstrumentation(baseInstrumentation);\n \n Reflector.with(activityThread).field(\"mInstrumentation\").set(instrumentation);\n Handler mainHandler = Reflector.with(activityThread).method(\"getHandler\").call();\n Reflector.with(mainHandler).field(\"mCallback\").set(instrumentation);\n this.mInstrumentation = instrumentation;\n Log.d(TAG, \"hookInstrumentationAndHandler succeed : \" + mInstrumentation);\n } catch (Exception e) {\n Log.w(TAG, e);\n }\n }\n\n protected void hookIContentProviderAsNeeded() {\n Uri uri = Uri.parse(RemoteContentProvider.getUri(mContext));\n mContext.getContentResolver().call(uri, \"wakeup\", null, null);\n try {\n Field authority = null;\n Field provider = null;\n ActivityThread activityThread = ActivityThread.currentActivityThread();\n Map providerMap = Reflector.with(activityThread).field(\"mProviderMap\").get();\n Iterator iter = providerMap.entrySet().iterator();\n while (iter.hasNext()) {\n Map.Entry entry = (Map.Entry) iter.next();\n Object key = entry.getKey();\n Object val = entry.getValue();\n String auth;\n if (key instanceof String) {\n auth = (String) key;\n } else {\n if (authority == null) {\n authority = key.getClass().getDeclaredField(\"authority\");\n authority.setAccessible(true);\n }\n auth = (String) authority.get(key);\n }\n if (auth.equals(RemoteContentProvider.getAuthority(mContext))) {\n if (provider == null) {\n provider = val.getClass().getDeclaredField(\"mProvider\");\n provider.setAccessible(true);\n }\n IContentProvider rawProvider = (IContentProvider) provider.get(val);\n IContentProvider proxy = IContentProviderProxy.newInstance(mContext, rawProvider);\n mIContentProvider = proxy;\n Log.d(TAG, \"hookIContentProvider succeed : \" + mIContentProvider);\n break;\n }\n }\n } catch (Exception e) {\n Log.w(TAG, e);\n }\n }\n\n /**\n * load a plugin into memory, then invoke it's Application.\n * @param apk the file of plugin, should end with .apk\n * @throws Exception\n */\n public void loadPlugin(File apk) throws Exception {\n if (null == apk) {\n throw new IllegalArgumentException(\"error : apk is null.\");\n }\n\n if (!apk.exists()) {\n // throw the FileNotFoundException by opening a stream.\n InputStream in = new FileInputStream(apk);\n in.close();\n }\n\n LoadedPlugin plugin = createLoadedPlugin(apk);\n \n if (null == plugin) {\n throw new RuntimeException(\"Can't load plugin which is invalid: \" + apk.getAbsolutePath());\n }\n \n this.mPlugins.put(plugin.getPackageName(), plugin);\n synchronized (mCallbacks) {\n for (int i = 0; i < mCallbacks.size(); i++) {\n mCallbacks.get(i).onAddedLoadedPlugin(plugin);\n }\n }\n }\n\n public LoadedPlugin getLoadedPlugin(Intent intent) {\n return getLoadedPlugin(PluginUtil.getComponent(intent));\n }\n\n public LoadedPlugin getLoadedPlugin(ComponentName component) {\n if (component == null) {\n return null;\n }\n return this.getLoadedPlugin(component.getPackageName());\n }\n\n public LoadedPlugin getLoadedPlugin(String packageName) {\n return this.mPlugins.get(packageName);\n }\n\n public List<LoadedPlugin> getAllLoadedPlugins() {\n List<LoadedPlugin> list = new ArrayList<>();\n list.addAll(mPlugins.values());\n return list;\n }\n\n public Context getHostContext() {\n return this.mContext;\n }\n\n public VAInstrumentation getInstrumentation() {\n return this.mInstrumentation;\n }\n\n public IActivityManager getActivityManager() {\n return this.mActivityManager;\n }\n\n public synchronized IContentProvider getIContentProvider() {\n if (mIContentProvider == null) {\n hookIContentProviderAsNeeded();\n }\n\n return mIContentProvider;\n }\n\n public ComponentsHandler getComponentsHandler() {\n return mComponentsHandler;\n }\n\n public ResolveInfo resolveActivity(Intent intent) {\n return this.resolveActivity(intent, 0);\n }\n\n public ResolveInfo resolveActivity(Intent intent, int flags) {\n for (LoadedPlugin plugin : this.mPlugins.values()) {\n ResolveInfo resolveInfo = plugin.resolveActivity(intent, flags);\n if (null != resolveInfo) {\n return resolveInfo;\n }\n }\n\n return null;\n }\n\n public ResolveInfo resolveService(Intent intent, int flags) {\n for (LoadedPlugin plugin : this.mPlugins.values()) {\n ResolveInfo resolveInfo = plugin.resolveService(intent, flags);\n if (null != resolveInfo) {\n return resolveInfo;\n }\n }\n\n return null;\n }\n\n public ProviderInfo resolveContentProvider(String name, int flags) {\n for (LoadedPlugin plugin : this.mPlugins.values()) {\n ProviderInfo providerInfo = plugin.resolveContentProvider(name, flags);\n if (null != providerInfo) {\n return providerInfo;\n }\n }\n\n return null;\n }\n\n /**\n * used in PluginPackageManager, do not invoke it from outside.\n */\n @Deprecated\n public List<ResolveInfo> queryIntentActivities(Intent intent, int flags) {\n List<ResolveInfo> resolveInfos = new ArrayList<ResolveInfo>();\n\n for (LoadedPlugin plugin : this.mPlugins.values()) {\n List<ResolveInfo> result = plugin.queryIntentActivities(intent, flags);\n if (null != result && result.size() > 0) {\n resolveInfos.addAll(result);\n }\n }\n\n return resolveInfos;\n }\n\n /**\n * used in PluginPackageManager, do not invoke it from outside.\n */\n @Deprecated\n public List<ResolveInfo> queryIntentServices(Intent intent, int flags) {\n List<ResolveInfo> resolveInfos = new ArrayList<ResolveInfo>();\n\n for (LoadedPlugin plugin : this.mPlugins.values()) {\n List<ResolveInfo> result = plugin.queryIntentServices(intent, flags);\n if (null != result && result.size() > 0) {\n resolveInfos.addAll(result);\n }\n }\n\n return resolveInfos;\n }\n\n /**\n * used in PluginPackageManager, do not invoke it from outside.\n */\n @Deprecated\n public List<ResolveInfo> queryBroadcastReceivers(Intent intent, int flags) {\n List<ResolveInfo> resolveInfos = new ArrayList<ResolveInfo>();\n\n for (LoadedPlugin plugin : this.mPlugins.values()) {\n List<ResolveInfo> result = plugin.queryBroadcastReceivers(intent, flags);\n if (null != result && result.size() > 0) {\n resolveInfos.addAll(result);\n }\n }\n\n return resolveInfos;\n }\n\n public interface Callback {\n void onAddedLoadedPlugin(LoadedPlugin plugin);\n }\n}",
"public class StubActivity extends Activity {\n @Override\n protected void onCreate(@Nullable Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n \n // Go to the main activity\n Intent mainIntent = getPackageManager().getLaunchIntentForPackage(getPackageName());\n \n if (mainIntent == null) {\n mainIntent = new Intent(Intent.ACTION_MAIN);\n mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);\n mainIntent.setPackage(getPackageName());\n \n ResolveInfo resolveInfo = getPackageManager().resolveActivity(mainIntent, 0);\n \n if (resolveInfo != null) {\n mainIntent.setClassName(this, resolveInfo.activityInfo.name);\n }\n }\n \n startActivity(mainIntent);\n \n finish();\n }\n}",
"public class PluginUtil {\n \n public static final String TAG = Constants.TAG_PREFIX + \"NativeLib\";\n \n public static ComponentName getComponent(Intent intent) {\n if (intent == null) {\n return null;\n }\n if (isIntentFromPlugin(intent)) {\n return new ComponentName(intent.getStringExtra(Constants.KEY_TARGET_PACKAGE),\n intent.getStringExtra(Constants.KEY_TARGET_ACTIVITY));\n }\n \n return intent.getComponent();\n }\n\n public static boolean isIntentFromPlugin(Intent intent) {\n if (intent == null) {\n return false;\n }\n return intent.getBooleanExtra(Constants.KEY_IS_PLUGIN, false);\n }\n\n public static int getTheme(Context context, Intent intent) {\n return PluginUtil.getTheme(context, PluginUtil.getComponent(intent));\n }\n\n public static int getTheme(Context context, ComponentName component) {\n LoadedPlugin loadedPlugin = PluginManager.getInstance(context).getLoadedPlugin(component);\n\n if (null == loadedPlugin) {\n return 0;\n }\n\n ActivityInfo info = loadedPlugin.getActivityInfo(component);\n if (null == info) {\n return 0;\n }\n\n if (0 != info.theme) {\n return info.theme;\n }\n\n ApplicationInfo appInfo = info.applicationInfo;\n if (null != appInfo && appInfo.theme != 0) {\n return appInfo.theme;\n }\n\n return selectDefaultTheme(0, Build.VERSION.SDK_INT);\n }\n\n public static int selectDefaultTheme(final int curTheme, final int targetSdkVersion) {\n return selectSystemTheme(curTheme, targetSdkVersion,\n android.R.style.Theme,\n android.R.style.Theme_Holo,\n android.R.style.Theme_DeviceDefault,\n android.R.style.Theme_DeviceDefault_Light_DarkActionBar);\n }\n\n public static int selectSystemTheme(final int curTheme, final int targetSdkVersion, final int orig, final int holo, final int dark, final int deviceDefault) {\n if (curTheme != 0) {\n return curTheme;\n }\n\n if (targetSdkVersion < 11 /* Build.VERSION_CODES.HONEYCOMB */) {\n return orig;\n }\n\n if (targetSdkVersion < 14 /* Build.VERSION_CODES.ICE_CREAM_SANDWICH */) {\n return holo;\n }\n\n if (targetSdkVersion < 24 /* Build.VERSION_CODES.N */) {\n return dark;\n }\n\n return deviceDefault;\n }\n\n public static void hookActivityResources(Activity activity, String packageName) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && isVivo(activity.getResources())) {\n // for 5.0+ vivo\n return;\n }\n\n // designed for 5.0 - only, but some bad phones not work, eg:letv\n try {\n Context base = activity.getBaseContext();\n final LoadedPlugin plugin = PluginManager.getInstance(activity).getLoadedPlugin(packageName);\n final Resources resources = plugin.getResources();\n if (resources != null) {\n Reflector.with(base).field(\"mResources\").set(resources);\n\n // copy theme\n Resources.Theme theme = resources.newTheme();\n theme.setTo(activity.getTheme());\n Reflector reflector = Reflector.with(activity);\n int themeResource = reflector.field(\"mThemeResource\").get();\n theme.applyStyle(themeResource, true);\n reflector.field(\"mTheme\").set(theme);\n\n reflector.field(\"mResources\").set(resources);\n }\n } catch (Exception e) {\n Log.w(Constants.TAG, e);\n }\n }\n\n public static final boolean isLocalService(final ServiceInfo serviceInfo) {\n return TextUtils.isEmpty(serviceInfo.processName) || serviceInfo.applicationInfo.packageName.equals(serviceInfo.processName);\n }\n\n public static boolean isVivo(Resources resources) {\n return resources.getClass().getName().equals(\"android.content.res.VivoResources\");\n }\n\n public static void putBinder(Bundle bundle, String key, IBinder value) {\n if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {\n bundle.putBinder(key, value);\n } else {\n Reflector.QuietReflector.with(bundle).method(\"putIBinder\", String.class, IBinder.class).call(key, value);\n }\n }\n\n public static IBinder getBinder(Bundle bundle, String key) {\n if (bundle == null) {\n return null;\n }\n if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {\n return bundle.getBinder(key);\n } else {\n return (IBinder) Reflector.QuietReflector.with(bundle)\n .method(\"getIBinder\", String.class).call(key);\n }\n }\n \n public static void copyNativeLib(File apk, Context context, PackageInfo packageInfo, File nativeLibDir) throws Exception {\n long startTime = System.currentTimeMillis();\n ZipFile zipfile = new ZipFile(apk.getAbsolutePath());\n \n try {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {\n for (String cpuArch : Build.SUPPORTED_ABIS) {\n if (findAndCopyNativeLib(zipfile, context, cpuArch, packageInfo, nativeLibDir)) {\n return;\n }\n }\n \n } else {\n if (findAndCopyNativeLib(zipfile, context, Build.CPU_ABI, packageInfo, nativeLibDir)) {\n return;\n }\n }\n \n findAndCopyNativeLib(zipfile, context, \"armeabi\", packageInfo, nativeLibDir);\n \n } finally {\n zipfile.close();\n Log.d(TAG, \"Done! +\" + (System.currentTimeMillis() - startTime) + \"ms\");\n }\n }\n \n private static boolean findAndCopyNativeLib(ZipFile zipfile, Context context, String cpuArch, PackageInfo packageInfo, File nativeLibDir) throws Exception {\n Log.d(TAG, \"Try to copy plugin's cup arch: \" + cpuArch);\n boolean findLib = false;\n boolean findSo = false;\n byte buffer[] = null;\n String libPrefix = \"lib/\" + cpuArch + \"/\";\n ZipEntry entry;\n Enumeration e = zipfile.entries();\n \n while (e.hasMoreElements()) {\n entry = (ZipEntry) e.nextElement();\n String entryName = entry.getName();\n \n if (entryName.charAt(0) < 'l') {\n continue;\n }\n if (entryName.charAt(0) > 'l') {\n break;\n }\n if (!findLib && !entryName.startsWith(\"lib/\")) {\n continue;\n }\n findLib = true;\n if (!entryName.endsWith(\".so\") || !entryName.startsWith(libPrefix)) {\n continue;\n }\n \n if (buffer == null) {\n findSo = true;\n Log.d(TAG, \"Found plugin's cup arch dir: \" + cpuArch);\n buffer = new byte[8192];\n }\n \n String libName = entryName.substring(entryName.lastIndexOf('/') + 1);\n Log.d(TAG, \"verify so \" + libName);\n File libFile = new File(nativeLibDir, libName);\n String key = packageInfo.packageName + \"_\" + libName;\n if (libFile.exists()) {\n int VersionCode = Settings.getSoVersion(context, key);\n if (VersionCode == packageInfo.versionCode) {\n Log.d(TAG, \"skip existing so : \" + entry.getName());\n continue;\n }\n }\n FileOutputStream fos = new FileOutputStream(libFile);\n Log.d(TAG, \"copy so \" + entry.getName() + \" of \" + cpuArch);\n copySo(buffer, zipfile.getInputStream(entry), fos);\n Settings.setSoVersion(context, key, packageInfo.versionCode);\n }\n \n if (!findLib) {\n Log.d(TAG, \"Fast skip all!\");\n return true;\n }\n \n return findSo;\n }\n \n private static void copySo(byte[] buffer, InputStream input, OutputStream output) throws IOException {\n BufferedInputStream bufferedInput = new BufferedInputStream(input);\n BufferedOutputStream bufferedOutput = new BufferedOutputStream(output);\n int count;\n \n while ((count = bufferedInput.read(buffer)) > 0) {\n bufferedOutput.write(buffer, 0, count);\n }\n bufferedOutput.flush();\n bufferedOutput.close();\n output.close();\n bufferedInput.close();\n input.close();\n }\n\n}",
"public class Reflector {\n \n public static final String LOG_TAG = Constants.TAG_PREFIX + \"Reflector\";\n \n protected Class<?> mType;\n protected Object mCaller;\n protected Constructor mConstructor;\n protected Field mField;\n protected Method mMethod;\n \n public static class ReflectedException extends Exception {\n \n public ReflectedException(String message) {\n super(message);\n }\n public ReflectedException(String message, Throwable cause) {\n super(message, cause);\n }\n \n }\n public static Reflector on(@NonNull String name) throws ReflectedException {\n return on(name, true, Reflector.class.getClassLoader());\n }\n \n public static Reflector on(@NonNull String name, boolean initialize) throws ReflectedException {\n return on(name, initialize, Reflector.class.getClassLoader());\n }\n \n public static Reflector on(@NonNull String name, boolean initialize, @Nullable ClassLoader loader) throws ReflectedException {\n try {\n return on(Class.forName(name, initialize, loader));\n } catch (Throwable e) {\n throw new ReflectedException(\"Oops!\", e);\n }\n }\n \n public static Reflector on(@NonNull Class<?> type) {\n Reflector reflector = new Reflector();\n reflector.mType = type;\n return reflector;\n }\n \n public static Reflector with(@NonNull Object caller) throws ReflectedException {\n return on(caller.getClass()).bind(caller);\n }\n \n protected Reflector() {\n \n }\n \n public Reflector constructor(@Nullable Class<?>... parameterTypes) throws ReflectedException {\n try {\n mConstructor = mType.getDeclaredConstructor(parameterTypes);\n mConstructor.setAccessible(true);\n mField = null;\n mMethod = null;\n return this;\n } catch (Throwable e) {\n throw new ReflectedException(\"Oops!\", e);\n }\n }\n \n @SuppressWarnings(\"unchecked\")\n public <R> R newInstance(@Nullable Object ... initargs) throws ReflectedException {\n if (mConstructor == null) {\n throw new ReflectedException(\"Constructor was null!\");\n }\n try {\n return (R) mConstructor.newInstance(initargs);\n } catch (InvocationTargetException e) {\n throw new ReflectedException(\"Oops!\", e.getTargetException());\n } catch (Throwable e) {\n throw new ReflectedException(\"Oops!\", e);\n }\n }\n \n protected Object checked(@Nullable Object caller) throws ReflectedException {\n if (caller == null || mType.isInstance(caller)) {\n return caller;\n }\n throw new ReflectedException(\"Caller [\" + caller + \"] is not a instance of type [\" + mType + \"]!\");\n }\n \n protected void check(@Nullable Object caller, @Nullable Member member, @NonNull String name) throws ReflectedException {\n if (member == null) {\n throw new ReflectedException(name + \" was null!\");\n }\n if (caller == null && !Modifier.isStatic(member.getModifiers())) {\n throw new ReflectedException(\"Need a caller!\");\n }\n checked(caller);\n }\n \n public Reflector bind(@Nullable Object caller) throws ReflectedException {\n mCaller = checked(caller);\n return this;\n }\n \n public Reflector unbind() {\n mCaller = null;\n return this;\n }\n \n public Reflector field(@NonNull String name) throws ReflectedException {\n try {\n mField = findField(name);\n mField.setAccessible(true);\n mConstructor = null;\n mMethod = null;\n return this;\n } catch (Throwable e) {\n throw new ReflectedException(\"Oops!\", e);\n }\n }\n \n protected Field findField(@NonNull String name) throws NoSuchFieldException {\n try {\n return mType.getField(name);\n } catch (NoSuchFieldException e) {\n for (Class<?> cls = mType; cls != null; cls = cls.getSuperclass()) {\n try {\n return cls.getDeclaredField(name);\n } catch (NoSuchFieldException ex) {\n // Ignored\n }\n }\n throw e;\n }\n }\n \n @SuppressWarnings(\"unchecked\")\n public <R> R get() throws ReflectedException {\n return get(mCaller);\n }\n \n @SuppressWarnings(\"unchecked\")\n public <R> R get(@Nullable Object caller) throws ReflectedException {\n check(caller, mField, \"Field\");\n try {\n return (R) mField.get(caller);\n } catch (Throwable e) {\n throw new ReflectedException(\"Oops!\", e);\n }\n }\n \n public Reflector set(@Nullable Object value) throws ReflectedException {\n return set(mCaller, value);\n }\n \n public Reflector set(@Nullable Object caller, @Nullable Object value) throws ReflectedException {\n check(caller, mField, \"Field\");\n try {\n mField.set(caller, value);\n return this;\n } catch (Throwable e) {\n throw new ReflectedException(\"Oops!\", e);\n }\n }\n \n public Reflector method(@NonNull String name, @Nullable Class<?>... parameterTypes) throws ReflectedException {\n try {\n mMethod = findMethod(name, parameterTypes);\n mMethod.setAccessible(true);\n mConstructor = null;\n mField = null;\n return this;\n } catch (NoSuchMethodException e) {\n throw new ReflectedException(\"Oops!\", e);\n }\n }\n \n protected Method findMethod(@NonNull String name, @Nullable Class<?>... parameterTypes) throws NoSuchMethodException {\n try {\n return mType.getMethod(name, parameterTypes);\n } catch (NoSuchMethodException e) {\n for (Class<?> cls = mType; cls != null; cls = cls.getSuperclass()) {\n try {\n return cls.getDeclaredMethod(name, parameterTypes);\n } catch (NoSuchMethodException ex) {\n // Ignored\n }\n }\n throw e;\n }\n }\n \n public <R> R call(@Nullable Object... args) throws ReflectedException {\n return callByCaller(mCaller, args);\n }\n \n @SuppressWarnings(\"unchecked\")\n public <R> R callByCaller(@Nullable Object caller, @Nullable Object... args) throws ReflectedException {\n check(caller, mMethod, \"Method\");\n try {\n return (R) mMethod.invoke(caller, args);\n } catch (InvocationTargetException e) {\n throw new ReflectedException(\"Oops!\", e.getTargetException());\n } catch (Throwable e) {\n throw new ReflectedException(\"Oops!\", e);\n }\n }\n \n public static class QuietReflector extends Reflector {\n \n protected Throwable mIgnored;\n \n public static QuietReflector on(@NonNull String name) {\n return on(name, true, QuietReflector.class.getClassLoader());\n }\n \n public static QuietReflector on(@NonNull String name, boolean initialize) {\n return on(name, initialize, QuietReflector.class.getClassLoader());\n }\n \n public static QuietReflector on(@NonNull String name, boolean initialize, @Nullable ClassLoader loader) {\n Class<?> cls = null;\n try {\n cls = Class.forName(name, initialize, loader);\n return on(cls, null);\n } catch (Throwable e) {\n// Log.w(LOG_TAG, \"Oops!\", e);\n return on(cls, e);\n }\n }\n \n public static QuietReflector on(@Nullable Class<?> type) {\n return on(type, (type == null) ? new ReflectedException(\"Type was null!\") : null);\n }\n \n private static QuietReflector on(@Nullable Class<?> type, @Nullable Throwable ignored) {\n QuietReflector reflector = new QuietReflector();\n reflector.mType = type;\n reflector.mIgnored = ignored;\n return reflector;\n }\n \n public static QuietReflector with(@Nullable Object caller) {\n if (caller == null) {\n return on((Class<?>) null);\n }\n return on(caller.getClass()).bind(caller);\n }\n \n protected QuietReflector() {\n \n }\n \n public Throwable getIgnored() {\n return mIgnored;\n }\n \n protected boolean skip() {\n return skipAlways() || mIgnored != null;\n }\n \n protected boolean skipAlways() {\n return mType == null;\n }\n \n @Override\n public QuietReflector constructor(@Nullable Class<?>... parameterTypes) {\n if (skipAlways()) {\n return this;\n }\n try {\n mIgnored = null;\n super.constructor(parameterTypes);\n } catch (Throwable e) {\n mIgnored = e;\n// Log.w(LOG_TAG, \"Oops!\", e);\n }\n return this;\n }\n \n @Override\n public <R> R newInstance(@Nullable Object... initargs) {\n if (skip()) {\n return null;\n }\n try {\n mIgnored = null;\n return super.newInstance(initargs);\n } catch (Throwable e) {\n mIgnored = e;\n// Log.w(LOG_TAG, \"Oops!\", e);\n }\n return null;\n }\n \n @Override\n public QuietReflector bind(@Nullable Object obj) {\n if (skipAlways()) {\n return this;\n }\n try {\n mIgnored = null;\n super.bind(obj);\n } catch (Throwable e) {\n mIgnored = e;\n// Log.w(LOG_TAG, \"Oops!\", e);\n }\n return this;\n }\n \n @Override\n public QuietReflector unbind() {\n super.unbind();\n return this;\n }\n \n @Override\n public QuietReflector field(@NonNull String name) {\n if (skipAlways()) {\n return this;\n }\n try {\n mIgnored = null;\n super.field(name);\n } catch (Throwable e) {\n mIgnored = e;\n// Log.w(LOG_TAG, \"Oops!\", e);\n }\n return this;\n }\n \n @Override\n public <R> R get() {\n if (skip()) {\n return null;\n }\n try {\n mIgnored = null;\n return super.get();\n } catch (Throwable e) {\n mIgnored = e;\n// Log.w(LOG_TAG, \"Oops!\", e);\n }\n return null;\n }\n \n @Override\n public <R> R get(@Nullable Object caller) {\n if (skip()) {\n return null;\n }\n try {\n mIgnored = null;\n return super.get(caller);\n } catch (Throwable e) {\n mIgnored = e;\n// Log.w(LOG_TAG, \"Oops!\", e);\n }\n return null;\n }\n \n @Override\n public QuietReflector set(@Nullable Object value) {\n if (skip()) {\n return this;\n }\n try {\n mIgnored = null;\n super.set(value);\n } catch (Throwable e) {\n mIgnored = e;\n// Log.w(LOG_TAG, \"Oops!\", e);\n }\n return this;\n }\n \n @Override\n public QuietReflector set(@Nullable Object caller, @Nullable Object value) {\n if (skip()) {\n return this;\n }\n try {\n mIgnored = null;\n super.set(caller, value);\n } catch (Throwable e) {\n mIgnored = e;\n// Log.w(LOG_TAG, \"Oops!\", e);\n }\n return this;\n }\n \n @Override\n public QuietReflector method(@NonNull String name, @Nullable Class<?>... parameterTypes) {\n if (skipAlways()) {\n return this;\n }\n try {\n mIgnored = null;\n super.method(name, parameterTypes);\n } catch (Throwable e) {\n mIgnored = e;\n// Log.w(LOG_TAG, \"Oops!\", e);\n }\n return this;\n }\n \n @Override\n public <R> R call(@Nullable Object... args) {\n if (skip()) {\n return null;\n }\n try {\n mIgnored = null;\n return super.call(args);\n } catch (Throwable e) {\n mIgnored = e;\n// Log.w(LOG_TAG, \"Oops!\", e);\n }\n return null;\n }\n \n @Override\n public <R> R callByCaller(@Nullable Object caller, @Nullable Object... args) {\n if (skip()) {\n return null;\n }\n try {\n mIgnored = null;\n return super.callByCaller(caller, args);\n } catch (Throwable e) {\n mIgnored = e;\n// Log.w(LOG_TAG, \"Oops!\", e);\n }\n return null;\n }\n }\n}"
] | import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Application;
import android.app.Fragment;
import android.app.Instrumentation;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.PersistableBundle;
import android.util.Log;
import com.didi.virtualapk.PluginManager;
import com.didi.virtualapk.delegate.StubActivity;
import com.didi.virtualapk.internal.utils.PluginUtil;
import com.didi.virtualapk.utils.Reflector;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List; | /*
* Copyright (C) 2017 Beijing Didi Infinity Technology and Development Co.,Ltd. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.didi.virtualapk.internal;
/**
* Created by renyugang on 16/8/10.
*/
public class VAInstrumentation extends Instrumentation implements Handler.Callback {
public static final String TAG = Constants.TAG_PREFIX + "VAInstrumentation";
public static final int LAUNCH_ACTIVITY = 100;
protected Instrumentation mBase;
protected final ArrayList<WeakReference<Activity>> mActivities = new ArrayList<>();
| protected PluginManager mPluginManager; | 1 |
KostyaSha/github-integration-plugin | github-pullrequest-plugin/src/main/java/org/jenkinsci/plugins/github/pullrequest/publishers/impl/GitHubPRLabelAddPublisher.java | [
"public class GitHubPRLabel implements Describable<GitHubPRLabel> {\n private Set<String> labels;\n\n @DataBoundConstructor\n public GitHubPRLabel(String labels) {\n this(new HashSet<>(Arrays.asList(labels.split(\"\\n\"))));\n }\n\n public GitHubPRLabel(Set<String> labels) {\n this.labels = labels;\n }\n\n // for UI binding\n public String getLabels() {\n return Joiner.on(\"\\n\").skipNulls().join(labels);\n }\n\n @NonNull\n public Set<String> getLabelsSet() {\n return nonNull(labels) ? labels : Collections.<String>emptySet();\n }\n\n public DescriptorImpl getDescriptor() {\n return (DescriptorImpl) Jenkins.getInstance().getDescriptor(GitHubPRLabel.class);\n }\n\n @Symbol(\"labels\")\n @Extension\n public static class DescriptorImpl extends Descriptor<GitHubPRLabel> {\n @NonNull\n @Override\n public String getDisplayName() {\n return \"Labels\";\n }\n }\n}",
"public abstract class GitHubPRAbstractPublisher extends Recorder implements SimpleBuildStep {\n\n @CheckForNull\n private StatusVerifier statusVerifier;\n\n @CheckForNull\n private PublisherErrorHandler errorHandler;\n\n public GitHubPRAbstractPublisher(StatusVerifier statusVerifier, PublisherErrorHandler errorHandler) {\n this.statusVerifier = statusVerifier;\n this.errorHandler = errorHandler;\n }\n\n public StatusVerifier getStatusVerifier() {\n return statusVerifier;\n }\n\n public PublisherErrorHandler getErrorHandler() {\n return errorHandler;\n }\n\n protected void handlePublisherError(Run<?, ?> run) {\n if (errorHandler != null) {\n errorHandler.markBuildAfterError(run);\n }\n }\n\n public final BuildStepMonitor getRequiredMonitorService() {\n return BuildStepMonitor.NONE;\n }\n\n public final GitHubPRTrigger.DescriptorImpl getTriggerDescriptor() {\n return (GitHubPRTrigger.DescriptorImpl) Jenkins.getInstance().getDescriptor(GitHubPRTrigger.class);\n }\n\n public abstract static class DescriptorImpl extends BuildStepDescriptor<Publisher> {\n @Override\n public final boolean isApplicable(final Class<? extends AbstractProject> jobType) {\n return true;\n }\n\n @Override\n public abstract String getDisplayName();\n }\n}",
"public class PublisherErrorHandler extends AbstractDescribableImpl<PublisherErrorHandler> {\n\n private Result buildStatus;\n\n @DataBoundConstructor\n public PublisherErrorHandler(Result buildStatus) {\n this.buildStatus = buildStatus;\n }\n\n public Result getBuildStatus() {\n return buildStatus;\n }\n\n public Result markBuildAfterError(Run<?, ?> run) {\n run.setResult(buildStatus);\n return buildStatus;\n }\n\n @Symbol(\"statusOnPublisherError\")\n @Extension\n public static class DescriptorImpl extends Descriptor<PublisherErrorHandler> {\n @NonNull\n @Override\n public String getDisplayName() {\n return \"Set build status if publisher failed\";\n }\n\n public ListBoxModel doFillBuildStatusItems() {\n ListBoxModel items = new ListBoxModel();\n items.add(Result.UNSTABLE.toString());\n items.add(Result.FAILURE.toString());\n return items;\n }\n }\n}",
"public static GHIssue getGhIssue(final Run<?, ?> run) throws IOException {\n return getGhRepositoryFromPRTrigger(run).getIssue(getPRNumberFromPRCause(run));\n}",
"public static int getPRNumberFromPRCause(final Run<?, ?> run) throws AbortException {\n GitHubPRCause cause = ghPRCauseFromRun(run);\n if (isNull(cause)) {\n throw new AbortException(\"Can't get cause from run/build\");\n }\n return cause.getNumber();\n}"
] | import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.tasks.BuildStepDescriptor;
import jenkins.model.Jenkins;
import org.jenkinsci.Symbol;
import org.jenkinsci.plugins.github.pullrequest.GitHubPRLabel;
import org.jenkinsci.plugins.github.pullrequest.publishers.GitHubPRAbstractPublisher;
import org.jenkinsci.plugins.github.pullrequest.utils.PublisherErrorHandler;
import org.jenkinsci.plugins.github.pullrequest.utils.StatusVerifier;
import org.kohsuke.github.GHIssue;
import org.kohsuke.github.GHLabel;
import org.kohsuke.stapler.DataBoundConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.umd.cs.findbugs.annotations.NonNull;
import java.io.IOException;
import java.util.HashSet;
import java.util.stream.Collectors;
import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.getGhIssue;
import static org.jenkinsci.plugins.github.pullrequest.utils.JobHelper.getPRNumberFromPRCause; | package org.jenkinsci.plugins.github.pullrequest.publishers.impl;
/**
* Implements addition of labels (one or many) to GitHub.
*
* @author Alina Karpovich
* @author Kanstantsin Shautsou
*/
public class GitHubPRLabelAddPublisher extends GitHubPRAbstractPublisher {
private static final Logger LOGGER = LoggerFactory.getLogger(GitHubPRLabelAddPublisher.class);
| private GitHubPRLabel labelProperty; | 0 |
micdoodle8/Crossbow_Mod_2 | src/main/java/micdoodle8/mods/crossbowmod/CrossbowEvents.java | [
"public class EntityDiamondBolt extends EntityBolt\n{\n public EntityDiamondBolt(World world)\n {\n super(world);\n }\n\n public EntityDiamondBolt(World world, double d, double d1, double d2)\n {\n super(world, d, d1, d2);\n }\n\n public EntityDiamondBolt(World world, EntityLivingBase entityliving, Float f, Float f2)\n {\n super(world, entityliving, f, f2);\n }\n\n @Override\n protected void entityInit()\n {\n super.entityInit();\n }\n\n @Override\n public float getSpeed()\n {\n return 4F;\n }\n\n @Override\n public int getDamage()\n {\n return 10;\n }\n}",
"public class EntityGoldBolt extends EntityBolt\n{\n public EntityGoldBolt(World world)\n {\n super(world);\n }\n\n public EntityGoldBolt(World world, double d, double d1, double d2)\n {\n super(world, d, d1, d2);\n }\n\n public EntityGoldBolt(World world, EntityLivingBase entityliving, Float f, Float f2)\n {\n super(world, entityliving, f, f2);\n }\n\n @Override\n protected void entityInit()\n {\n super.entityInit();\n }\n\n @Override\n public float getSpeed()\n {\n return 3.25F;\n }\n\n @Override\n public int getDamage()\n {\n return 7;\n }\n}",
"public class EntityIronBolt extends EntityBolt\n{\n public EntityIronBolt(World world)\n {\n super(world);\n }\n\n public EntityIronBolt(World world, double d, double d1, double d2)\n {\n super(world, d, d1, d2);\n }\n\n public EntityIronBolt(World world, EntityLivingBase entityliving, Float f, Float f2)\n {\n super(world, entityliving, f, f2);\n }\n\n @Override\n protected void entityInit()\n {\n super.entityInit();\n }\n\n @Override\n public float getSpeed()\n {\n return 2.5F;\n }\n\n @Override\n public int getDamage()\n {\n return 5;\n }\n}",
"public class EntityStoneBolt extends EntityBolt\n{\n public EntityStoneBolt(World world)\n {\n super(world);\n }\n\n public EntityStoneBolt(World world, double d, double d1, double d2)\n {\n super(world, d, d1, d2);\n }\n\n public EntityStoneBolt(World world, EntityLivingBase entityliving, Float f, Float f2)\n {\n super(world, entityliving, f, f2);\n }\n\n @Override\n protected void entityInit()\n {\n super.entityInit();\n }\n\n @Override\n public float getSpeed()\n {\n return 1.75F;\n }\n\n @Override\n public int getDamage()\n {\n return 4;\n }\n}",
"public class EntityWoodBolt extends EntityBolt\n{\n public EntityWoodBolt(World world)\n {\n super(world);\n }\n\n public EntityWoodBolt(World world, double d, double d1, double d2)\n {\n super(world, d, d1, d2);\n }\n\n public EntityWoodBolt(World world, EntityLivingBase entityliving, Float f, Float f2)\n {\n super(world, entityliving, f, f2);\n }\n\n @Override\n protected void entityInit()\n {\n super.entityInit();\n }\n\n @Override\n public float getSpeed()\n {\n return 1.0F;\n }\n\n @Override\n public int getDamage()\n {\n return 3;\n }\n}",
"public class Util\n{\n public static void addRecipes()\n {\n GameRegistry.addRecipe(new ItemStack(CrossbowItems.attachmentLimbBolt, 3, 5), \"XY\", \"XY\", \"XY\", Character.valueOf('X'), Items.stick, Character.valueOf('Y'), Blocks.planks);\n GameRegistry.addRecipe(new ItemStack(CrossbowItems.attachmentLimbBolt, 3, 6), \"XY\", \"XY\", \"XY\", Character.valueOf('X'), Items.stick, Character.valueOf('Y'), Blocks.cobblestone);\n GameRegistry.addRecipe(new ItemStack(CrossbowItems.attachmentLimbBolt, 3, 6), \"XY\", \"XY\", \"XY\", Character.valueOf('X'), Items.stick, Character.valueOf('Y'), Blocks.stone);\n GameRegistry.addRecipe(new ItemStack(CrossbowItems.attachmentLimbBolt, 3, 7), \"XY\", \"XY\", \"XY\", Character.valueOf('X'), Items.stick, Character.valueOf('Y'), Items.iron_ingot);\n GameRegistry.addRecipe(new ItemStack(CrossbowItems.attachmentLimbBolt, 3, 8), \"XY\", \"XY\", \"XY\", Character.valueOf('X'), Items.stick, Character.valueOf('Y'), Items.gold_ingot);\n GameRegistry.addRecipe(new ItemStack(CrossbowItems.attachmentLimbBolt, 3, 9), \"XY\", \"XY\", \"XY\", Character.valueOf('X'), Items.stick, Character.valueOf('Y'), Items.diamond);\n GameRegistry.addRecipe(new ItemStack(CrossbowItems.attachmentLimbBolt, 1, 10), \"XXX\", \"XYZ\", \"XZY\", Character.valueOf('X'), Blocks.cobblestone, Character.valueOf('Y'), Items.stick, Character.valueOf('Z'), Items.string);\n GameRegistry.addRecipe(new ItemStack(CrossbowItems.attachmentLimbBolt, 1, 11), \"AXX\", \"XBZ\", \"XZY\", Character.valueOf('X'), Blocks.cobblestone, Character.valueOf('Y'), Items.stick, Character.valueOf('Z'), Items.string, Character.valueOf('A'), Items.iron_ingot, Character.valueOf('B'), new ItemStack(CrossbowItems.attachmentLimbBolt, 1, 10));\n GameRegistry.addRecipe(new ItemStack(CrossbowItems.attachmentLimbBolt, 1, 12), \"XXX\", \"XBZ\", \"XZY\", Character.valueOf('X'), Items.iron_ingot, Character.valueOf('Y'), Items.stick, Character.valueOf('Z'), Items.redstone, Character.valueOf('B'), new ItemStack(CrossbowItems.attachmentLimbBolt, 1, 11));\n GameRegistry.addRecipe(new ItemStack(CrossbowItems.attachmentLimbBolt, 1, 13), \"XAA\", \"ABZ\", \"AZY\", Character.valueOf('X'), Items.diamond, Character.valueOf('A'), Items.iron_ingot, Character.valueOf('Y'), Items.stick, Character.valueOf('Z'), Items.redstone, Character.valueOf('B'), new ItemStack(CrossbowItems.attachmentLimbBolt, 1, 12));\n GameRegistry.addRecipe(new ItemStack(CrossbowItems.attachmentLimbBolt, 1, 14), \"ZX \", \"XAX\", \" XZ\", Character.valueOf('X'), Items.iron_ingot, Character.valueOf('A'), Blocks.redstone_torch, Character.valueOf('Z'), Blocks.glass_pane);\n GameRegistry.addRecipe(new ItemStack(CrossbowItems.attachmentLimbBolt, 1, 15), \"ZX \", \"XAB\", \" XZ\", Character.valueOf('X'), Items.iron_ingot, Character.valueOf('A'), new ItemStack(CrossbowItems.attachmentLimbBolt, 1, 14), Character.valueOf('Z'), Blocks.glass_pane, Character.valueOf('B'), Blocks.stone_button);\n GameRegistry.addRecipe(new ItemStack(CrossbowItems.attachmentLimbBolt, 8, 0), \"X\", \"#\", Character.valueOf('X'), Blocks.planks, Character.valueOf('#'), Items.stick);\n GameRegistry.addRecipe(new ItemStack(CrossbowItems.attachmentLimbBolt, 8, 1), \"X\", \"#\", Character.valueOf('X'), Blocks.cobblestone, Character.valueOf('#'), Items.stick);\n GameRegistry.addRecipe(new ItemStack(CrossbowItems.attachmentLimbBolt, 8, 2), \"X\", \"#\", Character.valueOf('X'), Items.iron_ingot, Character.valueOf('#'), Items.stick);\n GameRegistry.addRecipe(new ItemStack(CrossbowItems.attachmentLimbBolt, 8, 3), \"X\", \"#\", Character.valueOf('X'), Items.gold_ingot, Character.valueOf('#'), Items.stick);\n GameRegistry.addRecipe(new ItemStack(CrossbowItems.attachmentLimbBolt, 8, 4), \"X\", \"#\", Character.valueOf('X'), Items.diamond, Character.valueOf('#'), Items.stick);\n GameRegistry.addRecipe(new ItemStack(CrossbowBlocks.crossbowBench, 1), \"YYY\", \"ZXZ\", \"ZZZ\", Character.valueOf('X'), Blocks.crafting_table, Character.valueOf('Y'), Items.iron_ingot, Character.valueOf('Z'), Blocks.planks);\n GameRegistry.addRecipe(new ItemStack(CrossbowItems.attachmentLimbBolt, 1, 16), \"XZZ\", \"ZXZ\", \"ZZX\", Character.valueOf('X'), Items.flint_and_steel, Character.valueOf('Z'), Items.iron_ingot);\n GameRegistry.addRecipe(new ItemStack(CrossbowItems.attachmentLimbBolt, 1, 18), \"XZZ\", \"ZXZ\", \"ZZX\", Character.valueOf('X'), Items.lava_bucket, Character.valueOf('Z'), Items.iron_ingot);\n GameRegistry.addRecipe(new ItemStack(CrossbowItems.attachmentLimbBolt, 1, 17), \"XZZ\", \"ZXZ\", \"ZZX\", Character.valueOf('X'), Blocks.tnt, Character.valueOf('Z'), Items.iron_ingot);\n GameRegistry.addRecipe(new ItemStack(CrossbowItems.attachmentLimbBolt, 1, 19), \"XZZ\", \"ZXZ\", \"ZZX\", Character.valueOf('X'), Blocks.snow, Character.valueOf('Z'), Items.iron_ingot);\n GameRegistry.addRecipe(new ItemStack(CrossbowItems.attachmentLimbBolt, 1, 20), \"GZZ\", \"ZRZ\", \"ZZG\", Character.valueOf('G'), Items.glowstone_dust, Character.valueOf('Z'), Items.iron_ingot, Character.valueOf('R'), Items.redstone);\n GameRegistry.addRecipe(new ItemStack(CrossbowItems.attachmentLimbBolt, 1, 21), \"SZZ\", \"ZCZ\", \"ZZF\", Character.valueOf('S'), Items.stick, Character.valueOf('C'), Items.coal, Character.valueOf('F'), Items.flint_and_steel, Character.valueOf('Z'), Items.iron_ingot);\n GameRegistry.addRecipe(new ItemStack(CrossbowItems.attachmentLimbBolt, 1, 22), \"NZZ\", \"ZSZ\", \"ZZN\", Character.valueOf('N'), Items.nether_wart, Character.valueOf('Z'), Items.iron_ingot, Character.valueOf('S'), Items.spider_eye);\n GameRegistry.addRecipe(new ItemStack(CrossbowItems.attachmentLimbBolt, 1, 23), \"XXZ\", \"XZX\", \"ZXC\", Character.valueOf('C'), Items.redstone, Character.valueOf('Z'), new ItemStack(CrossbowItems.attachmentLimbBolt, 1, 10), Character.valueOf('X'), Items.iron_ingot);\n \n for (EnumAttachmentType attachment : EnumAttachmentType.values())\n {\n for (EnumCrossbowFireRate fireRate : EnumCrossbowFireRate.values())\n {\n Util.addCrossbowBenchRecipe(new ItemStack(CrossbowItems.woodenCrossbowBase), attachment, EnumCrossbowMaterial.wooden, fireRate);\n Util.addCrossbowBenchRecipe(new ItemStack(CrossbowItems.stoneCrossbowBase), attachment, EnumCrossbowMaterial.stone, fireRate);\n Util.addCrossbowBenchRecipe(new ItemStack(CrossbowItems.ironCrossbowBase), attachment, EnumCrossbowMaterial.iron, fireRate);\n Util.addCrossbowBenchRecipe(new ItemStack(CrossbowItems.goldCrossbowBase), attachment, EnumCrossbowMaterial.gold, fireRate);\n Util.addCrossbowBenchRecipe(new ItemStack(CrossbowItems.diamondCrossbowBase), attachment, EnumCrossbowMaterial.diamond, fireRate);\n }\n }\n \n FMLLog.info(\"[CROSSBOW MOD 2] Added \" + CrossbowRecipes.getRecipeMap().size() + \" recipes to the Crossbow Bench\");\n }\n \n public static void addCrossbowBenchRecipe(ItemStack baseCrossbow, EnumAttachmentType attachment, EnumCrossbowMaterial material, EnumCrossbowFireRate fireRate)\n {\n CrossbowRecipes.addCrossbowRecipe(new CrossbowInfo(attachment, material, fireRate), ItemCrossbow.setAttachmentAndMaterial(baseCrossbow, attachment, material, fireRate));\n }\n\n public static ItemStack findMatchingCrossbowRecipe(InventoryCrossbowBench inv)\n {\n ItemStack[] sticks = new ItemStack[] { inv.getStackInSlot(3), inv.getStackInSlot(4), inv.getStackInSlot(5) };\n ItemStack[] limbs = new ItemStack[] { inv.getStackInSlot(2), inv.getStackInSlot(6), inv.getStackInSlot(7), inv.getStackInSlot(8), inv.getStackInSlot(9) };\n ItemStack mechanism = inv.getStackInSlot(1);\n ItemStack attachment = inv.getStackInSlot(10);\n \n return CrossbowRecipes.findMatchingRecipe(sticks, limbs, mechanism, attachment);\n }\n\n public static boolean isWooden(ItemStack stack)\n {\n if (stack != null && stack.getTagCompound() != null)\n {\n NBTTagCompound comp = stack.getTagCompound();\n\n if (comp.getInteger(\"material\") == 0)\n {\n return true;\n }\n else\n {\n return false;\n }\n }\n else\n {\n return false;\n }\n }\n\n /**\n * If the provided Itemstack is any stone crossbow\n * \n * @param stack\n * The item to check\n * @return True if the provided Itemstack is any stone crossbow\n */\n public static boolean isStone(ItemStack stack)\n {\n if (stack != null && stack.getTagCompound() != null)\n {\n NBTTagCompound comp = stack.getTagCompound();\n\n if (comp.getInteger(\"material\") == 1)\n {\n return true;\n }\n else\n {\n return false;\n }\n }\n else\n {\n return false;\n }\n }\n\n /**\n * If the provided Itemstack is any iron crossbow\n * \n * @param stack\n * The item to check\n * @return True if the provided Itemstack is any iron crossbow\n */\n public static boolean isIron(ItemStack stack)\n {\n if (stack != null && stack.getTagCompound() != null)\n {\n NBTTagCompound comp = stack.getTagCompound();\n\n if (comp.getInteger(\"material\") == 2)\n {\n return true;\n }\n else\n {\n return false;\n }\n }\n else\n {\n return false;\n }\n }\n\n /**\n * If the provided Itemstack is any gold crossbow\n * \n * @param stack\n * The item to check\n * @return True if the provided Itemstack is any gold crossbow\n */\n public static boolean isGold(ItemStack stack)\n {\n if (stack != null && stack.getTagCompound() != null)\n {\n NBTTagCompound comp = stack.getTagCompound();\n\n if (comp.getInteger(\"material\") == 3)\n {\n return true;\n }\n else\n {\n return false;\n }\n }\n else\n {\n return false;\n }\n }\n\n /**\n * If the provided Itemstack is any diamond crossbow\n * \n * @param stack\n * The item to check\n * @return True if the provided Itemstack is any diamond crossbow\n */\n public static boolean isDiamond(ItemStack stack)\n {\n if (stack != null && stack.getTagCompound() != null)\n {\n NBTTagCompound comp = stack.getTagCompound();\n\n if (comp.getInteger(\"material\") == 4)\n {\n return true;\n }\n else\n {\n return false;\n }\n }\n else\n {\n return false;\n }\n }\n\n /**\n * If the provided Itemstack has a basic scope\n * \n * @param stack\n * The item to check\n * @return True if the provided Itemstack has a basic scope\n */\n public static boolean hasBasicScope(ItemStack stack)\n {\n if (stack != null && stack.getTagCompound() != null)\n {\n NBTTagCompound comp = stack.getTagCompound();\n\n if (comp.getInteger(\"attachment\") == 2)\n {\n return true;\n }\n else\n {\n return false;\n }\n }\n else\n {\n return false;\n }\n }\n\n /**\n * If the provided Itemstack has a long range scope\n * \n * @param stack\n * The item to check\n * @return True if the provided Itemstack has a long range scope\n */\n public static boolean hasLongRangeScope(ItemStack stack)\n {\n if (stack != null && stack.getTagCompound() != null)\n {\n NBTTagCompound comp = stack.getTagCompound();\n\n if (comp.getInteger(\"attachment\") == 1)\n {\n return true;\n }\n else\n {\n return false;\n }\n }\n else\n {\n return false;\n }\n }\n\n /**\n * If the provided Itemstack has a light mechanism attachment\n * \n * @param stack\n * The item to check\n * @return True if the provided Itemstack has a light mechanism attachment\n */\n public static boolean hasLightMech(ItemStack stack)\n {\n if (stack != null && stack.getTagCompound() != null)\n {\n NBTTagCompound comp = stack.getTagCompound();\n\n if (comp.getInteger(\"firerate\") == 1)\n {\n return true;\n }\n else\n {\n return false;\n }\n }\n else\n {\n return false;\n }\n }\n\n /**\n * If the provided Itemstack has a medium mechanism attachment\n * \n * @param stack\n * The item to check\n * @return True if the provided Itemstack has a medium mechanism attachment\n */\n public static boolean hasMediumMech(ItemStack stack)\n {\n if (stack != null && stack.getTagCompound() != null)\n {\n NBTTagCompound comp = stack.getTagCompound();\n\n if (comp.getInteger(\"firerate\") == 2)\n {\n return true;\n }\n else\n {\n return false;\n }\n }\n else\n {\n return false;\n }\n }\n\n /**\n * If the provided Itemstack has a heavy mechanism attachment\n * \n * @param stack\n * The item to check\n * @return True if the provided Itemstack has a heavy mechanism attachment\n */\n public static boolean hasHeavyMech(ItemStack stack)\n {\n if (stack != null && stack.getTagCompound() != null)\n {\n NBTTagCompound comp = stack.getTagCompound();\n\n if (comp.getInteger(\"firerate\") == 3)\n {\n return true;\n }\n else\n {\n return false;\n }\n }\n else\n {\n return false;\n }\n }\n\n /**\n * If the provided Itemstack has a tri shot mechanism attachment\n * \n * @param stack\n * The item to check\n * @return True if the provided Itemstack has a tri shot mechanism\n * attachment\n */\n public static boolean hasTriShotMech(ItemStack stack)\n {\n if (stack != null && stack.getTagCompound() != null)\n {\n NBTTagCompound comp = stack.getTagCompound();\n\n if (comp.getInteger(\"firerate\") == 4)\n {\n return true;\n }\n else\n {\n return false;\n }\n }\n else\n {\n return false;\n }\n }\n\n /**\n * If the provided Itemstack has a Flame attachment\n * \n * @param stack\n * The item to check\n * @return True if the provided Itemstack has a Flame attachment\n */\n public static boolean hasFlameAttachment(ItemStack stack)\n {\n if (stack != null && stack.getTagCompound() != null)\n {\n NBTTagCompound comp = stack.getTagCompound();\n\n if (comp.getInteger(\"attachment\") == 9)\n {\n return true;\n }\n else\n {\n return false;\n }\n }\n else\n {\n return false;\n }\n }\n\n /**\n * If the provided Itemstack has an explosive attachment\n * \n * @param stack\n * The item to check\n * @return True if the provided Itemstack has an explosive attachment\n */\n public static boolean hasExplosiveAttachment(ItemStack stack)\n {\n if (stack != null && stack.getTagCompound() != null)\n {\n NBTTagCompound comp = stack.getTagCompound();\n\n if (comp.getInteger(\"attachment\") == 8)\n {\n return true;\n }\n else\n {\n return false;\n }\n }\n else\n {\n return false;\n }\n }\n\n /**\n * If the provided Itemstack has a lava attachment\n * \n * @param stack\n * The item to check\n * @return True if the provided Itemstack has a lava attachment\n */\n public static boolean hasLavaAttachment(ItemStack stack)\n {\n if (stack != null && stack.getTagCompound() != null)\n {\n NBTTagCompound comp = stack.getTagCompound();\n\n if (comp.getInteger(\"attachment\") == 3)\n {\n return true;\n }\n else\n {\n return false;\n }\n }\n else\n {\n return false;\n }\n }\n\n /**\n * If the provided Itemstack has an ice attachment\n * \n * @param stack\n * The item to check\n * @return True if the provided Itemstack has a lava attachment\n */\n public static boolean hasIceAttachment(ItemStack stack)\n {\n if (stack != null && stack.getTagCompound() != null)\n {\n NBTTagCompound comp = stack.getTagCompound();\n\n if (comp.getInteger(\"attachment\") == 4)\n {\n return true;\n }\n else\n {\n return false;\n }\n }\n else\n {\n return false;\n }\n }\n\n /**\n * If the provided Itemstack has an ice attachment\n * \n * @param stack\n * The item to check\n * @return True if the provided Itemstack has a lava attachment\n */\n public static boolean hasLightningAttachment(ItemStack stack)\n {\n if (stack != null && stack.getTagCompound() != null)\n {\n NBTTagCompound comp = stack.getTagCompound();\n\n if (comp.getInteger(\"attachment\") == 7)\n {\n return true;\n }\n else\n {\n return false;\n }\n }\n else\n {\n return false;\n }\n }\n\n public static boolean hasTorchAttachment(ItemStack stack)\n {\n if (stack != null && stack.getTagCompound() != null)\n {\n NBTTagCompound comp = stack.getTagCompound();\n\n if (comp.getInteger(\"attachment\") == 6)\n {\n return true;\n }\n else\n {\n return false;\n }\n }\n else\n {\n return false;\n }\n }\n\n public static boolean hasPoisonAttachment(ItemStack stack)\n {\n if (stack != null && stack.getTagCompound() != null)\n {\n NBTTagCompound comp = stack.getTagCompound();\n\n if (comp.getInteger(\"attachment\") == 5)\n {\n return true;\n }\n else\n {\n return false;\n }\n }\n else\n {\n return false;\n }\n }\n}"
] | import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import micdoodle8.mods.crossbowmod.entity.EntityDiamondBolt;
import micdoodle8.mods.crossbowmod.entity.EntityGoldBolt;
import micdoodle8.mods.crossbowmod.entity.EntityIronBolt;
import micdoodle8.mods.crossbowmod.entity.EntityStoneBolt;
import micdoodle8.mods.crossbowmod.entity.EntityWoodBolt;
import micdoodle8.mods.crossbowmod.util.Util;
import net.minecraft.entity.passive.EntityChicken;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraftforge.event.entity.living.LivingDeathEvent; | package micdoodle8.mods.crossbowmod;
public class CrossbowEvents
{
@SubscribeEvent
public void deathEvent(LivingDeathEvent event)
{ | if (event.entity instanceof EntityChicken && (event.source.getSourceOfDamage() instanceof EntityWoodBolt || event.source.getSourceOfDamage() instanceof EntityStoneBolt || event.source.getSourceOfDamage() instanceof EntityIronBolt || event.source.getSourceOfDamage() instanceof EntityGoldBolt || event.source.getSourceOfDamage() instanceof EntityDiamondBolt) && event.source.getEntity() instanceof EntityPlayer) | 3 |
szmg/grafana-dashboard-generator-java | grafana-dashboard-generator-example/src/main/java/uk/co/szmg/grafana/example/dashboards/complex/MultiEnvExampleDashboards.java | [
"public interface DashboardFactory {\n\n /**\n * Creates dashboards.\n * @return a list of dashboards created, should not be {@code null}\n */\n List<Dashboard> create();\n\n}",
"public class ColorTheme {\n\n /**\n * A simple, red-yellow-green and white theme.\n */\n public static final ColorTheme RED_YELLOW_GREEN = new ColorTheme(\n \"white\",\n \"rgba(50, 172, 45, 0.97)\",\n \"rgba(237, 129, 40, 0.89)\",\n \"rgba(245, 54, 54, 0.9)\");\n\n private String neutral;\n private String healthy;\n private String warning;\n private String error;\n\n /**\n * Constructor.\n *\n * @param neutral neutral color for texts that are neither good nor bad; e.g., white\n * @param healthy color to mark healthy things, e.g., green\n * @param warning color used for the middle part of the thresholds, e.g., yellow\n * @param error color that marks an error, e.g., red\n */\n public ColorTheme(String neutral, String healthy, String warning, String error) {\n this.neutral = neutral;\n this.healthy = healthy;\n this.warning = warning;\n this.error = error;\n }\n\n /**\n * Gets neutral color.\n * @return neutral color\n */\n public String getNeutral() {\n return neutral;\n }\n\n /**\n * Gets healthy color.\n * @return healthy color\n */\n public String getHealthy() {\n return healthy;\n }\n\n /**\n * Gets warning color.\n * @return warning color\n */\n public String getWarning() {\n return warning;\n }\n\n /**\n * Gets error color.\n * @return error color\n */\n public String getError() {\n return error;\n }\n\n /**\n * Gets a color configuration used in singlestat for when low value is good,\n * e.g., number of errors.\n * @return color configuration for singlestat\n */\n public Colors colorsWhenLowIsHealthy() {\n return new Colors(healthy, warning, error);\n }\n\n /**\n * Gets a color configuration used in singlestat for when high value is good,\n * e.g., number of instances alive.\n * @return color configuration for singlestat\n */\n public Colors colorsWhenHighIsHealthy() {\n return new Colors(error, warning, healthy);\n }\n}",
"public static Text placeholder(int span) {\n return newText()\n .withContent(\"\")\n .withTransparent(true)\n .withSpan(span);\n}",
"public static Row thinRow() {\n return newRow().withHeight(\"95px\");\n}",
"public static Text title(String title) {\n return newText()\n .withContent(\"<div class=\\\"text-center dashboard-header\\\"><span>\" + title + \"</span></div>\")\n .withMode(\"html\")\n .withTransparent(true);\n}"
] | import static uk.co.szmg.grafana.dashboard.StaticFactories.placeholder;
import static uk.co.szmg.grafana.dashboard.StaticFactories.thinRow;
import static uk.co.szmg.grafana.dashboard.StaticFactories.title;
import static uk.co.szmg.grafana.domain.DomainFactories.newDashboard;
import static uk.co.szmg.grafana.domain.DomainFactories.newRow;
import uk.co.szmg.grafana.DashboardFactory;
import uk.co.szmg.grafana.dashboard.ColorTheme;
import uk.co.szmg.grafana.domain.Dashboard;
import uk.co.szmg.grafana.domain.Row;
import uk.co.szmg.grafana.domain.SingleStat;
import javax.inject.Named;
import java.util.ArrayList;
import java.util.List; | package uk.co.szmg.grafana.example.dashboards.complex;
/*-
* #%L
* grafana-dashboard-generator-example
* %%
* Copyright (C) 2017 Mate Gabor Szvoboda
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
@Named
public class MultiEnvExampleDashboards implements DashboardFactory {
private SampleAppEnvironment environments[] =
new SampleAppEnvironment[]{
new SampleAppEnvironment("Staging", "graphite", "MYAPP.stage", 2),
new SampleAppEnvironment("Production", "aws.graphite", "MYAPP.prod", 10)
};
| private ColorTheme colorTheme = ColorTheme.RED_YELLOW_GREEN; | 1 |
ming-soft/MCMS | src/main/java/net/mingsoft/cms/action/ContentAction.java | [
"public class ContentBean extends ContentEntity {\n\n// /**\n// * 静态化地址\n// */\n// private String staticUrl;\n\n /**\n * 开始时间\n */\n private String beginTime;\n\n /**\n * 结束时间\n */\n private String endTime;\n\n /**\n * 属性标记\n */\n private String flag;\n\n /**\n * 不包含属性标记\n */\n private String noflag;\n\n /**\n * 栏目类型,用于筛选文章列表\n */\n private String categoryType;\n\n /**\n * 栏目属性,用于筛选文章列表\n */\n private String categoryFlag;\n\n public String getCategoryType() {\n return categoryType;\n }\n\n public void setCategoryType(String categoryType) {\n this.categoryType = categoryType;\n }\n\n public String getCategoryFlag() {\n return categoryFlag;\n }\n\n public void setCategoryFlag(String categoryFlag) {\n this.categoryFlag = categoryFlag;\n }\n\n public String getBeginTime() {\n return beginTime;\n }\n\n public void setBeginTime(String beginTime) {\n this.beginTime = beginTime;\n }\n\n public String getEndTime() {\n return endTime;\n }\n\n public void setEndTime(String endTime) {\n this.endTime = endTime;\n }\n\n public String getFlag() {\n return flag;\n }\n\n public void setFlag(String flag) {\n this.flag = flag;\n }\n\n public String getNoflag() {\n return noflag;\n }\n\n public void setNoflag(String noflag) {\n this.noflag = noflag;\n }\n}",
"public interface ICategoryBiz extends IBaseBiz<CategoryEntity> {\n\n /**\n * 查询当前分类下的所有子分类,包含自身\n * @param category 通过setId指定栏目id\n * @return\n */\n List<CategoryEntity> queryChildren(CategoryEntity category);\n\n void saveEntity(CategoryEntity entity);\n\n /**更新父级及子集\n * @param entity\n */\n void updateEntity(CategoryEntity entity);\n\n /**只更新自身\n * @param entity\n */\n void update(CategoryEntity entity);\n\n void delete(String categoryId);\n\n void copyCategory(CategoryEntity entity);\n}",
"public interface IContentBiz extends IBaseBiz<ContentEntity> {\n\n /**\n * 根据文章属性查询\n * @param contentBean\n * @return\n */\n List<CategoryBean> queryIdsByCategoryIdForParser(ContentBean contentBean);\n\n int getSearchCount(ModelEntity contentModel, List diyList, Map whereMap, int appId, String categoryIds);\n}",
"@TableName(\"cms_category\")\npublic class CategoryEntity extends BaseEntity {\n\n private static final long serialVersionUID = 1574925152750L;\n\n\n @TableId(type = IdType.ASSIGN_ID)\n private String id;\n\n @Override\n public String getId() {\n return id;\n }\n\n @Override\n public void setId(String id) {\n this.id = id;\n }\n\n /**\n * 栏目管理名称\n */\n private String categoryTitle;\n /**\n * 栏目别名\n */\n private String categoryPinyin;\n /**\n * 所属栏目\n */\n @TableField(insertStrategy = FieldStrategy.NOT_EMPTY, updateStrategy = FieldStrategy.NOT_EMPTY, whereStrategy = FieldStrategy.NOT_EMPTY)\n private String categoryId;\n /**\n * 栏目管理属性\n */\n private String categoryType;\n /**\n * 自定义顺序\n */\n private Integer categorySort;\n /**\n * 列表模板\n */\n private String categoryListUrl;\n /**\n * 内容模板\n */\n private String categoryUrl;\n /**\n * 栏目管理关键字\n */\n private String categoryKeyword;\n /**\n * 栏目管理描述\n */\n private String categoryDescrip;\n /**\n * 缩略图\n */\n private String categoryImg;\n\n\n /**\n * 自定义链接\n */\n private String categoryDiyUrl;\n /**\n * 栏目管理的内容模型id\n */\n private Integer mdiyModelId;\n\n /**\n * 字典对应编号\n */\n private Integer dictId;\n /**\n * 栏目属性\n */\n private String categoryFlag;\n /**\n * 栏目路径\n */\n private String categoryPath;\n /**\n * 父类型编号\n */\n private String categoryParentIds;\n\n /**\n * 叶子节点\n */\n private Boolean leaf;\n\n /**\n * 顶级id\n */\n private String topId;\n\n public Boolean getLeaf() {\n return leaf;\n }\n\n public void setLeaf(Boolean leaf) {\n this.leaf = leaf;\n }\n\n public String getTopId() {\n return topId;\n }\n\n public void setTopId(String topId) {\n this.topId = topId;\n }\n\n /**\n * 设置栏目管理名称\n */\n public void setCategoryTitle(String categoryTitle) {\n this.categoryTitle = categoryTitle;\n }\n\n /**\n * 获取栏目管理名称\n */\n public String getCategoryTitle() {\n return this.categoryTitle;\n }\n\n /**\n * 设置所属栏目\n */\n public void setCategoryId(String categoryId) {\n this.categoryId = categoryId;\n }\n\n public String getCategoryPinyin() {\n return categoryPinyin;\n }\n\n public void setCategoryPinyin(String categoryPinyin) {\n this.categoryPinyin = categoryPinyin;\n }\n\n /**\n * 获取所属栏目\n */\n public String getCategoryId() {\n return this.categoryId;\n }\n\n /**\n * 设置栏目管理属性\n */\n public void setCategoryType(String categoryType) {\n this.categoryType = categoryType;\n }\n\n /**\n * 获取栏目管理属性\n */\n public String getCategoryType() {\n return this.categoryType;\n }\n\n /**\n * 设置自定义顺序\n */\n public void setCategorySort(Integer categorySort) {\n this.categorySort = categorySort;\n }\n\n /**\n * 获取自定义顺序\n */\n public Integer getCategorySort() {\n return this.categorySort;\n }\n\n /**\n * 设置列表模板\n */\n public void setCategoryListUrl(String categoryListUrl) {\n this.categoryListUrl = categoryListUrl;\n }\n\n /**\n * 获取列表模板\n */\n public String getCategoryListUrl() {\n return this.categoryListUrl;\n }\n\n /**\n * 设置内容模板\n */\n public void setCategoryUrl(String categoryUrl) {\n this.categoryUrl = categoryUrl;\n }\n\n /**\n * 获取内容模板\n */\n public String getCategoryUrl() {\n return this.categoryUrl;\n }\n\n /**\n * 设置栏目管理关键字\n */\n public void setCategoryKeyword(String categoryKeyword) {\n this.categoryKeyword = categoryKeyword;\n }\n\n /**\n * 获取栏目管理关键字\n */\n public String getCategoryKeyword() {\n return this.categoryKeyword;\n }\n\n /**\n * 设置栏目管理描述\n */\n public void setCategoryDescrip(String categoryDescrip) {\n this.categoryDescrip = categoryDescrip;\n }\n\n /**\n * 获取栏目管理描述\n */\n public String getCategoryDescrip() {\n return this.categoryDescrip;\n }\n\n /**\n * 设置缩略图\n */\n public void setCategoryImg(String categoryImg) {\n this.categoryImg = categoryImg;\n }\n\n /**\n * 获取缩略图\n */\n public String getCategoryImg() {\n return this.categoryImg;\n }\n\n /**\n * 设置自定义链接\n */\n public void setCategoryDiyUrl(String categoryDiyUrl) {\n this.categoryDiyUrl = categoryDiyUrl;\n }\n\n /**\n * 获取自定义链接\n */\n public String getCategoryDiyUrl() {\n return this.categoryDiyUrl;\n }\n\n public Integer getMdiyModelId() {\n return mdiyModelId;\n }\n\n public void setMdiyModelId(Integer mdiyModelId) {\n this.mdiyModelId = mdiyModelId;\n }\n\n /**\n * 设置字典对应编号\n */\n public void setDictId(Integer dictId) {\n this.dictId = dictId;\n }\n\n /**\n * 获取字典对应编号\n */\n public Integer getDictId() {\n return this.dictId;\n }\n\n /**\n * 设置栏目属性\n */\n public void setCategoryFlag(String categoryFlag) {\n this.categoryFlag = categoryFlag;\n }\n\n /**\n * 获取栏目属性\n */\n public String getCategoryFlag() {\n return this.categoryFlag;\n }\n\n /**\n * 设置栏目路径\n */\n public void setCategoryPath(String categoryPath) {\n this.categoryPath = categoryPath;\n }\n\n /**\n * 获取栏目路径\n */\n public String getCategoryPath() {\n return this.categoryPath;\n }\n\n /**\n * 设置父类型编号\n */\n public void setCategoryParentIds(String categoryParentIds) {\n this.categoryParentIds = categoryParentIds;\n }\n\n /**\n * 获取父类型编号\n */\n public String getCategoryParentIds() {\n return this.categoryParentIds;\n }\n\n /**\n * 获取栏目标题 (标签使用)\n */\n public String getTypetitle() {\n return this.categoryTitle;\n }\n\n /**\n * 获取栏目链接 (标签使用,动态链接不考虑)\n */\n public String getTypelink() {\n return \"3\".equals(this.categoryType) ? this.categoryDiyUrl : this.categoryPath + \"/index.html\";\n }\n\n /**\n * 获取栏目关键字 (标签使用)\n */\n public String getTypekeyword() {\n return this.categoryKeyword;\n }\n\n /**\n * 获取栏目url (标签使用)\n */\n public String getTypeurl() {\n return this.categoryDiyUrl;\n }\n\n /**\n * 获取栏目属性 (标签使用)\n */\n public String getFlag() {\n return this.categoryFlag;\n }\n\n /**\n * 获取栏目父级Id (标签使用)\n */\n public String getParentids() {\n return this.categoryParentIds;\n }\n\n /**\n * 获取栏目描述(标签使用)\n */\n public String getTypedescrip() {\n return this.categoryDescrip;\n }\n\n /**\n * 获取栏目Id(标签使用)\n */\n public String getTypeid() {\n return this.id;\n }\n\n /**\n * 获取栏目Id(标签使用)\n */\n public Boolean getTypeleaf() {\n return this.leaf; }\n\n\n /**\n * 获取栏目图片 (标签使用)\n */\n public String getTypelitpic() {\n return categoryImg;\n }\n\n @TableField(exist = false)\n private String typepath;\n /**\n * 获取栏目图片 (标签使用)\n */\n public String getTypepath() {\n return categoryPath;\n }\n\n}",
"@TableName(\"cms_content\")\npublic class ContentEntity extends BaseEntity {\n\nprivate static final long serialVersionUID = 1574925152617L;\n\n\t@TableId(type = IdType.ASSIGN_ID)\n\tprivate String id;\n\n\t@Override\n\tpublic String getId() {\n\t\treturn id;\n\t}\n\n\t@Override\n\tpublic void setId(String id) {\n\t\tthis.id = id;\n\t}\n\t/**\n\t* 文章标题\n\t*/\n\tprivate String contentTitle;\n\t/**\n\t* 所属栏目\n\t*/\n\tprivate String categoryId;\n\t/**\n\t* 文章类型\n\t*/\n\tprivate String contentType;\n\t/**\n\t* 是否显示\n\t*/\n\tprivate String contentDisplay;\n\t/**\n\t* 文章作者\n\t*/\n\tprivate String contentAuthor;\n\t/**\n\t* 文章来源\n\t*/\n\tprivate String contentSource;\n\t/**\n\t* 发布时间\n\t*/\n\t@JSONField(format = \"yyyy-MM-dd HH:mm:ss\")\n\t@DateTimeFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")\n\t@JsonFormat(timezone = \"GMT+8\",pattern = \"yyyy-MM-dd HH:mm:ss\")\n\tprivate Date contentDatetime;\n\t/**\n\t* 自定义顺序\n\t*/\n\tprivate Integer contentSort;\n\t/**\n\t* 文章缩略图\n\t*/\n\tprivate String contentImg;\n\t/**\n\t* 描述\n\t*/\n\tprivate String contentDescription;\n\t/**\n\t* 关键字\n\t*/\n\tprivate String contentKeyword;\n\t/**\n\t* 文章内容\n\t*/\n\tprivate String contentDetails;\n\t/**\n\t* 文章跳转链接地址\n\t*/\n\tprivate String contentUrl;\n\t/**\n\t* 点击次数\n\t*/\n\tprivate Integer contentHit;\n\n\tpublic Integer getContentHit() {\n\t\treturn contentHit;\n\t}\n\n\tpublic void setContentHit(Integer contentHit) {\n\t\tthis.contentHit = contentHit;\n\t}\n\n\t/**\n\t* 设置文章标题\n\t*/\n\tpublic void setContentTitle(String contentTitle) {\n\tthis.contentTitle = contentTitle;\n\t}\n\n\t/**\n\t* 获取文章标题\n\t*/\n\tpublic String getContentTitle() {\n\treturn this.contentTitle;\n\t}\n\n\tpublic String getCategoryId() {\n\t\treturn categoryId;\n\t}\n\n\tpublic void setCategoryId(String categoryId) {\n\t\tthis.categoryId = categoryId;\n\t}\n\n\t/**\n\t* 设置文章类型\n\t*/\n\tpublic void setContentType(String contentType) {\n\tthis.contentType = contentType;\n\t}\n\n\t/**\n\t* 获取文章类型\n\t*/\n\tpublic String getContentType() {\n\treturn this.contentType;\n\t}\n\t/**\n\t* 设置是否显示\n\t*/\n\tpublic void setContentDisplay(String contentDisplay) {\n\tthis.contentDisplay = contentDisplay;\n\t}\n\n\t/**\n\t* 获取是否显示\n\t*/\n\tpublic String getContentDisplay() {\n\treturn this.contentDisplay;\n\t}\n\t/**\n\t* 设置文章作者\n\t*/\n\tpublic void setContentAuthor(String contentAuthor) {\n\tthis.contentAuthor = contentAuthor;\n\t}\n\n\t/**\n\t* 获取文章作者\n\t*/\n\tpublic String getContentAuthor() {\n\treturn this.contentAuthor;\n\t}\n\t/**\n\t* 设置文章来源\n\t*/\n\tpublic void setContentSource(String contentSource) {\n\tthis.contentSource = contentSource;\n\t}\n\n\t/**\n\t* 获取文章来源\n\t*/\n\tpublic String getContentSource() {\n\treturn this.contentSource;\n\t}\n\t/**\n\t* 设置发布时间\n\t*/\n\tpublic void setContentDatetime(Date contentDatetime) {\n\tthis.contentDatetime = contentDatetime;\n\t}\n\n\t/**\n\t* 获取发布时间\n\t*/\n\tpublic Date getContentDatetime() {\n\treturn this.contentDatetime;\n\t}\n\t/**\n\t* 设置自定义顺序\n\t*/\n\tpublic void setContentSort(Integer contentSort) {\n\tthis.contentSort = contentSort;\n\t}\n\n\t/**\n\t* 获取自定义顺序\n\t*/\n\tpublic Integer getContentSort() {\n\treturn this.contentSort;\n\t}\n\t/**\n\t* 设置文章缩略图\n\t*/\n\tpublic void setContentImg(String contentImg) {\n\tthis.contentImg = contentImg;\n\t}\n\n\t/**\n\t* 获取文章缩略图\n\t*/\n\tpublic String getContentImg() {\n\treturn this.contentImg;\n\t}\n\t/**\n\t* 设置描述\n\t*/\n\tpublic void setContentDescription(String contentDescription) {\n\tthis.contentDescription = contentDescription;\n\t}\n\n\t/**\n\t* 获取描述\n\t*/\n\tpublic String getContentDescription() {\n\treturn this.contentDescription;\n\t}\n\t/**\n\t* 设置关键字\n\t*/\n\tpublic void setContentKeyword(String contentKeyword) {\n\tthis.contentKeyword = contentKeyword;\n\t}\n\n\t/**\n\t* 获取关键字\n\t*/\n\tpublic String getContentKeyword() {\n\treturn this.contentKeyword;\n\t}\n\t/**\n\t* 设置文章内容\n\t*/\n\tpublic void setContentDetails(String contentDetails) {\n\tthis.contentDetails = contentDetails;\n\t}\n\n\t/**\n\t* 获取文章内容\n\t*/\n\tpublic String getContentDetails() {\n\treturn this.contentDetails;\n\t}\n\t/**\n\t* 设置文章跳转链接地址\n\t*/\n\tpublic void setContentUrl(String contentUrl) {\n\tthis.contentUrl = contentUrl;\n\t}\n\n\t/**\n\t* 获取文章跳转链接地址\n\t*/\n\tpublic String getContentUrl() {\n\treturn this.contentUrl;\n\t}\n}"
] | import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.mingsoft.base.entity.ResultData;
import net.mingsoft.basic.annotation.LogAnn;
import net.mingsoft.basic.bean.EUListBean;
import net.mingsoft.basic.constant.e.BusinessTypeEnum;
import net.mingsoft.basic.util.BasicUtil;
import net.mingsoft.basic.util.StringUtil;
import net.mingsoft.cms.bean.ContentBean;
import net.mingsoft.cms.biz.ICategoryBiz;
import net.mingsoft.cms.biz.IContentBiz;
import net.mingsoft.cms.entity.CategoryEntity;
import net.mingsoft.cms.entity.ContentEntity;
import net.mingsoft.mdiy.biz.IModelBiz;
import net.mingsoft.mdiy.entity.ModelEntity;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; | /**
* The MIT License (MIT)
* Copyright (c) 2012-2022 铭软科技(mingsoft.net)
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package net.mingsoft.cms.action;
/**
* 文章管理控制层
* @author 铭飞开发团队
* 创建日期:2019-11-28 15:12:32<br/>
* 历史修订:<br/>
*/
@Api(tags={"后端-内容模块接口"})
@Controller("cmsContentAction")
@RequestMapping("/${ms.manager.path}/cms/content")
public class ContentAction extends BaseAction {
/**
* 注入文章业务层
*/
@Autowired
private IContentBiz contentBiz;
@Autowired | private ICategoryBiz categoryBiz; | 1 |
pfstrack/eldamo | src/test/java/xdb/dom/XQueryEngineTest.java | [
"public class ModelConfigManagerTest extends TestCase {\n\n public ModelConfigManagerTest(String testName) {\n super(testName);\n }\n\n public static ModelConfigManager getTestModelConfigManager() {\n init();\n return ModelConfigManager.instance();\n }\n\n public static void init() {\n Class<ModelConfigManagerTest> cls = ModelConfigManagerTest.class;\n URL url = cls.getResource(\"model-configs/model-config.xml\");\n File root = new File(url.getPath()).getParentFile();\n final String realPath = root.getAbsolutePath();\n ServletContext context = new MockContext() {\n\n @Override\n public String getRealPath(String path) {\n return realPath;\n }\n };\n ModelConfigManager.init(context);\n }\n\n public void testInit() {\n init();\n }\n\n public void testInstance() {\n ModelConfigManager result = getTestModelConfigManager();\n assertNotNull(result);\n }\n\n public void testGetKeys() {\n ModelConfigManager manager = getTestModelConfigManager();\n assertTrue(manager.getKeys(\"product\").size() >= 2);\n }\n}",
"public final class XQueryEngine {\n\n private XQueryEngine() {\n }\n\n @SuppressWarnings(\"serial\")\n private static final ModuleURIResolver MR = new ModuleURIResolver() {\n public StreamSource[] resolve(String moduleURI, String baseURI, String[] locations)\n throws XPathException {\n try {\n int lastSlash = moduleURI.lastIndexOf('/');\n if (lastSlash >= 0) {\n moduleURI = moduleURI.substring(lastSlash + 1);\n }\n String path = QueryConfigManager.getConfigRoot() + \"/\" + moduleURI;\n StreamSource src;\n src = new StreamSource(new FileInputStream(path), path);\n StreamSource[] srcs = { src };\n return srcs;\n } catch (FileNotFoundException e) {\n return null;\n }\n }\n };\n\n private static final NamespaceResolver NR = new NamespaceResolver() {\n\n public String getURIForPrefix(String arg0, boolean arg1) {\n if (\"xdb\".equals(arg0)) {\n return \"java:xdb.dom.CustomFunctions\";\n }\n return null;\n }\n\n public Iterator<String> iteratePrefixes() {\n return Collections.singletonList(\"xdb\").iterator();\n }\n };\n\n /**\n * Perform an xquery.\n * \n * @param context\n * The context.\n * @param xquery\n * The xquery.\n * @param params\n * Query parameters.\n * @param out\n * The output stream.\n * @param outputType\n * The output type.\n * @throws XPathException\n * For errors.\n */\n public static void query(Node context, String xquery, Map<String, String> params, Writer out,\n String outputType) throws XPathException {\n final Configuration config = XmlUtil.SAXON_CONFIG;\n final StaticQueryContext sqc = new StaticQueryContext(config);\n sqc.setModuleURIResolver(MR);\n sqc.setExternalNamespaceResolver(NR);\n final XQueryExpression expression = sqc.compileQuery(xquery); // TODO : cache\n Controller controller = expression.newController();\n controller.checkImplicitResultTree();\n\n final DynamicQueryContext queryContext = new DynamicQueryContext(config);\n for (String key : params.keySet()) {\n queryContext.setParameter(key, params.get(key));\n }\n queryContext.setContextItem((NodeImpl) context);\n final Properties props = new Properties();\n props.setProperty(OutputKeys.METHOD, outputType);\n props.setProperty(OutputKeys.INDENT, \"yes\");\n expression.run(queryContext, new StreamResult(out), props);\n }\n}",
"public class XmlParser extends DocumentBuilder {\n private ErrorHandler eh = null;\n\n @Override\n public DOMImplementation getDOMImplementation() {\n return DocumentImpl.IMPLEMENTATION;\n }\n\n @Override\n public boolean isNamespaceAware() {\n return false;\n }\n\n @Override\n public boolean isValidating() {\n return false;\n }\n\n @Override\n public Document newDocument() {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public void setEntityResolver(EntityResolver er) {\n }\n\n @Override\n public void setErrorHandler(ErrorHandler errorHandler) {\n this.eh = errorHandler;\n }\n\n @Override\n public Document parse(InputSource is) throws SAXException, IOException {\n try {\n SAXParserFactory factor = SAXParserFactory.newInstance();\n SAXParser parser = factor.newSAXParser();\n XMLReader reader = parser.getXMLReader();\n if (eh != null) {\n reader.setErrorHandler(eh);\n }\n DomHandler handler = new DomHandler();\n reader.setContentHandler(handler);\n reader.parse(is);\n return handler.getDoc();\n } catch (ParserConfigurationException ex) {\n throw new SAXException(ex);\n }\n }\n}",
"public class DocumentImpl extends NodeImpl implements Document, DocumentInfo {\n\n public static final DOMImplementationImpl IMPLEMENTATION = new DOMImplementationImpl();\n private NodeList childNodes = NodeListImpl.EMPTY_LIST;\n private Map<String, String> nodeNames;\n private Map<String, Element> elementById = new HashMap<String, Element>();\n private volatile Map<String, Map<String, List<Node>>> keyMap = Collections.emptyMap();\n private final int documentNumber;\n\n /**\n * Constructor.\n * \n * @param position\n * Node position within document.\n */\n public DocumentImpl(int position) {\n super(position);\n documentNumber = getConfiguration().getDocumentNumberAllocator().allocateDocumentNumber();\n }\n\n @Override\n public Node adoptNode(Node source) throws DOMException {\n throw DOMImplementationImpl.notSupportedErr();\n }\n\n @Override\n public Attr createAttribute(String name) throws DOMException {\n throw DOMImplementationImpl.notSupportedErr();\n }\n\n @Override\n public Attr createAttributeNS(String namespaceURI, String qualifiedName) throws DOMException {\n throw DOMImplementationImpl.notSupportedErr();\n }\n\n @Override\n public CDATASection createCDATASection(String data) throws DOMException {\n throw DOMImplementationImpl.notSupportedErr();\n }\n\n @Override\n public Comment createComment(String data) {\n throw DOMImplementationImpl.notSupportedErr();\n }\n\n @Override\n public DocumentFragment createDocumentFragment() {\n throw DOMImplementationImpl.notSupportedErr();\n }\n\n @Override\n public Element createElement(String tagName) throws DOMException {\n throw DOMImplementationImpl.notSupportedErr();\n }\n\n @Override\n public Element createElementNS(String namespaceURI, String qualifiedName) throws DOMException {\n throw DOMImplementationImpl.notSupportedErr();\n }\n\n @Override\n public EntityReference createEntityReference(String name) throws DOMException {\n throw DOMImplementationImpl.notSupportedErr();\n }\n\n @Override\n public ProcessingInstruction createProcessingInstruction(String target, String data) throws DOMException {\n throw DOMImplementationImpl.notSupportedErr();\n }\n\n @Override\n public Text createTextNode(String data) {\n throw DOMImplementationImpl.notSupportedErr();\n }\n\n @Override\n public DocumentType getDoctype() {\n return null;\n }\n\n @Override\n public Element getDocumentElement() {\n return (Element) this.getFirstChild();\n }\n\n @Override\n public String getDocumentURI() {\n return null;\n }\n\n @Override\n public DOMConfiguration getDomConfig() {\n throw DOMImplementationImpl.notSupportedErr();\n }\n\n @Override\n public Element getElementById(String id) {\n return elementById.get(id);\n }\n\n @Override\n public NodeList getElementsByTagName(String tagname) {\n String name = getCanonicalName(tagname);\n if (name == null) {\n return NodeListImpl.EMPTY_LIST;\n }\n List<Node> list = new LinkedList<Node>();\n ElementBase.addByTagName(getChildNodes(), name, list);\n return NodeListImpl.toNodeList(list);\n }\n\n @Override\n public NodeList getElementsByTagNameNS(String namespaceURI, String localName) {\n return getElementsByTagName(localName);\n }\n\n @Override\n public DOMImplementation getImplementation() {\n return IMPLEMENTATION;\n }\n\n @Override\n public String getInputEncoding() {\n return null;\n }\n\n @Override\n public boolean getStrictErrorChecking() {\n return false;\n }\n\n @Override\n public String getXmlEncoding() {\n return null;\n }\n\n @Override\n public boolean getXmlStandalone() {\n return false;\n }\n\n @Override\n public String getXmlVersion() {\n return \"1.0\";\n }\n\n @Override\n public Node importNode(Node importedNode, boolean deep) throws DOMException {\n if (!deep || !(importedNode instanceof ElementBase)) {\n throw DOMImplementationImpl.badImportErr();\n }\n return importNode((ElementBase) importedNode, this);\n }\n\n private ElementBase importNode(ElementBase element, Node parent) throws DOMException {\n String name = getOrSetCanonicalName(element.getNodeName());\n int position = element.getPosition();\n ElementBase result = null;\n if (element instanceof TextElementImpl) {\n String text = element.getTextContent();\n result = new TextElementImpl(position, name, parent, text);\n } else if (element instanceof ElementImpl) {\n result = new ElementImpl(position, name, parent);\n }\n\n NamedNodeMapImpl atts = (NamedNodeMapImpl) element.getAttributes();\n String[][] rawAtts = atts.getRawAttributes();\n String[][] newAtts = new String[rawAtts.length][2];\n for (int i = 0; i < rawAtts.length; i++) {\n String[] att = rawAtts[i];\n String attName = getOrSetCanonicalName(att[0]);\n String[] newAtt = { attName, att[1] };\n newAtts[i] = newAtt;\n }\n result.setAttributes(new NamedNodeMapImpl(result, newAtts));\n\n if (element instanceof ElementImpl) {\n ElementImpl resultImpl = (ElementImpl) result;\n NodeList children = element.getChildNodes();\n for (int i = 0; i < children.getLength(); i++) {\n ElementBase child = (ElementBase) children.item(i);\n child = importNode(child, result);\n resultImpl.addChild(child);\n }\n resultImpl.fixChildren();\n }\n\n return result;\n }\n\n @Override\n public void normalizeDocument() {\n }\n\n @Override\n public Node renameNode(Node n, String namespaceURI, String qualifiedName) throws DOMException {\n throw DOMImplementationImpl.notSupportedErr();\n }\n\n @Override\n public void setDocumentURI(String documentURI) {\n }\n\n @Override\n public void setStrictErrorChecking(boolean strictErrorChecking) {\n }\n\n @Override\n public void setXmlStandalone(boolean xmlStandalone) throws DOMException {\n }\n\n @Override\n public void setXmlVersion(String xmlVersion) throws DOMException {\n }\n\n @Override\n public short getNodeType() {\n return Node.DOCUMENT_NODE;\n }\n\n @Override\n public String getNodeValue() throws DOMException {\n return null;\n }\n\n @Override\n public String getNodeName() {\n return \"#document\";\n }\n\n @Override\n public NodeList getChildNodes() {\n return this.childNodes;\n }\n\n @Override\n public boolean hasChildNodes() {\n return true;\n }\n\n @Override\n public Node getParentNode() {\n return null;\n }\n\n @Override\n public String getTextContent() throws DOMException {\n return null;\n }\n\n @Override\n public Node getPreviousSibling() {\n return null;\n }\n\n @Override\n public Node getNextSibling() {\n return null;\n }\n\n /**\n * Get the canonical name string for elements and attributes. This string is the same object used for the node name\n * of strings and elements in the document, suitable for comparison using \"==\" instead of \"String.equals()\". Using\n * the canonical name string instead of an otherwise equal string can significantly improve performance.\n * \n * TODO: Deprecate and replace with optimized logic based on Saxon name-pool.\n * \n * @param name\n * The name.\n * @return The canonical name string.\n */\n public String getCanonicalName(String name) {\n return this.nodeNames.get(name);\n }\n\n private String getOrSetCanonicalName(String name) {\n String canonical = this.nodeNames.get(name);\n if (canonical == null) {\n this.nodeNames.put(name, name);\n canonical = name;\n }\n return canonical;\n }\n\n /**\n * Get elements by a key from the indexes.\n * \n * @param key\n * The key/index name.\n * @param value\n * The lookup value.\n * @return The list of elements.\n */\n public List<Node> getElementsFromKey(String key, String value) {\n Map<String, List<Node>> index = keyMap.get(key);\n if (index == null) {\n return Collections.emptyList();\n }\n List<Node> matches = index.get(value);\n if (matches == null) {\n return Collections.emptyList();\n }\n return matches;\n }\n\n /**\n * Build the index for key lookups.\n * \n * @throws javax.xml.xpath.XPathExpressionException\n * For errors.\n */\n public void buildIndex() throws XPathExpressionException {\n Element element = getDocumentElement();\n CustomFunctions.setHashcodeMap(indexHashcodes(element));\n Map<String, Map<String, List<Node>>> map = new HashMap<String, Map<String, List<Node>>>();\n indexElement(element, map);\n keyMap = map;\n }\n\n private Map<String, String> indexHashcodes(Element root) {\n Map<String, String> hashcodeMap = new HashMap<String, String>();\n Set<String> pageIds = new HashSet<String>();\n NodeList words = root.getElementsByTagName(\"word\");\n // Initialize hashcodes for elements with page ids\n for (int i = 0; i < words.getLength(); i++) {\n Element word = (Element) words.item(i);\n String pageId = word.getAttribute(\"page-id\");\n if (pageId.length() > 0) {\n String key = CustomFunctions.hashKey(word.getAttribute(\"l\"), word.getAttribute(\"v\"));\n hashcodeMap.put(key, pageId);\n pageIds.add(pageId);\n }\n }\n // Initialize hashcodes for elements without page ids\n for (int i = 0; i < words.getLength(); i++) {\n Element word = (Element) words.item(i);\n if (word.getAttribute(\"page-id\").length() == 0) {\n String key = CustomFunctions.hashKey(word.getAttribute(\"l\"), word.getAttribute(\"v\"));\n String pageId = CustomFunctions.hashValue(key);\n while (pageIds.contains(pageId)) {\n pageId = String.valueOf(Long.valueOf(pageId) + 1);\n }\n hashcodeMap.put(key, pageId);\n pageIds.add(pageId);\n }\n }\n return hashcodeMap;\n }\n\n void indexElement(Element element, Map<String, Map<String, List<Node>>> map)\n throws XPathExpressionException {\n String elementName = element.getNodeName();\n List<Key> keys = ModelConfigManager.instance().getKeys(elementName);\n for (Key key : keys) {\n Map<String, List<Node>> index = map.get(key.getName());\n if (index == null) {\n index = new HashMap<String, List<Node>>();\n map.put(key.getName(), index);\n }\n if (key.getMatch().equals(elementName)) {\n updateIndex(index, element, key, false);\n }\n }\n if (element instanceof ElementImpl) {\n NodeList children = element.getChildNodes();\n for (int i = 0; i < children.getLength(); i++) {\n Element child = (Element) children.item(i);\n indexElement(child, map);\n }\n }\n }\n\n\tprivate void updateIndex(Map<String, List<Node>> index, Element element,\n\t\t\tKey key, boolean sort) throws XPathExpressionException {\n\t\tif (\"string\".equals(key.getType())) {\n\t\t String id = XPathEngine.stringQuery(element, key.getXpath());\n\t\t if (id != null && id.length() > 0) {\n\t\t putInIndex(index, element, id, sort);\n\t\t }\n\t\t} else if (\"string-list\".equals(key.getType())) {\n\t\t String ids = XPathEngine.stringQuery(element, key.getXpath()).trim();\n\t\t if (ids != null && ids.length() > 0) {\n\t\t String[] idList = ids.split(\" \");\n\t\t for (String id : idList) {\n\t\t putInIndex(index, element, id, sort);\n\t\t }\n\t\t }\n\t\t} else {\n\t\t List<Node> nodes = XPathEngine.query(element, key.getXpath());\n\t\t for (Node node : nodes) {\n\t\t String id = node.getTextContent();\n\t\t if (id != null && id.length() > 0) {\n\t\t putInIndex(index, element, id, sort);\n\t\t }\n\t\t }\n\t\t}\n\t}\n\n\tprivate void putInIndex(Map<String, List<Node>> index, Element element,\n\t\t\tString id, boolean sort) {\n\t\tList<Node> list = index.get(id);\n\t\tif (list == null) {\n\t\t list = new LinkedList<Node>();\n\t\t index.put(id, list);\n\t\t}\n\t\tlist.add(element);\n\t\tif (sort) {\n Collections.sort(list, NODE_COMPARATOR);\n\t\t}\n\t}\n\n /**\n * Recalculate node positions in document order. Should be called after incorporating new nodes into the DOM, but\n * before re-indexing.\n */\n public void reposition() {\n reposition((ElementBase) getDocumentElement(), 1);\n }\n\n void reposition(ElementBase element, int position) {\n element.setPosition(position++);\n if (element instanceof ElementImpl) {\n position += element.getAttributes().getLength() * 2;\n NodeList children = element.getChildNodes();\n for (int i = 0; i < children.getLength(); i++) {\n reposition((ElementBase) children.item(i), position);\n }\n } else {\n position++; // For text node\n }\n }\n\n /**\n * Reindex a given element.\n * \n * @param element\n * The element.\n * @throws XPathExpressionException\n * For errors.\n */\n public void reindex(Element element) throws XPathExpressionException {\n this.elementById.put(element.getAttribute(\"id\"), element);\n String elementName = element.getNodeName();\n List<Key> keys = ModelConfigManager.instance().getKeys(elementName);\n for (Key key : keys) {\n Map<String, List<Node>> index = keyMap.get(key.getName());\n if (index == null) {\n index = new HashMap<String, List<Node>>();\n keyMap.put(key.getName(), index);\n }\n if (key.getMatch().equals(elementName)) {\n updateIndex(index, element, key, true);\n }\n }\n }\n\n /**\n * Remove the given elements from the index.\n * \n * @param elements\n * The elements.\n */\n public void unindex(Element[] elements) {\n for (Map<String, List<Node>> index : keyMap.values()) {\n for (List<Node> list : index.values()) {\n Iterator<Node> i = list.iterator();\n while (i.hasNext()) {\n Element element = (Element) i.next();\n for (Element unindex : elements) {\n if (element == unindex) {\n i.remove();\n }\n }\n }\n }\n }\n }\n\n @Override\n void addChild(Node child) {\n if (!(childNodes instanceof NodeListMutable)) {\n childNodes = new NodeListMutable();\n }\n ((NodeListMutable) childNodes).add(child);\n }\n\n @Override\n void fixChildren() {\n if (childNodes instanceof NodeListMutable) {\n childNodes = ((NodeListMutable) childNodes).fixed();\n }\n }\n\n void setNodeNames(Set<String> nodeNames) {\n this.nodeNames = new HashMap<String, String>(nodeNames.size());\n for (String name : nodeNames) {\n this.nodeNames.put(name, name);\n }\n }\n\n void setElementById(Map<String, Element> elementById) {\n this.elementById = elementById;\n }\n\n private static final Comparator<Node> NODE_COMPARATOR = new Comparator<Node>() {\n public int compare(Node o1, Node o2) {\n if (o1.isSameNode(o2)) {\n return 0;\n } else if ((o1.compareDocumentPosition(o2) & Node.DOCUMENT_POSITION_FOLLOWING) > 0) {\n return 1;\n } else {\n return -1;\n }\n }\n };\n\n @Override\n public int getNodeKind() {\n return Type.DOCUMENT;\n }\n\n @Override\n public int getDocumentNumber() {\n return documentNumber;\n }\n\n @Override\n public NodeInfo selectID(String id) {\n return (NodeImpl) getElementById(id);\n }\n\n @Override\n public Iterator<?> getUnparsedEntityNames() {\n return Collections.EMPTY_LIST.iterator();\n }\n\n @Override\n public String[] getUnparsedEntity(String name) {\n return null;\n }\n}",
"public final class XmlUtil {\n\n public static final Processor PROCESSOR = new Processor(false);\n public static final Configuration SAXON_CONFIG = PROCESSOR.getUnderlyingConfiguration();\n\n private XmlUtil() {\n }\n\n /**\n * Verify that specified file is well-formed XML. Does not validate against the schema or DTD.\n * \n * @param xml\n * The XML file.\n * @throws SAXException\n * For parse errors.\n * @throws IOException\n * For I/O errors.\n */\n public static void verifyXml(File xml) throws SAXException, IOException {\n if (!xml.exists()) {\n throw new IOException(\"XML file \" + xml + \" does not exist.\");\n }\n parse(xml.getAbsolutePath(), new DefaultHandler());\n }\n\n /**\n * Parse file as namespaceless XML. Does not load the DTD, if any.\n * \n * @param path\n * The XML file.\n * @param handler\n * The handler. If it is a {@link org.xml.sax.ext.LexicalHandler} it is specified as\n * the lexical handler for the parser as well.\n * @throws SAXException\n * For parse errors.\n * @throws IOException\n * For I/O errors.\n */\n public static void parse(String path, DefaultHandler handler) throws SAXException, IOException {\n parse(new FileInputStream(path), handler);\n }\n\n /**\n * Parse file as namespaceless XML. Does not load the DTD, if any.\n * \n * @param file\n * The XML file.\n * @param handler\n * The handler. If it is a {@link org.xml.sax.ext.LexicalHandler} it is specified as\n * the lexical handler for the parser as well.\n * @throws SAXException\n * For parse errors.\n * @throws IOException\n * For I/O errors.\n */\n public static void parse(File file, DefaultHandler handler) throws SAXException, IOException {\n parse(new FileInputStream(file), handler);\n }\n\n /**\n * Parse file as namespaceless XML. Does not load the DTD, if any. Closes the stream when done.\n * \n * @param in\n * The input stream\n * @param handler\n * The handler. If it is a {@link org.xml.sax.ext.LexicalHandler} it is specified as\n * the lexical handler for the parser as well.\n * @throws SAXException\n * For parse errors.\n * @throws IOException\n * For I/O errors.\n */\n public static void parse(InputStream in, DefaultHandler handler) throws SAXException,\n IOException {\n BufferedInputStream bis = new BufferedInputStream(in);\n try {\n SAXParserFactory pf = SAXParserFactory.newInstance();\n pf.setValidating(false);\n pf.setFeature(\"http://apache.org/xml/features/nonvalidating/load-external-dtd\", false);\n pf.setNamespaceAware(false);\n SAXParser p = pf.newSAXParser();\n if (handler instanceof LexicalHandler) {\n p.setProperty(\"http://xml.org/sax/properties/lexical-handler\", handler);\n }\n p.parse(bis, handler);\n } catch (ParserConfigurationException e) {\n throw new SAXException(e);\n } finally {\n bis.close();\n }\n }\n\n /**\n * Parse an xs:dateTime value in \"2009-05-21T14:52:18-07:00\" format (with the timezone).\n * \n * @param timestamp\n * The xs:dateTime\n * @return The converted date\n * @throws DatatypeConfigurationException\n * For errors.\n */\n public static Date parseXmlDateTimeWithZone(String timestamp)\n throws DatatypeConfigurationException {\n DatatypeFactory datatypeFactory = DatatypeFactory.newInstance();\n XMLGregorianCalendar xmlGregorianCalendar = datatypeFactory\n .newXMLGregorianCalendar(timestamp);\n GregorianCalendar gregorianCalendar = xmlGregorianCalendar.toGregorianCalendar();\n return gregorianCalendar.getTime();\n }\n\n /**\n * Format a date in xs:dateTime format.\n * \n * @param date\n * The date.\n * @return The xs:dateTime\n * @throws DatatypeConfigurationException\n * For errors.\n */\n public static String formatXmlDateTimeWithZone(Date date) throws DatatypeConfigurationException {\n GregorianCalendar gc = new GregorianCalendar();\n gc.setTime(date);\n DatatypeFactory datatypeFactory = DatatypeFactory.newInstance();\n XMLGregorianCalendar xmlGregorianCalendar = datatypeFactory.newXMLGregorianCalendar(gc);\n return xmlGregorianCalendar.toXMLFormat();\n }\n\n /**\n * Get the first child element with the given name.\n * \n * @param element\n * The parent element.\n * @param name\n * The child element name.\n * @return The child element.\n */\n public static Element getChildElement(Element element, String name) {\n DocumentImpl doc = (DocumentImpl) element.getOwnerDocument();\n name = doc.getCanonicalName(name);\n NodeList children = element.getChildNodes();\n for (int i = 0; i < children.getLength(); i++) {\n Node child = children.item(i);\n if (child.getNodeType() == Node.ELEMENT_NODE) {\n if (child.getNodeName() == name) {\n return (Element) child;\n }\n }\n }\n return null;\n }\n\n /**\n * Get all child elements with the given name.\n * \n * @param element\n * The parent element.\n * @param name\n * The child element name.\n * @return The child elements.\n */\n public static List<Element> getChildElements(Element element, String name) {\n DocumentImpl doc = (DocumentImpl) element.getOwnerDocument();\n name = doc.getCanonicalName(name);\n NodeList children = element.getChildNodes();\n List<Element> result = new LinkedList<Element>();\n for (int i = 0; i < children.getLength(); i++) {\n Node child = children.item(i);\n if (child.getNodeType() == Node.ELEMENT_NODE) {\n if (child.getNodeName() == name) {\n result.add((Element) child);\n }\n }\n }\n return result;\n }\n\n /**\n * Write XML header (UTF-8).\n * \n * @param out\n * The writer.\n */\n public static void writeXmlHeader(PrintWriter out) {\n out.print(\"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\");\n }\n\n /**\n * Write open element with attributes.\n * \n * @param out\n * The output stream.\n * @param element\n * The element name.\n * @param attributes\n * The attributes.\n */\n public static void writeOpenElement(PrintWriter out, String element, NamedNodeMap attributes) {\n writeOpenElementFragment(out, element, attributes);\n out.print('>');\n }\n\n /**\n * Write close element.\n * \n * @param out\n * The writer.\n * @param element\n * The element name.\n */\n public static void writeCloseElement(PrintWriter out, String element) {\n out.print(\"</\");\n out.print(element);\n out.print('>');\n }\n\n /**\n * Write attribute. If the value is null, no attribute is written.\n * \n * @param out\n * The writer.\n * @param name\n * The attribute name.\n * @param value\n * The attribute value.\n */\n public static void writeAttribute(PrintWriter out, String name, String value) {\n if (value != null) {\n out.print(' ');\n out.print(name);\n out.print(\"=\\\"\");\n writeCharacters(out, value);\n out.print(\"\\\"\");\n }\n }\n\n /**\n * Write characters. Character data is properly escaped.\n * \n * @param out\n * The writer.\n * @param value\n * The text as a strng.\n */\n public static void writeCharacters(PrintWriter out, String value) {\n writeCharacters(out, value.toCharArray(), 0, value.length());\n }\n\n /**\n * Write characters. Character data is properly escaped.\n * \n * @param out\n * The writer.\n * @param ch\n * The character array.\n * @param start\n * Start position.\n * @param length\n * Substring length.\n */\n public static void writeCharacters(PrintWriter out, char[] ch, int start, int length) {\n for (int j = start; j < start + length; j++) {\n char c = ch[j];\n if (c == '&') {\n out.print(\"&\");\n } else if (c == '\"') {\n out.print(\""\");\n } else if (c == '<') {\n out.print(\"<\");\n } else if (c == '>') {\n out.print(\">\");\n } else if (c == '\\'') {\n out.print(\"'\");\n } else {\n out.print(c);\n }\n }\n }\n\n /**\n * Write the beginning of an XML element and its attributes. The closing \">\" is omitted. For\n * example:\n * \n * <pre>\n * <element att=\"value\"\n * </pre>\n * \n * @param out\n * The writer.\n * @param element\n * The writer.\n * @param attributes\n * Its attributes.\n */\n public static void writeOpenElementFragment(PrintWriter out, String element,\n NamedNodeMap attributes) {\n out.print('<');\n out.print(element);\n if (attributes != null) {\n String[][] raw = ((NamedNodeMapImpl) attributes).getRawAttributes();\n for (String[] attribute : raw) {\n writeAttribute(out, attribute[0], attribute[1]);\n }\n }\n }\n\n /**\n * Write document to the specified path.\n * \n * @param path\n * The path.\n * @param doc\n * The document.\n * @throws IOException\n * For errors.\n */\n public static void writeXml(String path, Document doc) throws IOException {\n String tmp = path + \".tmp\";\n PrintWriter out = FileUtil.open(tmp);\n try {\n XmlUtil.writeXml(out, doc);\n } finally {\n out.close();\n }\n FileUtil.moveTempFile(tmp, path);\n }\n\n /**\n * Write gzipped document to the specified path.\n * \n * @param path\n * The path.\n * @param doc\n * The document.\n * @throws IOException\n * For errors.\n */\n public static void writeXmlGzipped(String path, Document doc) throws IOException {\n String tmp = path + \".tmp\";\n PrintWriter out = FileUtil.openGzip(tmp);\n try {\n XmlUtil.writeXml(out, doc);\n } finally {\n out.close();\n }\n FileUtil.moveTempFile(tmp, path);\n }\n\n /**\n * Write document with UTF-8 XML header.\n * \n * @param out\n * The output stream.\n * @param doc\n * The document.\n */\n public static void writeXml(PrintWriter out, Document doc) {\n writeXmlHeader(out);\n out.print('\\n');\n writeElement(out, doc.getDocumentElement());\n }\n\n /**\n * Convert XML document to a string.\n * \n * @param doc\n * The doc.\n * @return The xml string.\n */\n public static String xmlToString(Document doc) {\n StringWriter sw = new StringWriter();\n PrintWriter pw = new PrintWriter(sw);\n writeXml(pw, doc);\n return sw.toString();\n }\n\n /**\n * Write element with all of its attributes and children.\n * \n * @param out\n * The output stream.\n * @param element\n * The element.\n */\n public static void writeElement(PrintWriter out, Element element) {\n String name = element.getNodeName();\n writeOpenElementFragment(out, name, element.getAttributes());\n NodeList children = element.getChildNodes();\n if (children.getLength() == 0) {\n out.print(\"/>\\n\");\n } else {\n if (element instanceof TextElementImpl) {\n out.print(\">\");\n } else {\n out.print(\">\\n\");\n }\n for (int i = 0; i < children.getLength(); i++) {\n Node child = children.item(i);\n if (child.getNodeType() == Node.ELEMENT_NODE) {\n writeElement(out, (Element) child);\n } else {\n writeCharacters(out, child.getTextContent());\n }\n }\n XmlUtil.writeCloseElement(out, name);\n out.print(\"\\n\");\n }\n }\n\n /**\n * Normalize a text string as per XPath normalize() function.\n * \n * @param s\n * The string to normalize.\n * @return The normalized text as character array.\n */\n public static char[] normalizeText(String s) {\n char[] ch = s.trim().toCharArray();\n if (ch.length == 0) {\n return ch;\n }\n return normalizeTrimmedText(ch);\n }\n\n private static char[] normalizeTrimmedText(char[] ch) {\n char[] ch2 = new char[ch.length];\n boolean inWhitespace = false;\n int j = 0;\n for (int i = 0; i < ch.length; i++) {\n char c = ch[i];\n boolean isWhitespace = Character.isWhitespace(c);\n if (isWhitespace && !inWhitespace) {\n ch2[j] = ' ';\n j++;\n inWhitespace = true;\n } else if (!isWhitespace) {\n ch2[j] = c;\n j++;\n inWhitespace = false;\n }\n }\n char[] ch3 = new char[j];\n for (int i = 0; i < j; i++) {\n ch3[i] = ch2[i];\n }\n return ch3;\n }\n\n public static String xmlEscape(String text) {\n StringBuilder sb = new StringBuilder(); \n char[] ch = text.toCharArray();\n for (int j = 0; j < ch.length; j++) {\n char c = ch[j];\n if (c == '&') {\n sb.append(\"&\");\n } else if (c == '\"') {\n sb.append(\""\");\n } else if (c == '<') {\n sb.append(\"<\");\n } else if (c == '>') {\n sb.append(\">\");\n } else if (c == '\\'') {\n sb.append(\"'\");\n } else {\n sb.append(c);\n }\n }\n return sb.toString();\n }\n}"
] | import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import junit.framework.TestCase;
import net.sf.saxon.dom.NodeOverNodeInfo;
import net.sf.saxon.om.NodeInfo;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;
import xdb.config.ModelConfigManagerTest;
import xdb.dom.XQueryEngine;
import xdb.dom.XmlParser;
import xdb.dom.impl.DocumentImpl;
import xdb.util.XmlUtil; | package xdb.dom;
public class XQueryEngineTest extends TestCase {
public XQueryEngineTest(String testName) {
super(testName);
}
public void testQuery() throws Exception {
String xml = "<x><a id='1'>x</a><a id='2'>y</a><a id='3'>z</a></x>";
Document doc = parse(xml);
Map<String, String> params = Collections.singletonMap("id", "2");
TestWriter writer = new TestWriter();
XQueryEngine.query(doc, "declare variable $id external; /x/a[@id=$id]", params, writer,
"xml");
assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<a id=\"2\">y</a>",
writer.toString());
}
public void testStaticFunctions() throws Exception {
String declaration = "declare namespace test=\"java:" + getClass().getName() + "\";";
String xml = "<x><a id='1'>x</a><a id='2'>y</a><a id='3'>z</a></x>";
Document doc = parse(xml);
Map<String, String> params = Collections.singletonMap("id", "2");
TestWriter writer = new TestWriter();
XQueryEngine.query(doc, declaration + " test:functionTest('X')", params, writer, "text");
assertEquals("x", writer.toString());
}
public static String functionTest(String value) {
return value.toLowerCase();
}
public void testStaticElementFunctions() throws Exception {
String declaration = "declare namespace test=\"java:" + getClass().getName() + "\";";
String xml = "<x test='The Test' />";
Document doc = parse(xml);
Map<String, String> params = Collections.singletonMap("id", "2");
TestWriter writer = new TestWriter();
XQueryEngine.query(doc, declaration + " test:elementFunctionTest(/x)", params, writer,
"text");
assertEquals("The Test", writer.toString());
}
public static String elementFunctionTest(Element element) {
if (element instanceof NodeOverNodeInfo) {
NodeOverNodeInfo wrapper = (NodeOverNodeInfo) element;
element = (Element) wrapper.getUnderlyingNodeInfo();
}
return element.getAttribute("test");
}
public void testStaticNodeReturnTest() throws Exception {
String declaration = "declare namespace test=\"java:" + getClass().getName() + "\";";
String xml = "<x><a/><a/><a/></x>";
Document doc = parse(xml);
Map<String, String> params = Collections.singletonMap("id", "2");
TestWriter writer = new TestWriter();
XQueryEngine.query(doc, declaration + " count(test:nodeReturnTest(/x))", params, writer,
"text");
assertEquals("3", writer.toString());
}
public static List<NodeInfo> nodeReturnTest(Element element) {
if (element instanceof NodeOverNodeInfo) {
NodeOverNodeInfo wrapper = (NodeOverNodeInfo) element;
element = (Element) wrapper.getUnderlyingNodeInfo();
}
List<Element> children = XmlUtil.getChildElements(element, "a");
List<NodeInfo> result = new ArrayList<NodeInfo>(children.size());
for (Element child : children) {
result.add((NodeInfo) child);
}
return result;
}
public void testExternalNamespaceResolver() throws Exception {
Document doc = parseFromFile("sample-data.xml");
if (!(doc instanceof DocumentImpl)) {
return;
}
DocumentImpl docImpl = (DocumentImpl) doc; | ModelConfigManagerTest.init(); | 0 |
Putnami/putnami-gradle-plugin | src/main/java/fr/putnami/gwt/gradle/task/GwtDevTask.java | [
"public class JavaAction implements Action<Task> {\n\n\tpublic static class ProcessLogger extends Thread {\n\t\tprivate InputStream stream;\n\t\tprivate LogLevel level;\n\t\tprivate boolean quit = false;\n\n\t\tpublic void setStream(InputStream stream) {\n\t\t\tthis.stream = stream;\n\t\t}\n\n\t\tpublic void setLevel(LogLevel level) {\n\t\t\tthis.level = level;\n\t\t}\n\n\t\t@Override\n\t\tpublic void run() {\n\t\t\ttry (BufferedReader input = new BufferedReader(new InputStreamReader(stream))) {\n\t\t\t\tString line = input.readLine();\n\t\t\t\twhile (!quit && line != null) {\n\t\t\t\t\tprintLine(line);\n\t\t\t\t\tline = input.readLine();\n\t\t\t\t}\n\t\t\t\tstream.close();\n\t\t\t} catch (IOException e) {\n\t\t\t\tthrow new RuntimeException(e);\n\t\t\t}\n\t\t}\n\n\t\tprotected void printLine(String line) {\n\t\t\tif (level == LogLevel.ERROR) {\n\t\t\t\tSystem.err.println(line);\n\t\t\t} else {\n\t\t\t\tSystem.out.println(line);\n\t\t\t}\n\t\t}\n\n\t\tpublic void quitLogger() {\n\t\t\tquit = true;\n\t\t}\n\t}\n\n\tprivate final String javaCommand;\n\n\tprivate Process process;\n\n\tprivate ProcessLogger errorLogger = new ProcessLogger();\n\tprivate ProcessLogger infoLogger = new ProcessLogger();\n\n\tpublic JavaAction(String javaCommand) {\n\t\tsuper();\n\t\tthis.javaCommand = javaCommand;\n\t}\n\n\t@Override\n\tpublic void execute(Task task) {\n\t\ttry {\n\t\t\ttask.getLogger().info(javaCommand);\n\t\t\tprocess = Runtime.getRuntime().exec(javaCommand);\n\n\t\t\tRuntime.getRuntime().addShutdownHook(new Thread() {\n\t\t\t\t@Override\n\t\t\t\tpublic void run() {\n\t\t\t\t\tkill();\n\t\t\t\t}\n\t\t\t});\n\t\t} catch (IOException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t\terrorLogger.setStream(process.getErrorStream());\n\t\terrorLogger.setLevel(LogLevel.ERROR);\n\t\terrorLogger.start();\n\t\tinfoLogger.setStream(process.getInputStream());\n\t\terrorLogger.setLevel(LogLevel.INFO);\n\t\tinfoLogger.start();\n\t}\n\n\tpublic void setErrorLogger(ProcessLogger errorLogger) {\n\t\tthis.errorLogger = errorLogger;\n\t}\n\n\tpublic void setInfoLogger(ProcessLogger infoLogger) {\n\t\tthis.infoLogger = infoLogger;\n\t}\n\n\tpublic void kill() {\n\t\terrorLogger.quitLogger();\n\t\tinfoLogger.quitLogger();\n\t\tprocess.destroy();\n\t\ttry {\n\t\t\tprocess.waitFor();\n\t\t} catch (InterruptedException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t}\n\n\tpublic void join() {\n\t\ttry {\n\t\t\tprocess.waitFor();\n\t\t} catch (InterruptedException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t}\n\n\tpublic int exitValue() {\n\t\treturn process.exitValue();\n\t}\n\n\tpublic boolean isAlive() {\n\t\ttry {\n\t\t\tprocess.exitValue();\n\t\t\treturn false;\n\t\t} catch (IllegalThreadStateException e) {\n\t\t\treturn true;\n\t\t}\n\t}\n\n}",
"public static class ProcessLogger extends Thread {\n\tprivate InputStream stream;\n\tprivate LogLevel level;\n\tprivate boolean quit = false;\n\n\tpublic void setStream(InputStream stream) {\n\t\tthis.stream = stream;\n\t}\n\n\tpublic void setLevel(LogLevel level) {\n\t\tthis.level = level;\n\t}\n\n\t@Override\n\tpublic void run() {\n\t\ttry (BufferedReader input = new BufferedReader(new InputStreamReader(stream))) {\n\t\t\tString line = input.readLine();\n\t\t\twhile (!quit && line != null) {\n\t\t\t\tprintLine(line);\n\t\t\t\tline = input.readLine();\n\t\t\t}\n\t\t\tstream.close();\n\t\t} catch (IOException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t}\n\n\tprotected void printLine(String line) {\n\t\tif (level == LogLevel.ERROR) {\n\t\t\tSystem.err.println(line);\n\t\t} else {\n\t\t\tSystem.out.println(line);\n\t\t}\n\t}\n\n\tpublic void quitLogger() {\n\t\tquit = true;\n\t}\n}",
"public class DevOption extends JavaOption {\n\n\t/**\n\t * The ip address of the code server.\n\t */\n\tprivate String bindAddress;\n\t/**\n\t * Stop compiling if a module has a Java file with a compile error, even if unused.\n\t */\n\tprivate Boolean noServer;\n\t/**\n\t * Shown all compile errors.\n\t */\n\tprivate Boolean strict;\n\t/**\n\t * Stop compiling if a module has a Java file with a compile error, even if unused.\n\t */\n\tprivate Boolean failOnError;\n\t/**\n\t * Precompile modules.\n\t */\n\tprivate Boolean precompile = false;\n\t/**\n\t * The port where the code server will run.\n\t */\n\tprivate Integer port = 9876;\n\t/**\n\t * EXPERIMENTAL: Don't implicitly depend on \"client\" and \"public\" when a module doesn't define any\n\t * dependencies.\n\t */\n\tprivate Boolean enforceStrictResources;\n\t/**\n\t * Compiles faster by reusing data from the previous compile.\n\t */\n\tprivate Boolean incremental;\n\t/**\n\t * Specifies Java source level.\n\t */\n\tprivate String sourceLevel = \"\";\n\t/**\n\t * The level of logging detail.\n\t */\n\tprivate LogLevel logLevel = LogLevel.ERROR;\n\t/**\n\t * Emit extra information allow chrome dev tools to display Java identifiers in many places\n\t * instead of JavaScript functions.\n\t */\n\tprivate MethodNameDisplayMode methodNameDisplayMode;\n\n\t/**\n\t * The root of the directory tree where the code server willwrite compiler output. If not\n\t * supplied, a temporary directorywill be used.\n\t */\n\tprivate File workDir;\n\t/**\n\t * Dev war folder.\n\t */\n\tprivate File war;\n\t/**\n\t * Launcher dir, folder where CodeServer will deploy the *.nocache.js .\n\t */\n\tprivate File launcherDir;\n\t/**\n\t * Specifies JsInterop mode, either NONE, JS, or CLOSURE (till GWT 2.7.x ).\n\t */\n\tprivate JsInteropMode jsInteropMode;\n\t/**\n\t * Generate and export JsInterop (since GWT 2.8).\n\t */\n\tprivate Boolean generateJsInteropExports;\n\n\t/**\n\t * GWT extra args, can be used to experiment arguments.\n\t */\n\tprivate final List<String> extraArgs = Lists.newArrayList();\n\n\tpublic String getBindAddress() {\n\t\treturn bindAddress;\n\t}\n\n\tpublic void setBindAddress(String bindAddress) {\n\t\tthis.bindAddress = bindAddress;\n\t}\n\n\tpublic Boolean getNoServer() {\n\t\treturn noServer;\n\t}\n\n\tpublic void setNoServer(Boolean noServer) {\n\t\tthis.noServer = noServer;\n\t}\n\n\tpublic void setNoServer(String noServer) {\n\t\tthis.noServer = Boolean.valueOf(noServer);\n\t}\n\n\tpublic Boolean getStrict() {\n\t\treturn strict;\n\t}\n\n\tpublic void setStrict(Boolean strict) {\n\t\tthis.strict = strict;\n\t}\n\n\tpublic void setStrict(String strict) {\n\t\tthis.strict = Boolean.valueOf(strict);\n\t}\n\n\tpublic Boolean getFailOnError() {\n\t\treturn failOnError;\n\t}\n\n\tpublic void setFailOnError(Boolean failOnError) {\n\t\tthis.failOnError = failOnError;\n\t}\n\n\tpublic void setFailOnError(String failOnError) {\n\t\tthis.failOnError = Boolean.valueOf(failOnError);\n\t}\n\n\tpublic Boolean getPrecompile() {\n\t\treturn precompile;\n\t}\n\n\tpublic void setPrecompile(Boolean precompile) {\n\t\tthis.precompile = precompile;\n\t}\n\n\tpublic void setPrecompile(String precompile) {\n\t\tthis.precompile = Boolean.valueOf(precompile);\n\t}\n\n\tpublic Integer getPort() {\n\t\treturn port;\n\t}\n\n\tpublic void setPort(Integer port) {\n\t\tthis.port = port;\n\t}\n\n\tpublic void setPort(String port) {\n\t\tthis.port = Integer.valueOf(port);\n\t}\n\n\tpublic Boolean getEnforceStrictResources() {\n\t\treturn enforceStrictResources;\n\t}\n\n\tpublic void setEnforceStrictResources(Boolean enforceStrictResources) {\n\t\tthis.enforceStrictResources = enforceStrictResources;\n\t}\n\n\tpublic void setEnforceStrictResources(String enforceStrictResources) {\n\t\tthis.enforceStrictResources = Boolean.valueOf(enforceStrictResources);\n\t}\n\n\tpublic Boolean getIncremental() {\n\t\treturn incremental;\n\t}\n\n\tpublic void setIncremental(Boolean incremental) {\n\t\tthis.incremental = incremental;\n\t}\n\n\tpublic void setIncremental(String incremental) {\n\t\tthis.incremental = Boolean.valueOf(incremental);\n\t}\n\n\tpublic String getSourceLevel() {\n\t\treturn sourceLevel;\n\t}\n\n\tpublic void setSourceLevel(String sourceLevel) {\n\t\tthis.sourceLevel = sourceLevel;\n\t}\n\n\tpublic LogLevel getLogLevel() {\n\t\treturn logLevel;\n\t}\n\n\tpublic void setLogLevel(String logLevel) {\n\t\tthis.logLevel = LogLevel.valueOf(logLevel);\n\t}\n\n\tpublic JsInteropMode getJsInteropMode() {\n\t\treturn jsInteropMode;\n\t}\n\n\tpublic void setJsInteropMode(String jsInteropMode) {\n\t\tthis.jsInteropMode = JsInteropMode.valueOf(jsInteropMode);\n\t}\n\n\tpublic Boolean getGenerateJsInteropExports() {\n\t\treturn generateJsInteropExports;\n\t}\n\n\tpublic void setGenerateJsInteropExports(Boolean generateJsInteropExports) {\n\t\tthis.generateJsInteropExports = generateJsInteropExports;\n\t}\n\n\tpublic List<String> getExtraArgs() {\n\t\treturn extraArgs;\n\t}\n\n\tpublic void setExtraArgs(String... extraArgs) {\n\t\tthis.extraArgs.addAll(Arrays.asList(extraArgs));\n\t}\n\n\tpublic MethodNameDisplayMode getMethodNameDisplayMode() {\n\t\treturn methodNameDisplayMode;\n\t}\n\n\tpublic void setMethodNameDisplayMode(String methodNameDisplayMode) {\n\t\tthis.methodNameDisplayMode = MethodNameDisplayMode.valueOf(methodNameDisplayMode);\n\t}\n\n\tpublic File getWorkDir() {\n\t\treturn workDir;\n\t}\n\n\tpublic void setWorkDir(String workDir) {\n\t\tthis.workDir = new File(workDir);\n\t}\n\n\tpublic File getWar() {\n\t\treturn war;\n\t}\n\n\tpublic void setWar(String war) {\n\t\tif (war != null) {\n\t\t\tthis.war = new File(war);\n\t\t}\n\t}\n\n\tpublic void setLauncherDir(String launcherDir) {\n\t\tthis.launcherDir = new File(launcherDir);\n\t}\n\n\tpublic File getLauncherDir() {\n\t\treturn launcherDir;\n\t}\n\n\tpublic void init(Project project) {\n\t\tfinal File buildDir = new File(project.getBuildDir(), \"putnami\");\n\n\t\tthis.war = new File(buildDir, \"warDev\");\n\t\tthis.workDir = new File(buildDir, \"work\");\n\t}\n}",
"public class PutnamiExtension {\n\tpublic static final String PWT_EXTENSION = \"putnami\";\n\n\tprivate String gwtVersion = \"2.7.0\";\n\tprivate boolean gwtServletLib = false;\n\tprivate boolean gwtElementalLib = false;\n\tprivate boolean googlePluginEclipse = false;\n\tprivate String jettyVersion = \"9.2.7.v20150116\";\n\t/**\n\t * Specifies Java source level.\n\t */\n\tprivate String sourceLevel;\n\n\t/**\n\t * GWT Module to compile.\n\t */\n\tprivate final List<String> module = Lists.newArrayList();\n\n\tprivate CompilerOption compile = new CompilerOption();\n\tprivate DevOption dev = new DevOption();\n\tprivate JettyOption jetty = new JettyOption();\n\n\tpublic String getGwtVersion() {\n\t\treturn gwtVersion;\n\t}\n\n\tpublic void setGwtVersion(String gwtVersion) {\n\t\tthis.gwtVersion = gwtVersion;\n\t}\n\n\tpublic String getJettyVersion() {\n\t\treturn jettyVersion;\n\t}\n\n\tpublic void setJettyVersion(String jettyVersion) {\n\t\tthis.jettyVersion = jettyVersion;\n\t}\n\n\tpublic boolean isGwtServletLib() {\n\t\treturn gwtServletLib;\n\t}\n\n\tpublic void setGwtServletLib(boolean gwtServletLib) {\n\t\tthis.gwtServletLib = gwtServletLib;\n\t}\n\n\tpublic boolean isGwtElementalLib() {\n\t\treturn gwtElementalLib;\n\t}\n\n\tpublic void setGwtElementalLib(boolean gwtElementalLib) {\n\t\tthis.gwtElementalLib = gwtElementalLib;\n\t}\n\n\tpublic boolean isGooglePluginEclipse() {\n\t\treturn googlePluginEclipse;\n\t}\n\n\tpublic void setGooglePluginEclipse(boolean googlePluginEclipse) {\n\t\tthis.googlePluginEclipse = googlePluginEclipse;\n\t}\n\n\tpublic DevOption getDev() {\n\t\treturn dev;\n\t}\n\n\tpublic void setDev(DevOption dev) {\n\t\tthis.dev = dev;\n\t}\n\n\tpublic PutnamiExtension dev(Closure<DevOption> c) {\n\t\tConfigureUtil.configure(c, dev);\n\t\treturn this;\n\t}\n\n\tpublic CompilerOption getCompile() {\n\t\treturn compile;\n\t}\n\n\tpublic void setCompile(CompilerOption compile) {\n\t\tthis.compile = compile;\n\t}\n\n\tpublic PutnamiExtension compile(Closure<CompilerOption> c) {\n\t\tConfigureUtil.configure(c, compile);\n\t\treturn this;\n\t}\n\n\tpublic JettyOption getJetty() {\n\t\treturn jetty;\n\t}\n\n\tpublic void setJetty(JettyOption jetty) {\n\t\tthis.jetty = jetty;\n\t}\n\n\tpublic PutnamiExtension jetty(Closure<JettyOption> c) {\n\t\tConfigureUtil.configure(c, jetty);\n\t\treturn this;\n\t}\n\n\tpublic String getSourceLevel() {\n\t\treturn sourceLevel;\n\t}\n\n\tpublic void setSourceLevel(String sourceLevel) {\n\t\tthis.sourceLevel = sourceLevel;\n\t}\n\n\tpublic List<String> getModule() {\n\t\treturn module;\n\t}\n\n\tpublic void module(String... modules) {\n\t\tthis.module.addAll(Arrays.asList(modules));\n\t}\n}",
"public class CodeServerBuilder extends JavaCommandBuilder {\n\n\tpublic CodeServerBuilder() {\n\t\tsetMainClass(\"com.google.gwt.dev.codeserver.CodeServer\");\n\t}\n\n\tpublic void configure(Project project, DevOption devOption, Collection<String> modules) {\n\t\tConfigurationContainer configs = project.getConfigurations();\n\t\tConfiguration sdmConf = configs.getByName(PwtLibPlugin.CONF_GWT_SDM);\n\n\t\tPutnamiExtension putnami = project.getExtensions().getByType(PutnamiExtension.class);\n\n\t\tSourceSet mainSourceSet = project.getConvention()\n\t\t\t.getPlugin(JavaPluginConvention.class).getSourceSets().getByName(SourceSet.MAIN_SOURCE_SET_NAME);\n\t\tFileCollection sources = project.files(mainSourceSet.getAllJava().getSrcDirs());\n\n\t\tconfigureJavaArgs(devOption);\n\n\t\taddClassPath(mainSourceSet.getOutput().getAsPath());\n\t\taddClassPath(mainSourceSet.getAllJava().getSrcDirs());\n\t\taddClassPath(mainSourceSet.getCompileClasspath().getAsPath());\n\t\taddClassPath(sdmConf.getAsPath());\n\n\t\taddSrc(sources);\n\t\taddSrc(listProjectDepsSrcDirs(project));\n\n\t\taddArg(\"-bindAddress\", devOption.getBindAddress());\n\t\taddArgIf(devOption.getFailOnError(), \"-failOnError\", \"-nofailOnError\");\n\t\taddArgIf(devOption.getPrecompile(), \"-precompile\", \"-noprecompile\");\n\t\taddArg(\"-port\", devOption.getPort());\n\t\taddArgIf(devOption.getStrict(), \"-strict\");\n\t\taddArgIf(devOption.getEnforceStrictResources(), \"-XenforceStrictResources \", \"-XnoenforceStrictResources\");\n\t\taddArg(\"-workDir\", ResourceUtils.ensureDir(devOption.getWorkDir()));\n\t\taddArgIf(devOption.getIncremental(), \"-incremental\", \"-noincremental\");\n\t\taddArg(\"-sourceLevel\", devOption.getSourceLevel());\n\t\tif (!putnami.getGwtVersion().startsWith(\"2.6\")) {\n\t\t\taddArg(\"-logLevel\", devOption.getLogLevel());\n\t\t}\n\t\taddArg(\"-XmethodNameDisplayMode\", devOption.getMethodNameDisplayMode());\n\t\taddArg(\"-XjsInteropMode\", devOption.getJsInteropMode());\n\t\taddArgIf(devOption.getGenerateJsInteropExports(), \"-generateJsInteropExports\");\n\n\t\tif (devOption.getExtraArgs() != null) {\n\t\t\tfor (String arg : devOption.getExtraArgs()) {\n\t\t\t\tif (arg != null && arg.length() > 0) {\n\t\t\t\t\taddArg(arg);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (String module : modules) {\n\t\t\taddArg(module);\n\t\t}\n\t}\n\n\tpublic JavaAction buildJavaAction() {\n\t\treturn new JavaAction(this.toString());\n\t}\n\n\tprivate Collection<File> listProjectDepsSrcDirs(Project project) {\n\t\tConfigurationContainer configs = project.getConfigurations();\n\t\tConfiguration compileConf = configs.getByName(JavaPlugin.COMPILE_CLASSPATH_CONFIGURATION_NAME);\n\t\tDependencySet depSet = compileConf.getAllDependencies();\n\n\t\tList<File> result = Lists.newArrayList();\n\t\tfor (Dependency dep : depSet) {\n\t\t\tif (dep instanceof ProjectDependency) {\n\t\t\t\tProject projectDependency = ((ProjectDependency) dep).getDependencyProject();\n\t\t\t\tif (projectDependency.getPlugins().hasPlugin(PwtLibPlugin.class)) {\n\t\t\t\t\tJavaPluginConvention javaConvention = projectDependency.getConvention().getPlugin(JavaPluginConvention.class);\n\t\t\t\t\tSourceSet mainSourceSet = javaConvention.getSourceSets().getByName(SourceSet.MAIN_SOURCE_SET_NAME);\n\n\t\t\t\t\tresult.addAll(mainSourceSet.getAllSource().getSrcDirs());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n\tprivate void addSrc(Iterable<File> sources) {\n\t\tfor (File srcDir : sources) {\n\t\t\tif (srcDir.isDirectory()) {\n\t\t\t\taddArg(\"-src\", srcDir);\n\t\t\t}\n\t\t}\n\t}\n\n}",
"public class JettyServerBuilder extends JavaCommandBuilder {\n\n\tpublic JettyServerBuilder() {\n\t\tsetMainClass(\"org.eclipse.jetty.runner.Runner\");\n\t}\n\n\tpublic void configure(Project project, JettyOption jettyOption, File jettyConf) {\n\t\tConfigurationContainer configs = project.getConfigurations();\n\n\t\tConfiguration runtimeConf = configs.getByName(WarPlugin.PROVIDED_RUNTIME_CONFIGURATION_NAME);\n\t\tConfiguration jettyClassPath = configs.getByName(PwtLibPlugin.CONF_JETTY);\n\n\t\tconfigureJavaArgs(jettyOption);\n\n\t\taddClassPath(jettyClassPath.getAsPath());\n\t\taddClassPath(runtimeConf.getAsPath());\n\n\t\tif (jettyOption.getLogRequestFile() != null) {\n\t\t\tResourceUtils.ensureDir(jettyOption.getLogRequestFile().getParentFile());\n\t\t\taddArg(\"--log\", jettyOption.getLogRequestFile());\n\t\t}\n\t\tif (jettyOption.getLogFile() != null) {\n\t\t\tResourceUtils.ensureDir(jettyOption.getLogFile().getParentFile());\n\t\t\taddArg(\"--out\", jettyOption.getLogFile());\n\t\t}\n\t\taddArg(\"--host\", jettyOption.getBindAddress());\n\t\taddArg(\"--port\", jettyOption.getPort());\n\t\taddArg(\"--stop-port\", jettyOption.getStopPort());\n\t\taddArg(\"--stop-key\", jettyOption.getStopKey());\n\n\t\taddArg(jettyConf.getAbsolutePath());\n\t}\n\n\tpublic JavaAction buildJavaAction() {\n\t\treturn new JavaAction(this.toString());\n\t}\n}",
"public final class ResourceUtils {\n\tprivate ResourceUtils() {\n\t}\n\n\tpublic static File ensureDir(File parent, String path) {\n\t\treturn ensureDir(new File(parent, path));\n\t}\n\n\tpublic static File ensureDir(File dir) {\n\t\tif (dir != null) {\n\t\t\tdir.mkdirs();\n\t\t}\n\t\treturn dir;\n\t}\n\n\tpublic static File copy(String resourcePath, File targetDir, String targetName)\n\t\tthrows IOException {\n\t\treturn copy(resourcePath, targetDir, targetName, null);\n\t}\n\n\tpublic static File copy(String resourcePath, File targetDir, String targetName, Map<String, String> model)\n\t\tthrows IOException {\n\t\treturn copy(resourcePath, new File(targetDir, targetName), model);\n\t}\n\n\tpublic static File copy(String resourcePath, File target, Map<String, String> model)\n\t\tthrows IOException {\n\n\t\tInputStream input = ResourceUtils.class.getResource(resourcePath).openStream();\n\t\tByteArrayOutputStream out = new ByteArrayOutputStream();\n\n\t\tByteStreams.copy(input, out);\n\n\t\tString template = new String(out.toByteArray());\n\t\t// Resources.toString(url, Charsets.UTF_8);\n\n\t\tif (model != null) {\n\t\t\tfor (Map.Entry<String, String> entry : model.entrySet()) {\n\t\t\t\ttemplate = template.replace(entry.getKey(), entry.getValue());\n\t\t\t}\n\t\t}\n\n\t\tif (target.getParentFile() != null) {\n\t\t\ttarget.getParentFile().mkdirs();\n\t\t}\n\t\tFileWriter writer = new FileWriter(target);\n\t\twriter.write(template);\n\t\twriter.close();\n\t\treturn target;\n\t}\n\n\tpublic static void copyDirectory(File source, File target) throws IOException {\n\t\tif (source == null) {\n\t\t\treturn;\n\t\t}\n\t\tif (!target.exists()) {\n\t\t\ttarget.mkdirs();\n\t\t}\n\n\t\tString[] files = source.list();\n\t\tif (files != null) {\n\t\t\tfor (String fileName : files) {\n\t\t\t\tFile s = new File(source, fileName);\n\t\t\t\tFile t = new File(target, fileName);\n\t\t\t\tif (s.isDirectory()) {\n\t\t\t\t\tcopyDirectory(s, t);\n\t\t\t\t} else {\n\t\t\t\t\tcopy(s, t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static void copy(File source, File target) throws IOException {\n\t\ttry (\n\t\t\tInputStream in = new FileInputStream(source);\n\t\t\tOutputStream out = new FileOutputStream(target)) {\n\t\t\tbyte[] buf = new byte[1024];\n\t\t\tint length;\n\t\t\twhile ((length = in.read(buf)) > 0) {\n\t\t\t\tout.write(buf, 0, length);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static boolean deleteDirectory(File directory) {\n\t\tif (directory.exists()) {\n\t\t\tFile[] files = directory.listFiles();\n\t\t\tif (null != files) {\n\t\t\t\tfor (File file : files) {\n\t\t\t\t\tif (file.isDirectory()) {\n\t\t\t\t\t\tdeleteDirectory(file);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfile.delete();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn directory.delete();\n\t}\n}"
] | import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import org.gradle.api.Project;
import org.gradle.api.internal.ConventionMapping;
import org.gradle.api.internal.IConventionAware;
import org.gradle.api.plugins.JavaPlugin;
import org.gradle.api.plugins.JavaPluginConvention;
import org.gradle.api.plugins.WarPluginConvention;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.SourceSet;
import org.gradle.api.tasks.TaskAction;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.Semaphore;
import fr.putnami.gwt.gradle.action.JavaAction;
import fr.putnami.gwt.gradle.action.JavaAction.ProcessLogger;
import fr.putnami.gwt.gradle.extension.DevOption;
import fr.putnami.gwt.gradle.extension.PutnamiExtension;
import fr.putnami.gwt.gradle.helper.CodeServerBuilder;
import fr.putnami.gwt.gradle.helper.JettyServerBuilder;
import fr.putnami.gwt.gradle.util.ResourceUtils; | /**
* This file is part of pwt.
*
* pwt is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser
* General Public License as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* pwt is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
* General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with pwt. If not,
* see <http://www.gnu.org/licenses/>.
*/
package fr.putnami.gwt.gradle.task;
public class GwtDevTask extends AbstractTask {
public static final String NAME = "gwtDev";
private final List<String> modules = Lists.newArrayList();
private File jettyConf;
public GwtDevTask() {
setDescription("Run DevMode");
dependsOn(JavaPlugin.COMPILE_JAVA_TASK_NAME, JavaPlugin.PROCESS_RESOURCES_TASK_NAME);
}
@TaskAction
public void exec() throws Exception {
PutnamiExtension putnami = getProject().getExtensions().getByType(PutnamiExtension.class);
DevOption sdmOption = putnami.getDev();
createWarExploded(sdmOption);
ResourceUtils.ensureDir(sdmOption.getWar());
ResourceUtils.ensureDir(sdmOption.getWorkDir());
jettyConf = new File(getProject().getBuildDir(), "putnami/conf/jetty-run-conf.xml");
Map<String, String> model = new ImmutableMap.Builder<String, String>()
.put("__WAR_FILE__", sdmOption.getWar().getAbsolutePath())
.build();
ResourceUtils.copy("/stub.jetty-conf.xml", jettyConf, model);
JavaAction sdm = execSdm();
if (sdm.isAlive()) {
JavaAction jetty = execJetty();
jetty.join();
}
}
private void createWarExploded(DevOption sdmOption) throws IOException {
WarPluginConvention warConvention = getProject().getConvention().getPlugin(WarPluginConvention.class);
JavaPluginConvention javaConvention = getProject().getConvention().getPlugin(JavaPluginConvention.class);
File warDir = sdmOption.getWar();
ResourceUtils.copyDirectory(warConvention.getWebAppDir(), warDir);
if (Boolean.TRUE.equals(sdmOption.getNoServer())) {
File webInfDir = ResourceUtils.ensureDir(new File(warDir, "WEB-INF"));
ResourceUtils.deleteDirectory(webInfDir);
} else {
SourceSet mainSourceSet = javaConvention.getSourceSets().getByName("main");
File classesDir = ResourceUtils.ensureDir(new File(warDir, "WEB-INF/classes"));
for (File file : mainSourceSet.getResources().getSrcDirs()) {
ResourceUtils.copyDirectory(file, classesDir);
}
for (File f: mainSourceSet.getOutput().getClassesDirs()) {
ResourceUtils.copyDirectory(f, classesDir);
}
for (File file : mainSourceSet.getOutput().getFiles()) {
if (file.exists() && file.isFile()) {
ResourceUtils.copy(file, new File(classesDir, file.getName()));
}
}
File libDir = ResourceUtils.ensureDir(new File(warDir, "WEB-INF/lib"));
for (File file : mainSourceSet.getRuntimeClasspath()) {
if (file.exists() && file.isFile()) {
ResourceUtils.copy(file, new File(libDir, file.getName()));
}
}
}
}
private JavaAction execJetty() {
PutnamiExtension putnami = getProject().getExtensions().getByType(PutnamiExtension.class);
JettyServerBuilder jettyBuilder = new JettyServerBuilder();
jettyBuilder.configure(getProject(), putnami.getJetty(), jettyConf);
JavaAction jetty = jettyBuilder.buildJavaAction();
jetty.execute(this);
return jetty;
}
private JavaAction execSdm() {
PutnamiExtension putnami = getProject().getExtensions().getByType(PutnamiExtension.class);
DevOption devOption = putnami.getDev();
if (!Strings.isNullOrEmpty(putnami.getSourceLevel()) &&
Strings.isNullOrEmpty(devOption.getSourceLevel())) {
devOption.setSourceLevel(putnami.getSourceLevel());
}
CodeServerBuilder sdmBuilder = new CodeServerBuilder();
if (!putnami.getGwtVersion().startsWith("2.6")) {
sdmBuilder.addArg("-launcherDir", devOption.getWar());
}
sdmBuilder.configure(getProject(), putnami.getDev(), getModules());
final JavaAction sdmAction = sdmBuilder.buildJavaAction();
final Semaphore lock = new Semaphore(1);
| sdmAction.setInfoLogger(new ProcessLogger() { | 1 |
binkley/binkley | yaml-compile/src/main/java/hm/binkley/annotation/processing/y/YModel.java | [
"public final class LoadedTemplate\n extends Loaded<Template> {\n LoadedTemplate(final String path, final Resource whence,\n final Template template) {\n super(path, whence, template);\n }\n\n @Override\n public String where() {\n return where;\n }\n}",
"public final class LoadedYaml\n extends Loaded<Map<String, Map<String, Map<String, Object>>>> {\n public final String path;\n\n LoadedYaml(final String pathPattern, final Resource whence,\n final Map<String, Map<String, Map<String, Object>>> yaml,\n final List<String> roots)\n throws IOException {\n super(pathPattern, whence, yaml);\n path = path(pathPattern, whence, roots);\n }\n\n @Override\n public String where() {\n return path;\n }\n}",
"public final class YamlGenerateMesseger\n extends SingleAnnotationMessager<YamlGenerate, YamlGenerateMesseger> {\n private final Resource ftl;\n private final Resource yml;\n // Block and template are exclusive\n private final Map.Entry<String, ? extends Map<String, ?>> block;\n private final Template template;\n\n static YamlGenerateMesseger from(final Messager messager,\n final Element element) {\n return new YamlGenerateMesseger(messager, element, null, null, null,\n null, null, null);\n }\n\n private YamlGenerateMesseger(final Messager messager,\n final Element element, final AnnotationMirror mirror,\n final AnnotationValue value, final Resource ftl,\n final Resource yml,\n final Map.Entry<String, ? extends Map<String, ?>> block,\n final Template template) {\n super(YamlGenerate.class, messager, element, mirror, value);\n this.ftl = ftl;\n this.yml = yml;\n this.block = block;\n this.template = template;\n }\n\n @Override\n public YamlGenerateMesseger withAnnotation(final AnnotationMirror mirror,\n final AnnotationValue value) {\n return new YamlGenerateMesseger(messager, element, mirror, value, ftl,\n yml, block, template);\n }\n\n public YamlGenerateMesseger withTemplate(final Resource ftl) {\n return new YamlGenerateMesseger(messager, element, mirror, value, ftl,\n yml, block, template);\n }\n\n public YamlGenerateMesseger withYaml(final Resource yml) {\n return new YamlGenerateMesseger(messager, element, mirror, value, ftl,\n yml, block, template);\n }\n\n public YamlGenerateMesseger atYamlBlock(\n final Map.Entry<String, ? extends Map<String, ?>> block) {\n return new YamlGenerateMesseger(messager, element, mirror, value, ftl,\n yml, block, template);\n }\n\n public YamlGenerateMesseger clearYamlBlock() {\n return new YamlGenerateMesseger(messager, element, mirror, value, ftl,\n yml, null, template);\n }\n\n public YamlGenerateMesseger atTemplateSource(final Template template) {\n return new YamlGenerateMesseger(messager, element, mirror, value, ftl,\n yml, block, template);\n }\n\n @Override\n protected MessageArgs messageArgs(final Exception cause,\n final String format, final Object... args) {\n final String xFormat;\n final Object[] xArgs;\n\n if (null == ftl && null == yml) {\n xFormat = format;\n xArgs = args;\n } else if (null == yml) {\n xFormat = \"(%s): \" + format;\n xArgs = new Object[1 + args.length];\n xArgs[0] = ftl.getDescription();\n arraycopy(args, 0, xArgs, 1, args.length);\n } else if (null == ftl) {\n throw new AssertionError(\"FTL cannot be null if YML is present\");\n } else if (null != block) {\n xFormat = \"%s(%s): \" + format + \" with block: %s\";\n xArgs = new Object[3 + args.length];\n xArgs[0] = yml.getDescription();\n xArgs[1] = ftl.getDescription();\n arraycopy(args, 0, xArgs, 2, args.length);\n final String yaml = YamlHelper.builder().\n build(inOneLine()).\n dump(singletonMap(block.getKey(), block.getValue()));\n // Chop trailing newline\n if (yaml.endsWith(\"\\n\"))\n xArgs[xArgs.length - 1] = yaml\n .substring(0, yaml.length() - 2);\n } else if (null != template && cause instanceof TemplateException) {\n xFormat = \"%s(%s): \" + format + \" at template source: %s\";\n xArgs = new Object[3 + args.length];\n xArgs[0] = yml.getDescription();\n xArgs[1] = ftl.getDescription();\n arraycopy(args, 0, xArgs, 2, args.length);\n final TemplateException e = (TemplateException) cause;\n xArgs[xArgs.length - 1] = template\n .getSource(e.getColumnNumber(), e.getLineNumber(),\n e.getEndColumnNumber(), e.getEndLineNumber());\n } else {\n xFormat = \"%s(%s): \" + format;\n xArgs = new Object[2 + args.length];\n xArgs[0] = yml.getDescription();\n xArgs[1] = ftl.getDescription();\n arraycopy(args, 0, xArgs, 2, args.length);\n }\n\n return super.messageArgs(cause, xFormat, xArgs);\n }\n}",
"@FunctionalInterface\npublic interface Listable<T> {\n /**\n * Provides a list view.\n *\n * @return the list view, never missing\n */\n @Nonnull\n List<T> list();\n}",
"public interface YamlHelper<T> {\n interface Implicit<T>\n extends YamlHelper<T> {\n /**\n * Gets the first characters for implicit matching.\n *\n * @see Yaml#addImplicitResolver(Tag, Pattern, String)\n */\n @Nonnull\n String firstChars();\n\n /**\n * Gets the pattern for implicit matching.\n *\n * @see Yaml#addImplicitResolver(Tag, Pattern, String)\n */\n @Nonnull\n Pattern match();\n }\n\n interface Explicit<T>\n extends YamlHelper<T> {}\n\n /**\n * Converter for YAML constructors map.\n *\n * @see Builder.BuilderConstructor#addImplicit(Class, Implicit)\n * @see Builder.BuilderConstructor#addExplicit(Tag, Explicit)\n */\n @Nonnull\n Function<String, T> valueOf();\n\n /** Creates a new {@code Builder}. */\n @Nonnull\n static Builder builder() { return new Builder(); }\n\n /** Creates a new {@code YamlHelper.Implicit} for enums. */\n @Nonnull\n @SafeVarargs\n static <E extends Enum<E>> Implicit<E> implicitFrom(\n @Nonnull final Class<E> type, final E... values) {\n final List<E> v = asList(values);\n final String firstChars = v.stream().\n map(Object::toString).\n map(s -> s.substring(0, 1)).\n collect(joining());\n final Pattern match = compile(v.stream().\n map(Object::toString).\n collect(joining(\"|\", \"^(\", \")$\")));\n final Function<String, E> valueOf = s -> Enum.valueOf(type, s);\n return implicitFrom(firstChars, match, valueOf);\n }\n\n /**\n * Creates a new {@code YamlHelper.Implicit} for one-arg-constructor\n * classes.\n */\n @Nonnull\n static <T, R> Implicit<R> implicitFrom(@Nonnull final String firstChars,\n @Nonnull final String regex,\n @Nonnull final Function<String, T> valueOfT,\n @Nonnull final Function<T, R> ctor, @Nonnull final String error) {\n final Pattern match = compile(regex);\n final Function<String, R> valueOf = s -> {\n final Matcher matcher = Util.matcher(s, match, error);\n return ctor.apply(valueOfT.apply(matcher.group(1)));\n };\n return implicitFrom(firstChars, match, valueOf);\n }\n\n /**\n * Creates a new {@code YamlHelper.Implicit} for two-arg-constructor\n * classes.\n */\n @Nonnull\n static <T, U, R> Implicit<R> implicitFrom(\n @Nonnull final String firstChars, @Nonnull final String regex,\n @Nonnull final Function<String, T> valueOfT,\n @Nonnull final Function<String, U> valueOfU,\n @Nonnull final BiFunction<T, U, R> ctor,\n @Nonnull final String error) {\n final Pattern match = compile(regex);\n final Function<String, R> valueOf = s -> {\n final Matcher matcher = Util.matcher(s, match, error);\n return ctor.apply(valueOfT.apply(matcher.group(1)),\n valueOfU.apply(matcher.group(2)));\n };\n return implicitFrom(firstChars, match, valueOf);\n }\n\n /** Creates a new {@code YamlHelper.Implicit}. */\n @Nonnull\n static <T> Implicit<T> implicitFrom(@Nonnull final String firstChars,\n @Nonnull final Pattern match,\n @Nonnull final Function<String, T> valueOf) {\n return new SimpleImplicit<>(firstChars, match, valueOf);\n }\n\n @Nonnull\n static <T> Explicit<T> explicitFrom(\n @Nonnull final Function<String, T> valueOf) {\n return () -> valueOf;\n }\n\n final class Builder {\n private final BuilderConstructor constructor\n = new BuilderConstructor();\n private final BuilderRepresenter representer\n = new BuilderRepresenter();\n private final Map<Tag, Implicit<?>> implicits = new LinkedHashMap<>();\n\n /** Supports Hollywood principal. */\n @Nonnull\n public Builder then(final Consumer<Builder> then) {\n then.accept(this);\n return this;\n }\n\n /**\n * Configures an implicit tag for {@code Yaml} defining the tag to be\n * the <var>type</var> simple name prefixed by an exclamation point.\n */\n @Nonnull\n public <T> Builder addImplicit(@Nonnull final Class<T> type,\n @Nonnull final Implicit<T> helper) {\n final Tag tag = tagFor(type);\n constructor.addImplicit(tag, helper);\n representer.addImplicit(type, tag);\n implicits.put(tag, helper);\n return this;\n }\n\n @Nonnull\n public <T> Builder addExplicit(@Nonnull final Class<T> type,\n @Nonnull final String tagText,\n @Nonnull final Explicit<T> helper) {\n final Tag tag = new Tag(\"!\" + tagText);\n constructor.addExplicit(tag, helper);\n representer.addExplicit(type, tag);\n return this;\n }\n\n /** Creates a new YAML instance with default dumper options. */\n public Yaml build() {\n final DumperOptions dumperOptions = new BuilderDumperOptions();\n final BuilderYaml yaml = new BuilderYaml(constructor, representer,\n dumperOptions);\n implicits.entrySet().stream().\n forEach(e -> yaml\n .addImplicitResolver(e.getKey(), e.getValue()));\n return yaml;\n }\n\n /**\n * Creates a new YAML instance using the given <var>options</var>. No\n * options are inherited from previous configuration.\n */\n public Yaml build(final Consumer<DumperOptions> options) {\n final DumperOptions dumperOptions = new BuilderDumperOptions();\n options.accept(dumperOptions);\n final BuilderYaml yaml = new BuilderYaml(constructor, representer,\n dumperOptions);\n implicits.entrySet().stream().\n forEach(e -> yaml\n .addImplicitResolver(e.getKey(), e.getValue()));\n return yaml;\n }\n\n /**\n * Convenience for {@link #build(Consumer)} to generate simple YAML in\n * a single line.\n */\n public static Consumer<DumperOptions> inOneLine() {\n return dumper -> {\n dumper.setDefaultFlowStyle(FLOW);\n dumper.setDefaultScalarStyle(PLAIN);\n dumper.setWidth(Integer.MAX_VALUE);\n };\n }\n\n private static Tag tagFor(final Class<?> type) {\n return new Tag(\"!\" + type.getSimpleName());\n }\n\n private static class BuilderConstructor\n extends Constructor {\n <T> void addImplicit(final Tag tag, final Implicit<T> implicit) {\n yamlConstructors.put(tag, new BuilderConstruct<>(implicit));\n }\n\n <T> void addExplicit(final Tag tag, final Explicit<T> explicit) {\n final BuilderConstruct<T> ctor = new BuilderConstruct<>(\n explicit);\n yamlConstructors.put(tag, ctor);\n yamlMultiConstructors.put(tag.getValue(), ctor);\n }\n\n private class BuilderConstruct<T>\n extends AbstractConstruct {\n private final Function<String, T> valueOf;\n\n BuilderConstruct(final YamlHelper<T> helper) {\n valueOf = helper.valueOf();\n }\n\n @Override\n public T construct(final Node node) {\n return valueOf.apply((String) constructScalar(\n (ScalarNode) node));\n }\n }\n }\n\n private static class BuilderRepresenter\n extends Representer {\n {\n setDefaultFlowStyle(BLOCK);\n setDefaultScalarStyle(PLAIN);\n setTimeZone(null); // null is UTC\n }\n\n void addImplicit(final Class<?> type, final Tag tag) {\n addClassTag(type, tag);\n representers.put(type,\n data -> representScalar(tag, data.toString()));\n }\n\n void addExplicit(final Class<?> type, final Tag tag) {\n addClassTag(type, tag);\n representers.put(type,\n data -> representScalar(tag, data.toString()));\n }\n }\n\n static class BuilderDumperOptions\n extends DumperOptions {\n {\n setDefaultFlowStyle(BLOCK);\n setDefaultScalarStyle(PLAIN);\n setLineBreak(UNIX);\n setTimeZone(null); // null is UTC\n }\n }\n\n private static class BuilderYaml\n extends Yaml {\n public BuilderYaml(final BuilderConstructor constructor,\n final BuilderRepresenter representer,\n final DumperOptions dumperOptions) {\n super(constructor, representer, dumperOptions);\n }\n\n public void addImplicitResolver(final Tag tag,\n final Implicit<?> helper) {\n addImplicitResolver(tag, helper.match(), helper.firstChars());\n }\n\n @Override\n public Iterable<Object> loadAll(final Reader yaml) {\n final List<Object> list = new ArrayList<>();\n for (final Object doc : super.loadAll(yaml))\n list.add(doc);\n return list;\n }\n\n @Override\n public Iterable<Object> loadAll(final String yaml) {\n final List<Object> list = new ArrayList<>();\n for (final Object doc : super.loadAll(yaml))\n list.add(doc);\n return list;\n }\n\n @Override\n public Iterable<Object> loadAll(final InputStream yaml) {\n final List<Object> list = new ArrayList<>();\n for (final Object doc : super.loadAll(yaml))\n list.add(doc);\n return list;\n }\n }\n }\n\n class SimpleImplicit<T>\n implements Implicit<T> {\n private final String firstChars;\n private final Pattern match;\n private final Function<String, T> valueOf;\n\n public SimpleImplicit(final String firstChars, final Pattern match,\n final Function<String, T> valueOf) {\n this.firstChars = firstChars;\n this.match = match;\n this.valueOf = valueOf;\n }\n\n @Nonnull\n @Override\n public String firstChars() { return firstChars; }\n\n @Nonnull\n @Override\n public Pattern match() { return match; }\n\n @Nonnull\n @Override\n public Function<String, T> valueOf() { return valueOf; }\n }\n\n class Util {\n private static Matcher matcher(final String s, final Pattern match,\n final String error) {\n final Matcher matcher = match.matcher(s);\n if (!matcher.matches())\n throw new IllegalArgumentException(format(error, s));\n return matcher;\n }\n }\n}"
] | import hm.binkley.annotation.processing.LoadedTemplate;
import hm.binkley.annotation.processing.LoadedYaml;
import hm.binkley.annotation.processing.YamlGenerateMesseger;
import hm.binkley.util.Listable;
import hm.binkley.util.YamlHelper;
import org.yaml.snakeyaml.Yaml;
import javax.annotation.Nonnull;
import javax.lang.model.element.Element;
import javax.lang.model.element.Name;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.function.Consumer;
import java.util.function.Function;
import static java.util.Collections.emptyMap;
import static java.util.Collections.unmodifiableList;
import static java.util.stream.Collectors.toList;
import static org.yaml.snakeyaml.DumperOptions.FlowStyle.FLOW;
import static org.yaml.snakeyaml.DumperOptions.ScalarStyle.PLAIN; | package hm.binkley.annotation.processing.y;
/**
* Represents YAML class/enum definitions immutably and accessible from
* FreeMarker. Typical: <pre>
* Foo:
* .meta:
* doc: I am the one and only Foo!
* bar:
* doc: I am bar
* value: 0</pre>
*
* @author <a href="mailto:binkley@alumni.rice.edu">B. K. Oxley (binkley)</a>
* @todo Documentation
*/
public final class YModel
implements Listable<YType> {
// TODO: Some less gross place for this global
public static final Map<ZisZuper, List<YMethod>> methods
= new LinkedHashMap<>();
private final String generator;
@Nonnull | private final Yaml yaml = YamlHelper.builder().build(dumper -> { | 4 |
xpush/lib-xpush-android | sample/src/main/java/io/xpush/sampleChat/fragments/ProfileFragment.java | [
"public class Constants {\n public static final int REQUEST_SIGNUP = 100;\n\n public static final int REQUEST_EDIT_IMAGE = 111;\n public static final int REQUEST_EDIT_NICKNAME = 112;\n public static final int REQUEST_EDIT_STATUS_MESSAGE = 113;\n\n public static final int REQUEST_INVITE_USER = 201;\n\n public static final int REQUEST_IMAGE_SELECT = 210;\n public static final int REQUEST_IMAGE_CAPTURE = 211;\n\n public static final String CRASH_TEXT = \"oooops ! I crashed, but a report has been sent to my developer to help fix the issue !\";\n public static final MediaType MEDIA_TYPE_PNG = MediaType.parse(\"image/png\");\n}",
"public interface CallbackEvent {\n public void call(Object... args);\n}",
"public class XPushCore {\n\n private static final int NETWORK_WIFI = 1;\n private static final int NETWORK_MOBILE = 2;\n private static final int NETWORK_NOT_AVAILABLE = 0;\n\n private static XPushSession mXpushSession;\n\n private static final String TAG = XPushCore.class.getSimpleName();\n\n public static XPushCore sInstance;\n\n private static String mHostname;\n private static String mAppId;\n private static String mDeviceId;\n private static Context baseContext;\n\n private static Socket mGlobalSocket;\n\n\n private HashMap<String, Emitter.Listener> mEvents;\n\n private static final AtomicBoolean mGlobalSocketConnected = new AtomicBoolean();\n private static final AtomicBoolean mConnecting = new AtomicBoolean();\n\n private static CountDownLatch latch = new CountDownLatch(2);\n\n public static void initialize(Context context){\n if( sInstance == null ){\n sInstance = new XPushCore(context);\n sInstance.init();\n }\n }\n\n public static XPushCore getInstance(){\n\n if( sInstance == null ){\n sInstance = new XPushCore();\n sInstance.init();\n }\n\n return sInstance;\n }\n\n public XPushCore(){\n }\n\n public XPushCore(Context context){\n baseContext = context;\n }\n\n\n private void init(){\n if( getBaseContext() != null ) {\n mXpushSession = restoreXpushSession();\n mHostname = getBaseContext().getString(R.string.host_name);\n mAppId = getBaseContext().getString(R.string.app_id);\n mDeviceId = getBaseContext().getString(R.string.device_id);\n }\n }\n\n public static String getHostname(){\n return mHostname;\n }\n\n public static String getAppId(){\n return mAppId;\n }\n\n public static void setBaseContext(Context context){\n baseContext = context;\n XPushCore.getInstance().init();\n }\n\n public static Context getBaseContext(){\n if( baseContext == null){\n Log.w(TAG, \"!!!!! baseContext is null !!!!!\");\n baseContext = ApplicationController.getInstance();\n }\n return baseContext;\n }\n\n public static void setGlobalSocket(Socket socket){\n mGlobalSocket = socket;\n latch.countDown();\n }\n\n public static void setGlobalSocketConnected(){\n mGlobalSocketConnected.getAndSet(true);\n }\n\n private Socket getClient() {\n\n try {\n if( !mGlobalSocketConnected.get() ) {\n\n // create three threads passing a CountDownLatch\n Thread T1 = new Thread(){\n public void run() {\n Log.d(TAG, \"--- connect --- \");\n connect();\n }\n };\n\n Thread T2 = new Thread(){\n public void run() {\n try {\n Thread.sleep(10);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n latch.countDown();\n }\n };\n\n T1.start();\n T2.start();\n\n try {\n latch.await(6, TimeUnit.SECONDS);\n } catch(InterruptedException ie) {\n ie.printStackTrace();\n }\n }\n } catch (Exception e) {\n // Happens if someone interrupts your thread.\n e.printStackTrace();\n }\n\n if( mGlobalSocket == null ){\n Log.d(TAG, \"null null null\");\n }\n\n return mGlobalSocket;\n }\n\n public static boolean isGlobalConnected(){\n return mGlobalSocketConnected.get();\n }\n\n /**\n *\n * Auth start\n *\n *\n */\n public static void register(String id, String password, String name, final CallbackEvent callbackEvent){\n\n getInstance();\n\n final Map<String,String> params = new HashMap<String, String>();\n\n if( name != null ) {\n\n JSONObject data = new JSONObject();\n try {\n data.put(\"NM\", name);\n } catch (JSONException e) {\n e.printStackTrace();\n }\n params.put(\"DT\", data.toString());\n }\n\n params.put(\"A\", mAppId);\n params.put(\"U\", id);\n params.put(\"PW\", password);\n params.put(\"D\", mDeviceId);\n SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());\n if( null != pref.getString(\"REGISTERED_NOTIFICATION_ID\", null)){\n params.put(\"N\", pref.getString(\"REGISTERED_NOTIFICATION_ID\", null) );\n }\n String url = mHostname+\"/user/register\";\n\n StringRequest request = new StringRequest(url, params,\n new Response.Listener<JSONObject>() {\n @Override\n public void onResponse(JSONObject response) {\n Log.d(TAG, response.toString());\n try {\n if( \"ok\".equalsIgnoreCase(response.getString(\"status\")) ){\n callbackEvent.call();\n } else {\n if( response.has(\"message\") ){\n callbackEvent.call(response.getString(\"status\"), response.getString(\"message\") );\n } else {\n callbackEvent.call(response.getString(\"status\"));\n }\n }\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n },\n new Response.ErrorListener() {\n @Override\n public void onErrorResponse(VolleyError error) {\n error.printStackTrace();\n callbackEvent.call( error.getMessage() );\n }\n }\n );\n\n RequestQueue queue = Volley.newRequestQueue(getBaseContext());\n queue.add(request);\n }\n\n /**\n *\n * Auth start\n *\n *\n */\n public static void login(String id, String password, final CallbackEvent callbackEvent){\n\n getInstance();\n\n final Map<String,String> params = new HashMap<String, String>();\n\n params.put(\"A\", mAppId);\n params.put(\"U\", id);\n params.put(\"PW\", password);\n params.put(\"D\", mDeviceId);\n SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());\n if( null != pref.getString(\"REGISTERED_NOTIFICATION_ID\", null)){\n params.put(\"N\", pref.getString(\"REGISTERED_NOTIFICATION_ID\", null) );\n }\n\n String url = mHostname+\"/auth\";\n\n LoginRequest request = new LoginRequest(getBaseContext(), url, params,\n new Response.Listener<JSONObject>() {\n @Override\n public void onResponse(JSONObject response) {\n try {\n if( \"ok\".equalsIgnoreCase(response.getString(\"status\")) ){\n callbackEvent.call();\n } else {\n if( response.has(\"message\") ){\n callbackEvent.call(response.getString(\"status\"), response.getString(\"message\") );\n } else {\n callbackEvent.call(response.getString(\"status\"));\n }\n }\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n },\n new Response.ErrorListener() {\n @Override\n public void onErrorResponse(VolleyError error) {\n error.printStackTrace();\n callbackEvent.call( \"SERVER-ERROR\", error.getMessage() );\n }\n }\n );\n\n RequestQueue queue = Volley.newRequestQueue(getBaseContext());\n queue.add(request);\n }\n\n /**\n *\n * logout\n *\n *\n */\n public static void logout(){\n getInstance();\n mXpushSession = null;\n XPushService.actionStop(baseContext);\n sInstance = null;\n\n SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());\n SharedPreferences.Editor editor = pref.edit();\n editor.remove(\"XPUSH_SESSION\");\n editor.commit();\n }\n\n /**\n *\n * Add device start\n *\n *\n */\n public static void addDevice(String id, String password, final CallbackEvent callbackEvent){\n\n getInstance();\n\n final Map<String,String> params = new HashMap<String, String>();\n\n params.put(\"A\", mAppId);\n params.put(\"U\", id);\n params.put(\"PW\", password);\n params.put(\"D\", mDeviceId);\n\n String url = mHostname+\"/device/add\";\n\n LoginRequest request = new LoginRequest(getBaseContext(), url, params,\n new Response.Listener<JSONObject>() {\n @Override\n public void onResponse(JSONObject response) {\n try {\n if( \"ok\".equalsIgnoreCase(response.getString(\"status\")) ){\n callbackEvent.call();\n } else {\n if( response.has(\"message\") ){\n callbackEvent.call(response.getString(\"status\"), response.getString(\"message\") );\n } else {\n callbackEvent.call(response.getString(\"status\"));\n }\n }\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n },\n new Response.ErrorListener() {\n @Override\n public void onErrorResponse(VolleyError error) {\n error.printStackTrace();\n callbackEvent.call(\"SERVER-ERROR\", error.getMessage());\n }\n }\n );\n\n RequestQueue queue = Volley.newRequestQueue(getBaseContext());\n queue.add(request);\n }\n\n public static void updateToken(final CallbackEvent callbackEvent){\n updateUser(null, callbackEvent);\n }\n\n public static void updateUser(final JSONObject mJsonUserData, final CallbackEvent callbackEvent){\n if( mXpushSession == null ){\n return;\n }\n\n getInstance();\n\n final Map<String,String> params = new HashMap<String, String>();\n\n params.put(\"A\", mAppId);\n params.put(\"U\", mXpushSession.getId());\n params.put(\"PW\", mXpushSession.getPassword());\n params.put(\"D\", mXpushSession.getDeviceId());\n\n if( mJsonUserData != null ) {\n params.put(\"DT\", mJsonUserData.toString());\n }\n\n SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());\n if( null != pref.getString(\"REGISTERED_NOTIFICATION_ID\", null)){\n params.put(\"N\", pref.getString(\"REGISTERED_NOTIFICATION_ID\", null) );\n }\n\n String url = getBaseContext().getString(R.string.host_name)+\"/user/update\";\n\n StringRequest request = new StringRequest(url, params,\n new Response.Listener<JSONObject>() {\n @Override\n public void onResponse(JSONObject response) {\n Log.d(TAG, \"Update user success ======================\");\n Log.d(TAG, response.toString());\n try {\n if( \"ok\".equalsIgnoreCase(response.getString(\"status\")) ){\n Log.d(TAG, response.getString(\"status\"));\n\n if( mJsonUserData != null ) {\n if (mJsonUserData.has(\"I\")) {\n mXpushSession.setImage(mJsonUserData.getString(\"I\"));\n }\n if (mJsonUserData.has(\"NM\")) {\n mXpushSession.setName(mJsonUserData.getString(\"NM\"));\n }\n if (mJsonUserData.has(\"MG\")) {\n mXpushSession.setMessage(mJsonUserData.getString(\"MG\"));\n }\n }\n\n if( params.containsKey(\"N\")) {\n mXpushSession.setNotiId(params.get(\"N\"));\n }\n\n // SessionData Update\n SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(baseContext);\n SharedPreferences.Editor editor = pref.edit();\n editor.putString(\"XPUSH_SESSION\", mXpushSession.toJSON().toString());\n editor.commit();\n\n if( mJsonUserData != null ) {\n callbackEvent.call(mJsonUserData);\n } else {\n callbackEvent.call(response);\n }\n }\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n },\n new Response.ErrorListener() {\n @Override\n public void onErrorResponse(VolleyError error) {\n Log.d(TAG, \"Update user error ======================\");\n error.printStackTrace();\n }\n }\n );\n\n RequestQueue queue = Volley.newRequestQueue(getBaseContext());\n queue.add(request);\n }\n\n /**\n *\n * Session Start\n *\n */\n public static XPushSession restoreXpushSession(){\n getInstance();\n if( mXpushSession == null ){\n SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());\n final String sessionStr = pref.getString(\"XPUSH_SESSION\", \"\");\n if( !\"\".equals( sessionStr ) ){\n try {\n mXpushSession = new XPushSession( new JSONObject( sessionStr ) );\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n }\n\n return mXpushSession;\n }\n\n public static boolean isLogined(){\n getInstance();\n if( restoreXpushSession() != null ){\n return true;\n } else {\n return false;\n }\n }\n\n public static XPushSession getXpushSession(){\n getInstance();\n if( mXpushSession == null ){\n restoreXpushSession();\n }\n\n return mXpushSession;\n }\n\n /**\n *\n * Channel start\n *\n *\n */\n\n public static void createChannel(final XPushChannel xpushChannel, final CallbackEvent callbackEvent){\n\n JSONArray userArray = new JSONArray();\n for( String userId : xpushChannel.getUsers() ){\n userArray.put(userId);\n }\n final String cid = xpushChannel.getId() != null ? xpushChannel.getId() : XPushUtils.generateChannelId(xpushChannel.getUsers());\n xpushChannel.setId( cid );\n\n JSONObject jsonObject = new JSONObject();\n try {\n jsonObject.put(\"C\", cid);\n jsonObject.put(\"U\", userArray);\n\n } catch (JSONException e) {\n e.printStackTrace();\n }\n\n if ( mGlobalSocket == null || !mGlobalSocket.connected() ){\n Log.d(TAG, \"Not connected\");\n return;\n }\n\n getInstance().getClient().emit(\"channel.create\", jsonObject, new Ack() {\n @Override\n public void call(Object... args) {\n JSONObject response = (JSONObject) args[0];\n\n if (response.has(\"status\")) {\n try {\n Log.d(TAG, response.getString(\"status\"));\n if (\"ok\".equalsIgnoreCase(response.getString(\"status\")) || \"WARN-EXISTED\".equals(response.getString(\"status\"))\n // duplicate\n || (\"ERR-INTERNAL\".equals(response.getString(\"status\"))) && response.get(\"message\").toString().indexOf(\"E11000\") > -1) {\n\n getChannel(cid, callbackEvent);\n }\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n }\n });\n }\n\n\n public static void getChannel(final String channelId, final CallbackEvent callbackEvent){\n getChannel(getBaseContext(), channelId, callbackEvent);\n }\n\n public static void getChannel(Context context, final String channelId, final CallbackEvent callbackEvent){\n getInstance();\n String url = null;\n try {\n url = mHostname + \"/node/\"+ getInstance().getAppId()+\"/\"+ URLEncoder.encode(channelId, \"UTF-8\");\n } catch (UnsupportedEncodingException e) {\n e.printStackTrace();\n }\n\n StringRequest request = new StringRequest(url,\n new Response.Listener<JSONObject>() {\n @Override\n public void onResponse(JSONObject response) {\n try {\n ChannelCore result = null;\n if( \"ok\".equalsIgnoreCase(response.getString(\"status\")) ){\n JSONObject serverInfo = response.getJSONObject(\"result\").getJSONObject(\"server\");\n result = new ChannelCore(channelId, serverInfo.getString(\"url\"), serverInfo.getString(\"name\") );\n }\n\n callbackEvent.call( result );\n } catch (JSONException e) {\n e.printStackTrace();\n callbackEvent.call();\n }\n }\n },\n new Response.ErrorListener() {\n @Override\n public void onErrorResponse(VolleyError error) {\n error.printStackTrace();\n callbackEvent.call(error.getMessage());\n }\n }\n );\n\n RequestQueue queue = Volley.newRequestQueue(context);\n queue.add(request);\n }\n\n public static void storeChannel(XPushChannel channel){\n getInstance();\n ContentValues values = new ContentValues();\n values.put(ChannelTable.KEY_ID, channel.getId());\n values.put(ChannelTable.KEY_NAME, channel.getName());\n values.put(ChannelTable.KEY_IMAGE, channel.getImage());\n values.put(ChannelTable.KEY_MESSAGE, channel.getMessage());\n values.put(ChannelTable.KEY_UPDATED, System.currentTimeMillis());\n\n values.put(XpushContentProvider.SQL_INSERT_OR_REPLACE, true);\n getBaseContext().getContentResolver().insert(XpushContentProvider.CHANNEL_CONTENT_URI, values);\n }\n\n /**\n *\n * Group Start\n *\n */\n public static void getFriends(final CallbackEvent callbackEvent) {\n\n\n JSONObject jsonObject = new JSONObject();\n\n try {\n jsonObject.put(\"GR\", mXpushSession.getId());\n } catch (JSONException e) {\n e.printStackTrace();\n }\n\n try {\n getInstance().getClient().emit(\"group.list\", jsonObject, new Ack() {\n @Override\n public void call(Object... args) {\n JSONObject response = (JSONObject) args[0];\n\n Log.d(TAG, response.toString());\n if (response.has(\"result\")) {\n try {\n JSONArray result = (JSONArray) response.getJSONArray(\"result\");\n callbackEvent.call(result);\n\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n }\n });\n } catch ( Exception ee ){\n ee.printStackTrace();\n }\n }\n\n public static void storeFriends(final Context mContext, final JSONArray result) {\n getInstance();\n try {\n List<ContentValues> valuesToInsert = new ArrayList<ContentValues>();\n\n for (int inx = 0; inx < result.length(); inx++) {\n JSONObject json = (JSONObject) result.get(inx);\n\n ContentValues contentValues = new ContentValues();\n contentValues.put(UserTable.KEY_ID, json.getString(\"U\"));\n\n if (json.has(\"DT\") && !json.isNull(\"DT\")) {\n Object obj = json.get(\"DT\");\n JSONObject data = null;\n if (obj instanceof JSONObject) {\n data = (JSONObject) obj;\n } else if (obj instanceof String) {\n data = new JSONObject((String) obj);\n }\n\n if (data.has(\"NM\")) {\n contentValues.put(UserTable.KEY_NAME, data.getString(\"NM\"));\n }\n if (data.has(\"MG\")) {\n contentValues.put(UserTable.KEY_MESSAGE, data.getString(\"MG\"));\n }\n if (data.has(\"I\")) {\n contentValues.put(UserTable.KEY_IMAGE, data.getString(\"I\"));\n }\n } else {\n contentValues.put(UserTable.KEY_NAME, json.getString(\"U\"));\n }\n\n contentValues.put(XpushContentProvider.SQL_INSERT_OR_REPLACE, true);\n valuesToInsert.add(contentValues);\n }\n\n\n mContext.getContentResolver().bulkInsert(XpushContentProvider.USER_CONTENT_URI, valuesToInsert.toArray(new ContentValues[0]));\n\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n\n public static void addFriend(final Context mContext, final XPushUser user, final CallbackEvent callbackEvent) {\n\n JSONObject jsonObject = new JSONObject();\n JSONArray array = new JSONArray();\n\n try {\n array.put( user.getId() );\n\n jsonObject.put(\"GR\", XPushCore.getXpushSession().getId() );\n jsonObject.put(\"U\", array);\n } catch (JSONException e) {\n e.printStackTrace();\n }\n\n getInstance().getClient().emit(\"group.add\", jsonObject, new Ack() {\n @Override\n public void call(Object... args) {\n JSONObject response = (JSONObject) args[0];\n Log.d(TAG, response.toString());\n try {\n if (\"ok\".equalsIgnoreCase(response.getString(\"status\"))) {\n\n ContentValues contentValues = new ContentValues();\n contentValues.put(UserTable.KEY_ID, user.getId());\n contentValues.put(UserTable.KEY_NAME, user.getName());\n contentValues.put(UserTable.KEY_MESSAGE, user.getMessage());\n contentValues.put(UserTable.KEY_IMAGE, user.getImage());\n\n contentValues.put(XpushContentProvider.SQL_INSERT_OR_REPLACE, true);\n mContext.getContentResolver().insert(XpushContentProvider.USER_CONTENT_URI, contentValues);\n\n callbackEvent.call();\n }\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n });\n }\n\n public static void searchUser(final Context context, String searchKey, final CallbackEvent callbackEvent){\n searchUser(context, searchKey, 1, 50, callbackEvent);\n }\n\n public static void searchUser(final Context context, String searchKey, int pageNum, int pageSize, final CallbackEvent callbackEvent){\n\n getInstance();\n\n JSONObject options = new JSONObject();\n\n try {\n options.put(\"pageNum\", pageNum);\n options.put(\"pageSize\", pageSize);\n } catch (JSONException e) {\n e.printStackTrace();\n }\n\n final Map<String,String> params = new HashMap<String, String>();\n params.put(\"A\", mAppId);\n params.put(\"K\", searchKey);\n params.put(\"option\", options.toString());\n\n String url = mHostname+\"/user/search\";\n\n StringRequest request = new StringRequest(url, params,\n new Response.Listener<JSONObject>() {\n @Override\n public void onResponse(JSONObject response) {\n try {\n Log.d(TAG, \"====== search user response ====== \" + response.toString() );\n if( \"ok\".equalsIgnoreCase(response.getString(\"status\")) ){\n JSONArray result = (JSONArray) response.getJSONObject(\"result\").getJSONArray(\"users\");\n\n ArrayList<XPushUser> users = new ArrayList<XPushUser>();\n\n for (int inx = 0; inx < result.length(); inx++) {\n JSONObject json = (JSONObject) result.get(inx);\n Log.d(TAG, json.toString());\n\n XPushUser xpushUser = new XPushUser();\n\n xpushUser.setId(json.getString(\"U\"));\n\n if (json.has(\"DT\") && !json.isNull(\"DT\")) {\n Object obj = json.get(\"DT\");\n JSONObject data = null;\n if (obj instanceof JSONObject) {\n data = (JSONObject) obj;\n } else if (obj instanceof String) {\n data = new JSONObject((String) obj);\n }\n\n if (data.has(\"NM\")) {\n xpushUser.setName(data.getString(\"NM\"));\n } else {\n xpushUser.setName(json.getString(\"U\"));\n }\n if (data.has(\"MG\")) {\n xpushUser.setMessage(data.getString(\"MG\"));\n }\n if (data.has(\"I\")) {\n xpushUser.setImage(data.getString(\"I\"));\n }\n } else {\n xpushUser.setName(json.getString(\"U\"));\n }\n\n users.add(xpushUser);\n }\n\n callbackEvent.call(users);\n }\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n },\n new Response.ErrorListener() {\n @Override\n public void onErrorResponse(VolleyError error) {\n error.printStackTrace();\n callbackEvent.call(error.getMessage());\n }\n }\n );\n\n RequestQueue queue = Volley.newRequestQueue(context);\n queue.add(request);\n }\n\n public static String[] uploadImage(Uri uri){\n\n getInstance();\n\n String[] results = new String[3];\n\n String downloadUrl = null;\n String url = mXpushSession.getServerUrl()+\"/upload\";\n JSONObject userData = new JSONObject();\n\n try {\n userData.put( \"U\", mXpushSession.getId() );\n userData.put( \"D\", mDeviceId );\n } catch (JSONException e) {\n e.printStackTrace();\n }\n\n String realPath = ContentUtils.getRealPath(getBaseContext(), uri);\n File aFile = new File(realPath);\n\n BitmapFactory.Options options = new BitmapFactory.Options();\n options.inJustDecodeBounds = true;\n BitmapFactory.decodeFile(realPath, options);\n\n int imageWidth = options.outWidth;\n int imageHeight = options.outHeight;\n\n RequestBody requestBody = new MultipartBuilder()\n .type(MultipartBuilder.FORM)\n .addFormDataPart(\"file\", aFile.getName(), RequestBody.create(Constants.MEDIA_TYPE_PNG, aFile)).build();\n\n\n String appId = XPushCore.getAppId();\n\n Request request = new Request.Builder()\n .url(url)\n .addHeader(\"XP-A\", appId )\n .addHeader(\"XP-C\", getXpushSession().getId() +\"^\"+ appId)\n .addHeader(\"XP-U\", userData.toString() )\n .addHeader(\"XP-FU-org\", aFile.getName())\n .addHeader(\"XP-FU-nm\", aFile.getName().substring(0, aFile.getName().lastIndexOf(\".\") ) )\n .addHeader(\"XP-FU-tp\", \"image\")\n .post(requestBody)\n .build();\n\n OkHttpClient client = new OkHttpClient();\n\n com.squareup.okhttp.Response response = null;\n try {\n response = client.newCall(request).execute();\n if (!response.isSuccessful()) {\n throw new IOException(\"Unexpected code \" + response);\n }\n\n JSONObject res = new JSONObject( response.body().string() );\n Log.d(TAG, res.toString() );\n\n if( \"ok\".equals(res.getString(\"status\")) ) {\n JSONObject result = res.getJSONObject(\"result\");\n\n String channel = result.getString(\"channel\");\n String tname = result.getString(\"name\");\n\n downloadUrl = mXpushSession.getServerUrl() + \"/download/\" + appId + \"/\" + channel + \"/\" + mXpushSession.getId() + \"/\" + tname;\n\n Log.d(TAG, downloadUrl );\n }\n\n\n results[0] = downloadUrl;\n results[1] = String.valueOf(imageWidth);\n results[2] = String.valueOf(imageHeight);\n\n } catch (IOException e) {\n e.printStackTrace();\n } catch (JSONException e) {\n e.printStackTrace();\n }\n\n return results;\n }\n\n public synchronized void connect() {\n\n if( getOnlineType() == NETWORK_NOT_AVAILABLE ){\n Log.d(TAG, \"Network is not available\");\n return;\n }\n\n if( mConnecting.get() ){\n Log.d(TAG, \"Tring connect\");\n return;\n }\n\n mConnecting.set(true);\n\n // fetch the device ID from the preferences.\n String appId = getBaseContext().getString(R.string.app_id);\n String url = mXpushSession.getServerUrl() + \"/global\";\n\n IO.Options opts = new IO.Options();\n opts.forceNew = true;\n opts.reconnectionAttempts = 20;\n try {\n opts.query = \"A=\"+appId+\"&U=\"+ URLEncoder.encode(mXpushSession.getId(), \"UTF-8\")+\"&TK=\"+mXpushSession.getToken()+\"&D=\"+mXpushSession.getDeviceId();\n } catch (UnsupportedEncodingException e) {\n e.printStackTrace();\n }\n\n IO.Options mOpts = opts;\n Log.i(TAG, \"Connecting with URL in XPushCore : \" + url);\n try {\n mGlobalSocket = IO.socket(url, mOpts);\n HashMap<String, Emitter.Listener> events = new HashMap<>();\n\n events.put(Socket.EVENT_CONNECT, onConnectSuccess);\n events.put(Socket.EVENT_CONNECT_ERROR, onConnectError);\n events.put(\"_event\", onNewMessage);\n\n if (events != null) {\n for (String eventName : events.keySet()) {\n mGlobalSocket.on(eventName, events.get(eventName));\n }\n }\n\n mEvents = events;\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n mGlobalSocket.connect();\n }\n\n private Emitter.Listener onNewMessage = new Emitter.Listener() {\n @Override\n public void call(final Object... args) {\n JSONObject json = (JSONObject) args[0];\n Log.d(TAG, \"on GlobalMesssage\" );\n XPushService.handleMessage(baseContext, json);\n }\n };\n\n private Emitter.Listener onConnectSuccess = new Emitter.Listener() {\n @Override\n public void call(Object... args) {\n Log.d(TAG, \"connect sucesss\");\n mConnecting.set(false);\n setGlobalSocketConnected();\n }\n };\n\n private Emitter.Listener onConnectError = new Emitter.Listener() {\n @Override\n public void call(Object... args) {\n\n if( args[0] instanceof SocketIOException) {\n SocketIOException e = (SocketIOException) args[0];\n Log.d(TAG, e.getMessage());\n } else if ( args[0] instanceof EngineIOException){\n EngineIOException e = (EngineIOException) args[0];\n Log.d(TAG, e.getMessage());\n }\n mConnecting.set(false);\n }\n };\n\n private int getOnlineType() {\n try {\n ConnectivityManager conMan = (ConnectivityManager) baseContext.getSystemService(Context.CONNECTIVITY_SERVICE);\n\n NetworkInfo.State wifi = conMan.getNetworkInfo(1).getState(); // wifi\n if (wifi == NetworkInfo.State.CONNECTED || wifi == NetworkInfo.State.CONNECTING)\n return NETWORK_WIFI;\n\n NetworkInfo.State mobile = conMan.getNetworkInfo(0).getState();\n if (mobile == NetworkInfo.State.CONNECTED || mobile == NetworkInfo.State.CONNECTING)\n return NETWORK_MOBILE;\n\n } catch (NullPointerException e) {\n return NETWORK_NOT_AVAILABLE;\n }\n\n return NETWORK_NOT_AVAILABLE;\n }\n\n public void disconnect(){\n for (String eventName : mEvents.keySet()) {\n this.off(eventName);\n }\n Log.d(TAG, \"=== disconnect global socket ===\");\n mGlobalSocket.disconnect();\n }\n\n public Socket getGlobalSocket(){\n return mGlobalSocket;\n }\n\n public boolean isConnecting(){\n return mConnecting.get();\n }\n\n public void on(String event, Emitter.Listener eventListener) {\n if( !mEvents.containsKey( event) ){\n mGlobalSocket.on(event, eventListener);\n }\n }\n\n public void off(String event) {\n mGlobalSocket.off(event);\n }\n}",
"public class XPushSession {\n\n public static final String ID = \"U\";\n public static final String PASSWORD = \"PW\";\n public static final String DEVICE_ID = \"D\";\n public static final String TOKEN = \"TK\";\n public static final String NOTI_ID = \"N\";\n public static final String SERVER_NAME = \"SERVER_NAME\";\n public static final String SERVER_URL = \"SERVER_URL\";\n public static final String IMAGE = \"I\";\n public static final String NAME = \"NM\";\n public static final String MESSAGE = \"MG\";\n public static final String EMAIL = \"EM\";\n\n private String id;\n private String password;\n private String deviceId;\n private String token;\n private String notiId;\n private String serverName;\n private String image;\n private String serverUrl;\n private String name;\n private String message;\n private String email;\n\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n public String getDeviceId() {\n return deviceId;\n }\n\n public void setDeviceId(String deviceId) {\n this.deviceId = deviceId;\n }\n\n public String getToken() {\n return token;\n }\n\n public void setToken(String token) {\n this.token = token;\n }\n\n public String getNotiId() {\n return notiId;\n }\n\n public void setNotiId(String notiId) {\n this.notiId = notiId;\n }\n\n public String getServerName() {\n return serverName;\n }\n\n public void setServerName(String serverName) {\n this.serverName = serverName;\n }\n\n public String getServerUrl() {\n return serverUrl;\n }\n\n public void setServerUrl(String serverUrl) {\n this.serverUrl = serverUrl;\n }\n\n public String getImage() {\n return image;\n }\n\n public void setImage(String image) {\n this.image = image;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getMessage() {\n return message;\n }\n\n public void setMessage(String message) {\n this.message = message;\n }\n\n public String getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n\n public XPushSession(){\n }\n\n public XPushSession(Bundle bundle){\n this.id= bundle.getString(ID);\n this.password= bundle.getString(PASSWORD);\n this.deviceId= bundle.getString(DEVICE_ID);\n this.token= bundle.getString(TOKEN);\n this.notiId= bundle.getString(NOTI_ID);\n this.serverName= bundle.getString(SERVER_NAME);\n this.serverUrl= bundle.getString(SERVER_URL);\n this.image = bundle.getString(IMAGE);\n this.name = bundle.getString(NAME);\n this.message = bundle.getString(MESSAGE);\n this.email = bundle.getString(EMAIL);\n }\n\n public XPushSession(JSONObject object){\n try {\n if( object.has(ID)) {\n this.id = object.getString(ID);\n }\n if( object.has(PASSWORD)) {\n this.password = object.getString(PASSWORD);\n }\n if( object.has(DEVICE_ID)) {\n this.deviceId = object.getString(DEVICE_ID);\n }\n if( object.has(TOKEN)) {\n this.token = object.getString(TOKEN);\n }\n if( object.has(NOTI_ID)) {\n this.notiId = object.getString(NOTI_ID);\n }\n if( object.has(SERVER_NAME)) {\n this.serverName = object.getString(SERVER_NAME);\n }\n if( object.has(SERVER_URL)) {\n this.serverUrl = object.getString(SERVER_URL);\n }\n\n if( object.has(IMAGE)) {\n this.image = object.getString(IMAGE);\n }\n\n if( object.has(NAME)) {\n this.name = object.getString(NAME);\n }\n\n if( object.has(MESSAGE)) {\n this.message = object.getString(MESSAGE);\n }\n\n if( object.has(EMAIL)) {\n this.email = object.getString(EMAIL);\n }\n\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n\n public JSONObject toJSON() {\n JSONObject j = new JSONObject();\n try {\n j.put(ID, this.id);\n j.put(PASSWORD, this.password);\n j.put(DEVICE_ID, this.deviceId);\n j.put(TOKEN, this.token);\n j.put(NOTI_ID, this.notiId);\n j.put(SERVER_NAME, this.serverName);\n j.put(SERVER_URL, this.serverUrl);\n j.put(IMAGE, this.image);\n j.put(NAME, this.name);\n j.put(MESSAGE, this.message);\n j.put(EMAIL, this.email);\n } catch (JSONException e) {\n e.printStackTrace();\n }\n\n return j;\n }\n\n public JSONObject getUserData(){\n JSONObject userData = new JSONObject();\n try {\n userData.put(\"NM\", name);\n userData.put(\"I\", image);\n userData.put(\"MG\", message);\n userData.put(\"EM\", email);\n } catch (JSONException e) {\n e.printStackTrace();\n }\n\n return userData;\n }\n}",
"public class EditNickNameActivity extends FragmentActivity implements TextWatcher{\n\n private EditText mUserName = null;\n private TextView mTextCount;\n\n protected void onCreate(Bundle paramBundle) {\n super.onCreate(paramBundle);\n setContentView(R.layout.activity_edit_nickname);\n\n mUserName = ((EditText)findViewById(R.id.user_name));\n mTextCount = ((TextView)findViewById(R.id.text_count));\n\n mUserName.setText(XPushCore.getInstance().getXpushSession().getName() );\n mTextCount.setText( ContentUtils.getInputStringLength(XPushCore.getXpushSession().getName(), 20) );\n mUserName.setSelection(mUserName.getText().length());\n\n mUserName.addTextChangedListener(this);\n mUserName.setOnEditorActionListener(new TextView.OnEditorActionListener() {\n @Override\n public boolean onEditorAction(TextView textView, int paramInt, KeyEvent paramKeyEvent) {\n\n if ((paramInt == EditorInfo.IME_ACTION_DONE ) || ((paramKeyEvent != null) && (paramKeyEvent.getKeyCode() == 66))) {\n Intent intent = new Intent();\n intent.putExtra(\"nickname\", mUserName.getText().toString());\n setResult(RESULT_OK, intent);\n finish();\n return true;\n }\n return false;\n }\n });\n }\n\n @Override\n public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {\n\n }\n\n @Override\n public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {\n\n }\n\n @Override\n public void afterTextChanged(Editable editable) {\n String strLen = ContentUtils.getInputStringLength(editable.toString(), 20);\n mTextCount.setText( strLen );\n }\n}",
"public class EditStatusMessageActivity extends FragmentActivity implements TextWatcher{\n\n private EditText mStatusMessage = null;\n private TextView mTextCount;\n\n protected void onCreate(Bundle paramBundle) {\n super.onCreate(paramBundle);\n setContentView(R.layout.activity_edit_status_message);\n\n mStatusMessage = ((EditText)findViewById(R.id.status_message));\n mTextCount = ((TextView)findViewById(R.id.text_count));\n\n mStatusMessage.setText(XPushCore.getXpushSession().getMessage() );\n mTextCount.setText( ContentUtils.getInputStringLength(XPushCore.getXpushSession().getMessage(), 20) );\n mStatusMessage.setSelection(mStatusMessage.getText().length());\n\n mStatusMessage.addTextChangedListener(this);\n mStatusMessage.setOnEditorActionListener(new TextView.OnEditorActionListener() {\n @Override\n public boolean onEditorAction(TextView textView, int paramInt, KeyEvent paramKeyEvent) {\n\n if ((paramInt == EditorInfo.IME_ACTION_DONE ) || ((paramKeyEvent != null) && (paramKeyEvent.getKeyCode() == 66))) {\n Intent intent = new Intent();\n intent.putExtra(\"statusMessage\", mStatusMessage.getText().toString());\n setResult(RESULT_OK, intent);\n finish();\n return true;\n }\n return false;\n }\n });\n }\n\n @Override\n public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {\n\n }\n\n @Override\n public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {\n\n }\n\n @Override\n public void afterTextChanged(Editable editable) {\n String strLen = ContentUtils.getInputStringLength(editable.toString(), 20);\n mTextCount.setText( strLen );\n }\n}"
] | import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.facebook.drawee.view.SimpleDraweeView;
import org.json.JSONException;
import org.json.JSONObject;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.xpush.chat.common.Constants;
import io.xpush.chat.core.CallbackEvent;
import io.xpush.chat.core.XPushCore;
import io.xpush.chat.models.XPushSession;
import io.xpush.sampleChat.R;
import io.xpush.sampleChat.activities.EditNickNameActivity;
import io.xpush.sampleChat.activities.EditStatusMessageActivity; | package io.xpush.sampleChat.fragments;
public class ProfileFragment extends Fragment {
private String TAG = ProfileFragment.class.getSimpleName();
private Context mActivity;
| private XPushSession mSession; | 3 |
bonigarcia/dualsub | src/test/java/io/github/bonigarcia/dualsub/test/TestSynchronization.java | [
"public class DualSrt {\n\n\tprivate static final Logger log = LoggerFactory.getLogger(DualSrt.class);\n\n\tprivate TreeMap<String, Entry[]> subtitles;\n\n\tprivate int signatureGap;\n\tprivate int signatureTime;\n\tprivate int gap;\n\tprivate int desync;\n\tprivate int extension;\n\tprivate boolean extend;\n\tprivate boolean progressive;\n\n\tprivate final String SPACE_HTML = \" \";\n\n\tpublic DualSrt(Properties properties, int desync, boolean extend,\n\t\t\tint extension, boolean progressive) {\n\t\tthis.extend = extend;\n\t\tthis.extension = extension;\n\t\tthis.progressive = progressive;\n\n\t\tthis.subtitles = new TreeMap<String, Entry[]>();\n\n\t\tthis.signatureGap = Integer\n\t\t\t\t.parseInt(properties.getProperty(\"signatureGap\")); // seconds\n\t\tthis.signatureTime = Integer\n\t\t\t\t.parseInt(properties.getProperty(\"signatureTime\")); // seconds\n\t\tthis.gap = Integer.parseInt(properties.getProperty(\"gap\")); // milliseconds\n\t\tthis.desync = desync;\n\t}\n\n\tpublic void addEntry(String time, Entry[] entries) {\n\t\tthis.subtitles.put(time, entries);\n\t}\n\n\tpublic void addAll(Map<String, Entry> allSubs) {\n\t\tfor (String t : allSubs.keySet()) {\n\t\t\taddEntry(t, new Entry[] { allSubs.get(t) });\n\t\t}\n\t}\n\n\tpublic void log() {\n\t\tString left = null, right = null, line = \"\";\n\t\tfor (String time : subtitles.keySet()) {\n\t\t\tfor (int i = 0; i < Math.max(subtitles.get(time)[0].size(),\n\t\t\t\t\tsubtitles.get(time)[1].size()); i++) {\n\t\t\t\tleft = i < subtitles.get(time)[0].size()\n\t\t\t\t\t\t? subtitles.get(time)[0].get(i)\n\t\t\t\t\t\t: SrtUtils.getBlankLine();\n\t\t\t\tright = i < subtitles.get(time)[1].size()\n\t\t\t\t\t\t? subtitles.get(time)[1].get(i)\n\t\t\t\t\t\t: SrtUtils.getBlankLine();\n\t\t\t\tline = left + right;\n\t\t\t\tlog.info(time + \" \" + line + \" \" + SrtUtils.getWidth(line));\n\t\t\t}\n\t\t\tlog.info(\"\");\n\t\t}\n\t}\n\n\tprivate void addPadding() {\n\t\tMap<String, Entry[]> output = new TreeMap<String, Entry[]>();\n\t\tEntry[] newEntry;\n\n\t\tfor (String t : subtitles.keySet()) {\n\t\t\tnewEntry = new Entry[2];\n\t\t\tfor (int i = 0; i < 2; i++) {\n\t\t\t\tif (isLong(subtitles.get(t)[i])) {\n\t\t\t\t\tnewEntry[i] = this.splitEntry(subtitles.get(t)[i]);\n\t\t\t\t} else {\n\t\t\t\t\tnewEntry[i] = this.noSplitEntry(subtitles.get(t)[i]);\n\t\t\t\t}\n\t\t\t\toutput.put(t, newEntry);\n\t\t\t}\n\t\t}\n\t\tsubtitles = new TreeMap<String, Entry[]>(output);\n\t}\n\n\t/**\n\t * It checks whether or not an entry (collection of entries) is long (width\n\t * upper than half_width)\n\t * \n\t * @param entry\n\t * @return\n\t */\n\tprivate boolean isLong(Entry entry) {\n\t\tboolean split = false;\n\t\tfloat width;\n\t\tfor (int i = 0; i < entry.size(); i++) {\n\t\t\twidth = SrtUtils.getWidth(entry.get(i));\n\t\t\tif (width > SrtUtils.getHalfWidth()) {\n\t\t\t\tsplit = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn split;\n\t}\n\n\t/**\n\t * It converts and entry adding the padding and splitting lines.\n\t * \n\t * @param entry\n\t * @return\n\t */\n\tprivate Entry splitEntry(Entry entry) {\n\t\tEntry newEntry = new Entry();\n\n\t\tString append = \"\";\n\t\tfor (int i = 0; i < entry.size(); i++) {\n\t\t\tappend += entry.get(i) + SrtUtils.getSpace();\n\t\t}\n\t\tappend = append.trim();\n\t\tString[] words = append.split(SrtUtils.getSpace());\n\n\t\tList<String> ensuredArray = ensureArray(words);\n\n\t\tString newLine = \"\";\n\t\tfor (int i = 0; i < ensuredArray.size(); i++) {\n\t\t\tif (SrtUtils.getWidth(newLine + ensuredArray.get(i)) < SrtUtils\n\t\t\t\t\t.getHalfWidth()) {\n\t\t\t\tnewLine += ensuredArray.get(i) + SrtUtils.getSpace();\n\t\t\t} else {\n\t\t\t\tnewEntry.add(convertLine(newLine.trim()));\n\t\t\t\tnewLine = ensuredArray.get(i) + SrtUtils.getSpace();\n\t\t\t}\n\t\t}\n\t\tif (!newLine.isEmpty()) {\n\t\t\tnewEntry.add(convertLine(newLine.trim()));\n\t\t}\n\n\t\treturn newEntry;\n\t}\n\n\t/**\n\t * It converts and entry adding the padding but without splitting lines.\n\t * \n\t * @param entry\n\t * @return\n\t */\n\tprivate Entry noSplitEntry(Entry entry) {\n\t\tEntry newEntry = new Entry(entry);\n\t\tfor (int i = 0; i < entry.size(); i++) {\n\t\t\tnewEntry.set(i, convertLine(entry.get(i)));\n\t\t}\n\t\treturn newEntry;\n\t}\n\n\t/**\n\t * Ensures that each word in the arrays in no longer than MAXWIDTH\n\t * \n\t * @param words\n\t * @return\n\t */\n\tprivate List<String> ensureArray(String[] words) {\n\t\tList<String> ensured = new LinkedList<String>();\n\t\tfor (String s : words) {\n\t\t\tif (SrtUtils.getWidth(s) <= SrtUtils.getHalfWidth()) {\n\t\t\t\tensured.add(s);\n\t\t\t} else {\n\t\t\t\tint sLength = s.length();\n\t\t\t\tensured.add(s.substring(0, sLength / 2));\n\t\t\t\tensured.add(s.substring(sLength / 2, sLength / 2));\n\t\t\t}\n\t\t}\n\t\treturn ensured;\n\t}\n\n\t/**\n\t * It adds the padding (SEPARATOR + SPACEs) to a single line.\n\t * \n\t * @param line\n\t * @return\n\t */\n\tprivate String convertLine(String line) {\n\t\tfloat width = SrtUtils.getWidth(line);\n\t\tdouble diff = ((SrtUtils.getHalfWidth() - width)\n\t\t\t\t/ SrtUtils.getSpaceWidth()) / 2;\n\t\tdouble rest = diff % 1;\n\t\tint numSpaces = (int) Math.floor(diff);\n\t\tString additional = (rest >= 0.5) ? SrtUtils.getPadding() : \"\";\n\n\t\tif (numSpaces < 0) {\n\t\t\tnumSpaces = 0;\n\t\t}\n\t\tString newLine = SrtUtils.getSeparator()\n\t\t\t\t+ SrtUtils.repeat(SrtUtils.getPadding(), numSpaces + 1)\n\t\t\t\t+ additional + line\n\t\t\t\t+ SrtUtils.repeat(SrtUtils.getPadding(), numSpaces + 1)\n\t\t\t\t+ SrtUtils.getSeparator();\n\n\t\treturn newLine;\n\t}\n\n\tpublic void processDesync(String time, Entry desyncEntry)\n\t\t\tthrows ParseException {\n\t\tTreeMap<String, Entry[]> newSubtitles = new TreeMap<String, Entry[]>();\n\n\t\tDate inTime = SrtUtils.getInitTime(time);\n\t\tDate enTime = SrtUtils.getEndTime(time);\n\t\tlong initTime = inTime != null ? inTime.getTime() : 0;\n\t\tlong endTime = enTime != null ? enTime.getTime() : 0;\n\t\tlong iTime, jTime;\n\t\tint top = 0, down = subtitles.keySet().size();\n\t\tboolean topOver = false, downOver = false;\n\t\tint from, to;\n\n\t\tfor (String t : subtitles.keySet()) {\n\t\t\tinTime = SrtUtils.getInitTime(time);\n\t\t\tenTime = SrtUtils.getEndTime(time);\n\n\t\t\t// Added to ensure format\n\t\t\tif (!t.contains(\"-->\")) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tiTime = inTime != null ? SrtUtils.getInitTime(t).getTime() : 0;\n\t\t\tjTime = enTime != null ? SrtUtils.getEndTime(t).getTime() : 0;\n\n\t\t\tif (iTime <= initTime) {\n\t\t\t\ttop++;\n\t\t\t}\n\t\t\tif (jTime >= endTime) {\n\t\t\t\tdown--;\n\t\t\t}\n\t\t\tif (iTime <= initTime && jTime >= initTime) {\n\t\t\t\ttopOver = true;\n\t\t\t}\n\t\t\tif (iTime <= endTime && jTime >= endTime) {\n\t\t\t\tdownOver = true;\n\t\t\t}\n\t\t}\n\t\tfrom = top - 1 + (topOver ? 0 : 1);\n\t\tto = down - (downOver ? 0 : 1);\n\n\t\tlog.debug(time + \" TOP \" + top + \" DOWN \" + down + \" TOPOVER \" + topOver\n\t\t\t\t+ \" DOWNOVER \" + downOver + \" SIZE \" + subtitles.size()\n\t\t\t\t+ \" FROM \" + from + \" TO \" + to + \" \"\n\t\t\t\t+ desyncEntry.getSubtitleLines());\n\t\tString mixedTime = mixTime(initTime, endTime, from, to);\n\t\tlog.debug(mixedTime);\n\n\t\tEntry newEntryLeft = new Entry();\n\t\tEntry newEntryRight = new Entry();\n\t\tfor (int i = from; i <= to; i++) {\n\t\t\tnewEntryLeft\n\t\t\t\t\t.addAll(subtitles.get(subtitles.keySet().toArray()[i])[0]);\n\t\t\tnewEntryRight\n\t\t\t\t\t.addAll(subtitles.get(subtitles.keySet().toArray()[i])[1]);\n\t\t}\n\t\tnewEntryRight.addAll(desyncEntry);\n\n\t\tif (top != 0) {\n\t\t\tnewSubtitles.putAll(subtitles.subMap(subtitles.firstKey(), true,\n\t\t\t\t\t(String) subtitles.keySet().toArray()[top - 1], !topOver));\n\t\t}\n\t\tnewSubtitles.put(mixedTime,\n\t\t\t\tnew Entry[] { newEntryLeft, newEntryRight });\n\t\tif (down != subtitles.size()) {\n\t\t\tnewSubtitles.putAll(subtitles.subMap(\n\t\t\t\t\t(String) subtitles.keySet().toArray()[down], !downOver,\n\t\t\t\t\tsubtitles.lastKey(), true));\n\t\t}\n\n\t\tsubtitles = newSubtitles;\n\t}\n\n\tprivate String mixTime(long initTime, long endTime, int from, int to)\n\t\t\tthrows ParseException {\n\n\t\tlong initCandidate = initTime;\n\t\tlong endCandidate = endTime;\n\t\tlong initFromTime = initTime;\n\t\tlong endToTime = endTime;\n\n\t\tif (to > 0 && to >= from) {\n\t\t\tif (from < subtitles.size()) {\n\t\t\t\tDate iTime = SrtUtils.getInitTime(\n\t\t\t\t\t\t(String) subtitles.keySet().toArray()[from]);\n\t\t\t\tif (iTime != null) {\n\t\t\t\t\tinitFromTime = iTime.getTime();\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (to < subtitles.size()) {\n\t\t\t\tDate eTime = SrtUtils\n\t\t\t\t\t\t.getEndTime((String) subtitles.keySet().toArray()[to]);\n\t\t\t\tif (eTime != null) {\n\t\t\t\t\tendToTime = eTime.getTime();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tswitch (getDesync()) {\n\t\t\tcase 0:\n\t\t\t\t// Left\n\t\t\t\tinitCandidate = initFromTime;\n\t\t\t\tendCandidate = endToTime;\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\t// Right\n\t\t\t\tinitCandidate = initTime;\n\t\t\t\tendCandidate = endTime;\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\t// Max\n\t\t\t\tinitCandidate = Math.min(initTime, initFromTime);\n\t\t\t\tendCandidate = Math.max(endTime, endToTime);\n\t\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\t// Min\n\t\t\t\tinitCandidate = Math.max(initTime, initFromTime);\n\t\t\t\tendCandidate = Math.min(endTime, endToTime);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\treturn SrtUtils.createSrtTime(new Date(initCandidate),\n\t\t\t\tnew Date(endCandidate));\n\t}\n\n\t/**\n\t * It writes a new subtitle file (SRT) from a subtitle map.\n\t * \n\t * @param subs\n\t * @param fileOuput\n\t * @throws IOException\n\t * @throws ParseException\n\t */\n\tpublic void writeSrt(String fileOuput, String charsetStr, boolean translate,\n\t\t\tboolean merge) throws IOException, ParseException {\n\n\t\tboolean horizontal = SrtUtils.isHorizontal();\n\t\tif (!horizontal && (!translate || (translate & merge))) {\n\t\t\taddPadding();\n\t\t}\n\t\tif (extend) {\n\t\t\tshiftSubs(extension, progressive);\n\t\t}\n\n\t\tString blankLine = horizontal ? \"\" : SrtUtils.getBlankLine();\n\n\t\tFileOutputStream fileOutputStream = new FileOutputStream(\n\t\t\t\tnew File(fileOuput));\n\t\tFileChannel fileChannel = fileOutputStream.getChannel();\n\n\t\tCharset charset = Charset.forName(charsetStr);\n\t\tCharsetEncoder encoder = charset.newEncoder();\n\t\tencoder.onMalformedInput(CodingErrorAction.IGNORE);\n\t\tencoder.onUnmappableCharacter(CodingErrorAction.IGNORE);\n\n\t\tCharBuffer uCharBuffer;\n\t\tByteBuffer byteBuffer;\n\n\t\tif (horizontal) {\n\t\t\tfor (String key : subtitles.keySet()) {\n\t\t\t\tEntry[] entries = subtitles.get(key);\n\t\t\t\tfor (int j = 0; j < entries.length; j++) {\n\t\t\t\t\tList<String> subtitleLines = entries[j].getSubtitleLines();\n\t\t\t\t\tString newLine = \"\";\n\t\t\t\t\tfor (String s : subtitleLines) {\n\t\t\t\t\t\tnewLine += s + \" \";\n\t\t\t\t\t}\n\t\t\t\t\tsubtitleLines.clear();\n\t\t\t\t\tsubtitleLines.add(newLine.trim());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tString left = \"\", right = \"\", time = \"\";\n\t\tString separator = SrtUtils.getSeparator().trim().isEmpty() ? SPACE_HTML\n\t\t\t\t: SrtUtils.getSeparator();\n\t\tString horizontalSeparator = SrtUtils.EOL\n\t\t\t\t+ (SrtUtils.isUsingSeparator() ? separator + SrtUtils.EOL : \"\");\n\t\tfor (int j = 0; j < subtitles.keySet().size(); j++) {\n\t\t\ttime = (String) subtitles.keySet().toArray()[j];\n\t\t\tbyteBuffer = ByteBuffer.wrap((String.valueOf(j + 1) + SrtUtils.EOL)\n\t\t\t\t\t.getBytes(Charset.forName(charsetStr)));\n\t\t\tfileChannel.write(byteBuffer);\n\t\t\tbyteBuffer = ByteBuffer.wrap((time + SrtUtils.EOL)\n\t\t\t\t\t.getBytes(Charset.forName(charsetStr)));\n\t\t\tfileChannel.write(byteBuffer);\n\n\t\t\tint limit = subtitles.get(time).length > 1\n\t\t\t\t\t? Math.max(subtitles.get(time)[0].size(),\n\t\t\t\t\t\t\tsubtitles.get(time)[1].size())\n\t\t\t\t\t: subtitles.get(time)[0].size();\n\t\t\tfor (int i = 0; i < limit; i++) {\n\t\t\t\tleft = i < subtitles.get(time)[0].size()\n\t\t\t\t\t\t? subtitles.get(time)[0].get(i) : blankLine;\n\t\t\t\tif (subtitles.get(time).length > 1) {\n\t\t\t\t\tright = i < subtitles.get(time)[1].size()\n\t\t\t\t\t\t\t? subtitles.get(time)[1].get(i) : blankLine;\n\t\t\t\t}\n\n\t\t\t\tString leftColor = SrtUtils.getParsedLeftColor();\n\t\t\t\tif (leftColor != null) {\n\t\t\t\t\tleft = String.format(leftColor, left);\n\t\t\t\t}\n\t\t\t\tString rightColor = SrtUtils.getParsedRightColor();\n\t\t\t\tif (rightColor != null) {\n\t\t\t\t\tright = String.format(rightColor, right);\n\t\t\t\t}\n\n\t\t\t\tif (horizontal) {\n\t\t\t\t\tuCharBuffer = CharBuffer.wrap(\n\t\t\t\t\t\t\tleft + horizontalSeparator + right + SrtUtils.EOL);\n\t\t\t\t} else {\n\t\t\t\t\tuCharBuffer = CharBuffer.wrap(left + right + SrtUtils.EOL);\n\t\t\t\t}\n\t\t\t\tbyteBuffer = encoder.encode(uCharBuffer);\n\n\t\t\t\tlog.debug(new String(byteBuffer.array(),\n\t\t\t\t\t\tCharset.forName(charsetStr)));\n\n\t\t\t\tfileChannel.write(byteBuffer);\n\t\t\t}\n\t\t\tbyteBuffer = ByteBuffer\n\t\t\t\t\t.wrap(SrtUtils.EOL.getBytes(Charset.forName(charsetStr)));\n\t\t\tfileChannel.write(byteBuffer);\n\t\t}\n\n\t\tfor (String s : signature(translate, merge)) {\n\t\t\tbyteBuffer = ByteBuffer.wrap(\n\t\t\t\t\t(s + SrtUtils.EOL).getBytes(Charset.forName(charsetStr)));\n\t\t\tfileChannel.write(byteBuffer);\n\t\t}\n\t\tbyteBuffer = ByteBuffer\n\t\t\t\t.wrap(SrtUtils.EOL.getBytes(Charset.forName(charsetStr)));\n\t\tfileChannel.write(byteBuffer);\n\t\tfileChannel.close();\n\n\t\tfileOutputStream.close();\n\t}\n\n\t/**\n\t * Adds an entry in the end of the merged subtitles with the program author.\n\t * \n\t * @param subs\n\t * @throws ParseException\n\t */\n\tprivate List<String> signature(boolean translate, boolean merge)\n\t\t\tthrows ParseException {\n\t\tString lastEntryTime = (String) subtitles.keySet()\n\t\t\t\t.toArray()[subtitles.keySet().size() - 1];\n\t\tDate end = SrtUtils.getEndTime(lastEntryTime);\n\t\tfinal Date newDateInit = new Date(end.getTime() + signatureGap);\n\t\tfinal Date newDateEnd = new Date(end.getTime() + signatureTime);\n\t\tString newTime = SrtUtils.createSrtTime(newDateInit, newDateEnd);\n\t\tList<String> signature = new LinkedList<String>();\n\t\tsignature.add(String.valueOf(subtitles.size() + 1));\n\t\tsignature.add(newTime);\n\t\tString signatureText = \"\";\n\t\tif (translate & merge) {\n\t\t\tsignatureText = I18N.getText(\"Merger.signatureboth.text\");\n\t\t} else if (translate & !merge) {\n\t\t\tsignatureText = I18N.getText(\"Merger.signaturetranslated.text\");\n\t\t} else {\n\t\t\tsignatureText = I18N.getText(\"Merger.signature.text\");\n\t\t}\n\t\tsignature.add(signatureText);\n\t\tsignature.add(I18N.getText(\"Merger.signature.url\"));\n\t\treturn signature;\n\t}\n\n\t/**\n\t * This method extends the duration of each subtitle 1 second (EXTENSION).\n\t * If the following subtitle is located inside that extension, the extension\n\t * will be only until the beginning of this next subtitle minus 20\n\t * milliseconds (GAP).\n\t * \n\t * @throws ParseException\n\t */\n\tpublic void shiftSubs(int extension, boolean progressive)\n\t\t\tthrows ParseException {\n\t\tTreeMap<String, Entry[]> newSubtitles = new TreeMap<String, Entry[]>();\n\n\t\tString timeBefore = \"\";\n\t\tDate init;\n\t\tDate tsBeforeInit = new Date();\n\t\tDate tsBeforeEnd = new Date();\n\t\tString newTime = \"\";\n\t\tEntry[] entries;\n\t\tint shiftTime = extension;\n\n\t\tfor (String t : subtitles.keySet()) {\n\t\t\tif (!timeBefore.isEmpty()) {\n\t\t\t\tinit = SrtUtils.getInitTime(t);\n\t\t\t\tif (init != null) {\n\t\t\t\t\tentries = subtitles.get(timeBefore);\n\t\t\t\t\tif (progressive) {\n\t\t\t\t\t\tshiftTime = entries.length > 1 ? extension\n\t\t\t\t\t\t\t\t* Math.max(entries[0].size(), entries[1].size())\n\t\t\t\t\t\t\t\t: entries[0].size();\n\t\t\t\t\t}\n\t\t\t\t\tif (tsBeforeEnd.getTime() + shiftTime < init.getTime()) {\n\t\t\t\t\t\tnewTime = SrtUtils.createSrtTime(tsBeforeInit,\n\t\t\t\t\t\t\t\tnew Date(tsBeforeEnd.getTime() + shiftTime));\n\t\t\t\t\t\tlog.debug(\"Shift \" + timeBefore + \" to \" + newTime\n\t\t\t\t\t\t\t\t+ \" ... extension \" + shiftTime);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tnewTime = SrtUtils.createSrtTime(tsBeforeInit,\n\t\t\t\t\t\t\t\tnew Date(init.getTime() - gap));\n\t\t\t\t\t\tlog.debug(\"Shift \" + timeBefore + \" to \" + newTime);\n\t\t\t\t\t}\n\t\t\t\t\tnewSubtitles.put(newTime, entries);\n\t\t\t\t}\n\t\t\t}\n\t\t\ttimeBefore = t;\n\t\t\ttsBeforeInit = SrtUtils.getInitTime(timeBefore);\n\t\t\ttsBeforeEnd = SrtUtils.getEndTime(timeBefore);\n\t\t\tif (tsBeforeInit == null || tsBeforeEnd == null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\t// Last entry\n\t\tentries = subtitles.get(timeBefore);\n\t\tif (entries != null && tsBeforeInit != null && tsBeforeEnd != null) {\n\t\t\tif (progressive) {\n\t\t\t\textension *= entries.length > 1\n\t\t\t\t\t\t? Math.max(entries[0].size(), entries[1].size())\n\t\t\t\t\t\t: entries[0].size();\n\t\t\t}\n\t\t\tnewTime = SrtUtils.createSrtTime(tsBeforeInit,\n\t\t\t\t\tnew Date(tsBeforeEnd.getTime() + extension));\n\t\t\tnewSubtitles.put(newTime, entries);\n\t\t}\n\n\t\tsubtitles = newSubtitles;\n\t}\n\n\tpublic int size() {\n\t\treturn subtitles.size();\n\t}\n\n\tpublic int getDesync() {\n\t\treturn desync;\n\t}\n\n}",
"public class Merger {\n\n\tprivate static final Logger log = LoggerFactory.getLogger(Merger.class);\n\n\tprivate String outputFolder;\n\tprivate int extension;\n\tprivate boolean extend;\n\tprivate boolean progressive;\n\tprivate Properties properties;\n\tprivate String charset;\n\tprivate int desynch;\n\tprivate boolean translate;\n\tprivate boolean merge;\n\n\tpublic Merger(String outputFolder, boolean extend, int extension,\n\t\t\tboolean progressive, Properties properties, String charset,\n\t\t\tint desynch, boolean translate, boolean merge) {\n\t\tthis.outputFolder = outputFolder;\n\t\tthis.extend = extend;\n\t\t// Extension should be in ms, and GUI asks for it in seconds\n\t\tthis.extension = 1000 * extension;\n\t\tthis.progressive = progressive;\n\t\tthis.properties = properties;\n\t\tthis.charset = charset;\n\t\tthis.desynch = desynch;\n\t\tthis.translate = translate;\n\t\tthis.merge = merge;\n\t}\n\n\tpublic DualSrt mergeSubs(Srt srtLeft, Srt srtRigth) throws ParseException {\n\t\tDualSrt dualSrt = new DualSrt(properties, getDesynch(), extend,\n\t\t\t\textension, progressive);\n\n\t\tMap<String, Entry> subtitlesLeft = new TreeMap<String, Entry>(\n\t\t\t\tsrtLeft.getSubtitles());\n\t\tMap<String, Entry> subtitlesRight = new TreeMap<String, Entry>(\n\t\t\t\tsrtRigth.getSubtitles());\n\n\t\tif (subtitlesLeft.isEmpty() || subtitlesRight.isEmpty()) {\n\t\t\tif (subtitlesLeft.isEmpty()) {\n\t\t\t\tdualSrt.addAll(subtitlesRight);\n\t\t\t} else if (subtitlesRight.isEmpty()) {\n\t\t\t\tdualSrt.addAll(subtitlesLeft);\n\t\t\t}\n\t\t} else {\n\t\t\tfor (String t : subtitlesLeft.keySet()) {\n\t\t\t\tif (subtitlesRight.containsKey(t)) {\n\t\t\t\t\tdualSrt.addEntry(t, new Entry[] { subtitlesLeft.get(t),\n\t\t\t\t\t\t\tsubtitlesRight.get(t) });\n\t\t\t\t\tsubtitlesRight.remove(t);\n\t\t\t\t} else {\n\t\t\t\t\tdualSrt.addEntry(t, new Entry[] { subtitlesLeft.get(t),\n\t\t\t\t\t\t\tnew Entry() });\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!subtitlesRight.isEmpty()) {\n\t\t\t\tfor (String t : subtitlesRight.keySet()) {\n\t\t\t\t\tlog.debug(\"Desynchronization on \" + t + \" \"\n\t\t\t\t\t\t\t+ subtitlesRight.get(t).subtitleLines);\n\t\t\t\t\tdualSrt.processDesync(t, subtitlesRight.get(t));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn dualSrt;\n\t}\n\n\tpublic String getMergedFileName(Srt subs1, Srt subs2) {\n\t\tString mergedFileName = \"\";\n\t\tif (translate) {\n\t\t\tSrt srt = subs1.getFileName() == null ? subs2 : subs1;\n\t\t\tFile file = new File(srt.getFileName());\n\t\t\tString fileName = file.getName();\n\t\t\tint i = fileName.lastIndexOf('.');\n\t\t\ti = i == -1 ? fileName.length() - 1 : i;\n\t\t\tString extension = fileName.substring(i);\n\t\t\tmergedFileName = getOutputFolder() + File.separator\n\t\t\t\t\t+ fileName.substring(0, i);\n\t\t\tif (merge) {\n\t\t\t\tmergedFileName += \" \" + I18N.getText(\"Merger.merged.text\");\n\t\t\t} else {\n\t\t\t\tmergedFileName += \" \" + I18N.getText(\"Merger.translated.text\");\n\t\t\t}\n\t\t\tmergedFileName += extension;\n\t\t} else {\n\t\t\tmergedFileName = getOutputFolder() + File.separator\n\t\t\t\t\t+ compareNames(subs1.getFileName(), subs2.getFileName());\n\t\t}\n\t\treturn mergedFileName;\n\t}\n\n\t/**\n\t * It compares the input names of the SRTs (files) and get the part of those\n\t * name which is the same.\n\t * \n\t * @param str1\n\t * @param str2\n\t * @return\n\t */\n\tprivate String compareNames(String str1, String str2) {\n\t\tstr1 = str1.substring(str1.lastIndexOf(File.separator) + 1).replaceAll(\n\t\t\t\tSrtUtils.SRT_EXT, \"\");\n\t\tstr2 = str2.substring(str2.lastIndexOf(File.separator) + 1).replaceAll(\n\t\t\t\tSrtUtils.SRT_EXT, \"\");\n\n\t\tList<String> set1 = new ArrayList<String>(Arrays.asList(str1\n\t\t\t\t.split(\" |_|\\\\.\")));\n\t\tList<String> set2 = new ArrayList<String>(Arrays.asList(str2\n\t\t\t\t.split(\" |_|\\\\.\")));\n\t\tset1.retainAll(set2);\n\n\t\tStringBuilder sb = new StringBuilder();\n\t\tfor (String s : set1) {\n\t\t\tsb.append(s).append(SrtUtils.getSpace());\n\t\t}\n\t\tString finalName = sb.toString().trim();\n\t\tif (finalName.isEmpty()) {\n\t\t\tfinalName = I18N.getText(\"Merger.finalName.text\").trim();\n\t\t}\n\t\treturn finalName + SrtUtils.SRT_EXT;\n\t}\n\n\tpublic String getOutputFolder() {\n\t\treturn outputFolder;\n\t}\n\n\tpublic boolean isProgressive() {\n\t\treturn progressive;\n\t}\n\n\tpublic void setCharset(String charset) {\n\t\tthis.charset = charset;\n\t}\n\n\tpublic String getCharset() {\n\t\treturn charset;\n\t}\n\n\tpublic boolean isTranslate() {\n\t\treturn translate;\n\t}\n\n\tpublic boolean isMerge() {\n\t\treturn merge;\n\t}\n\n\t/**\n\t * 0 = left; 1 = right; 2 = max; 3 = min\n\t * \n\t * @return\n\t */\n\tpublic int getDesynch() {\n\t\treturn desynch;\n\t}\n\n}",
"public class Srt {\n\n\tprivate static final Logger log = LoggerFactory.getLogger(Merger.class);\n\n\tprivate Map<String, Entry> subtitles;\n\tprivate String fileName;\n\tprivate String charset;\n\n\tpublic Srt(String fileName) throws IOException {\n\t\tthis.fileName = fileName;\n\t\tthis.subtitles = new TreeMap<String, Entry>();\n\t\tthis.readSrt(fileName);\n\t}\n\n\tpublic Srt(Srt inputSrt, String fromLang, String toLang, String charset,\n\t\t\tDualSub parent) throws IOException {\n\t\tthis.subtitles = new TreeMap<String, Entry>();\n\t\tMap<String, Entry> subtitlesToTranslate = inputSrt.getSubtitles();\n\t\tString lineToTranslate;\n\t\tEntry translatedEntry;\n\n\t\tPreferences preferences;\n\t\tProperties properties;\n\n\t\tif (parent != null) {\n\t\t\tpreferences = parent.getPreferences();\n\t\t\tproperties = parent.getProperties();\n\t\t} else {\n\t\t\tpreferences = Preferences.userNodeForPackage(DualSub.class);\n\n\t\t\tproperties = new Properties();\n\t\t\tInputStream inputStream = Thread.currentThread()\n\t\t\t\t\t.getContextClassLoader()\n\t\t\t\t\t.getResourceAsStream(\"dualsub.properties\");\n\t\t\tReader reader = new InputStreamReader(inputStream,\n\t\t\t\t\tCharset.ISO88591);\n\t\t\tproperties.load(reader);\n\t\t}\n\n\t\tTranslator.getInstance().setPreferences(preferences);\n\n\t\tList<String> inputLines = new ArrayList<String>();\n\n\t\tfor (String time : subtitlesToTranslate.keySet()) {\n\t\t\tlineToTranslate = \"\";\n\t\t\tfor (String line : subtitlesToTranslate.get(time)\n\t\t\t\t\t.getSubtitleLines()) {\n\t\t\t\tlineToTranslate += line + \" \";\n\t\t\t}\n\t\t\tinputLines.add(lineToTranslate);\n\t\t}\n\n\t\tint max = Integer\n\t\t\t\t.parseInt(properties.getProperty(\"maxTranslationBatch\"));\n\t\tint size = inputLines.size();\n\t\tint rounds = 1 + (size / max);\n\t\tlog.trace(\"Number of rounds {} (total lines {})\", rounds, size);\n\n\t\tList<String> translations = new ArrayList<String>();\n\t\tfor (int i = 0; i < rounds; i++) {\n\t\t\tint fromIndex = i * max;\n\t\t\tint toIndex = fromIndex + max;\n\t\t\tif (toIndex > size) {\n\t\t\t\ttoIndex = size;\n\t\t\t}\n\n\t\t\tlog.trace(\"Round {}/{} ... from {} to {}\", i + 1, rounds, fromIndex,\n\t\t\t\t\ttoIndex);\n\n\t\t\tList<String> roundTranslation = Translator.getInstance().translate(\n\t\t\t\t\tinputLines.subList(fromIndex, toIndex), fromLang, toLang);\n\n\t\t\tlog.trace(\"Adding {} translation to result\",\n\t\t\t\t\troundTranslation.size());\n\t\t\tlog.trace(\"Translation list {} \", roundTranslation);\n\t\t\ttranslations.addAll(roundTranslation);\n\t\t}\n\n\t\tIterator<String> iterator = translations.iterator();\n\n\t\tfor (String time : subtitlesToTranslate.keySet()) {\n\t\t\ttranslatedEntry = new Entry();\n\t\t\ttranslatedEntry.add(iterator.next());\n\t\t\tsubtitles.put(time, translatedEntry);\n\t\t}\n\n\t}\n\n\t/**\n\t * Converts a subtitle file (SRT) into a Map, in which key in the timing of\n\t * each subtitle entry, and the value is a List of String with the content\n\t * of the entry.\n\t * \n\t * @param file\n\t * @throws IOException\n\t */\n\tprivate void readSrt(String file) throws IOException {\n\t\tEntry entry = new Entry();\n\t\tint i = 0;\n\t\tString time = \"\";\n\t\tInputStream isForDetection = readSrtInputStream(file);\n\t\tInputStream isForReading = readSrtInputStream(file);\n\t\tcharset = Charset.detect(isForDetection);\n\t\tlog.info(file + \" detected charset \" + charset);\n\n\t\tBufferedReader br = new BufferedReader(\n\t\t\t\tnew InputStreamReader(isForReading, charset));\n\t\ttry {\n\t\t\tString line = br.readLine();\n\t\t\twhile (line != null) {\n\t\t\t\tif (line.isEmpty()) {\n\t\t\t\t\tif (entry.size() > 0) {\n\t\t\t\t\t\tsubtitles.put(time, entry);\n\t\t\t\t\t\tentry = new Entry();\n\t\t\t\t\t\ti = 0;\n\t\t\t\t\t\ttime = \"\";\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif (i == 1) {\n\t\t\t\t\t\ttime = line;\n\t\t\t\t\t}\n\t\t\t\t\tif (i >= 2) {\n\t\t\t\t\t\t// Not adding first two lines of subtitles (index and\n\t\t\t\t\t\t// time)\n\t\t\t\t\t\tif (line.indexOf(SrtUtils.TAG_INIT) != -1\n\t\t\t\t\t\t\t\t&& line.indexOf(SrtUtils.TAG_END) != -1) {\n\t\t\t\t\t\t\tline = removeTags(line);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tentry.add(line);\n\t\t\t\t\t\tlog.debug(line);\n\t\t\t\t\t}\n\t\t\t\t\ti++;\n\t\t\t\t}\n\t\t\t\tline = br.readLine();\n\t\t\t}\n\t\t} finally {\n\t\t\tbr.close();\n\t\t\tisForReading.close();\n\t\t}\n\t}\n\n\tpublic InputStream readSrtInputStream(String file)\n\t\t\tthrows FileNotFoundException {\n\t\tInputStream inputStream = Thread.currentThread().getContextClassLoader()\n\t\t\t\t.getResourceAsStream(file);\n\t\tif (inputStream == null) {\n\t\t\tinputStream = new BufferedInputStream(new FileInputStream(file));\n\t\t}\n\t\treturn inputStream;\n\t}\n\n\tpublic static String removeTags(String line) {\n\t\tPattern pattern = Pattern.compile(\"<([^>]+)>\");\n\t\tMatcher matcher = pattern.matcher(line);\n\t\treturn matcher.replaceAll(\"\");\n\t}\n\n\tpublic void log() {\n\t\tEntry list;\n\t\tfor (String time : subtitles.keySet()) {\n\t\t\tlist = subtitles.get(time);\n\t\t\tfor (int i = 0; i < list.size(); i++) {\n\t\t\t\tlog.info(time + \" \" + list.get(i) + \" \");\n\t\t\t}\n\t\t\tlog.info(\"\");\n\t\t}\n\t}\n\n\tpublic Map<String, Entry> getSubtitles() {\n\t\treturn subtitles;\n\t}\n\n\tpublic void resetSubtitles() {\n\t\tsubtitles.clear();\n\t}\n\n\tpublic String getFileName() {\n\t\treturn fileName;\n\t}\n\n\tpublic String getCharset() {\n\t\treturn charset;\n\t}\n\n}",
"public class SrtUtils {\n\n\tprivate static final Logger log = LoggerFactory.getLogger(Merger.class);\n\n\tprivate static final String SPACE = \" \";\n\tprivate static final String HARD_SPACE = \"\\\\h\";\n\n\tpublic static final String SEP_SRT = \" --> \";\n\tpublic static final String SRT_EXT = \".srt\";\n\tpublic static final String TAG_INIT = \"<\";\n\tpublic static final String TAG_END = \">\";\n\tpublic static final String EOL = \"\\r\\n\";\n\tpublic static final String FONT_INIT = \"<font color=\\\"%s\\\">\";\n\tpublic static final String FONT_END = \"%s</font>\";\n\n\tprivate Font font;\n\tprivate FontMetrics fontMetrics;\n\tprivate float maxWidth;\n\tprivate float separatorWidth;\n\tprivate float spaceWidth;\n\tprivate float halfWidth;\n\tprivate String blankLine;\n\tprivate SimpleDateFormat simpleDateFormat;\n\tprivate String padding;\n\tprivate String separator;\n\tprivate boolean usingSpace;\n\tprivate boolean usingSeparator;\n\tprivate boolean horizontal;\n\tprivate String leftColor;\n\tprivate String rightColor;\n\n\tprivate static SrtUtils singleton = null;\n\n\tpublic static SrtUtils getSingleton() {\n\t\tif (singleton == null) {\n\t\t\tsingleton = new SrtUtils();\n\t\t}\n\t\treturn singleton;\n\t}\n\n\t// Default constructor\n\tpublic SrtUtils() {\n\t}\n\n\t@SuppressWarnings(\"deprecation\")\n\tpublic static void init(String maxWidth, String fontFamily, int fontSize,\n\t\t\tboolean space, boolean separator, String separatorChar, int guard,\n\t\t\tboolean horizontal, String leftColor, String rightColor) {\n\t\tlog.debug(\"maxWidth \" + maxWidth + \" fontFamily \" + fontFamily\n\t\t\t\t+ \" fontSize \" + fontSize + \" space \" + space + \" separator \"\n\t\t\t\t+ separator + \" separatorChar \" + separatorChar + \" guard \"\n\t\t\t\t+ guard);\n\t\tSrtUtils srtUtils = getSingleton();\n\t\tsrtUtils.font = new Font(fontFamily, Font.PLAIN, fontSize);\n\t\tsrtUtils.maxWidth = Float.parseFloat(maxWidth) - guard;\n\t\tsrtUtils.fontMetrics = Toolkit.getDefaultToolkit().getFontMetrics(\n\t\t\t\tsrtUtils.font);\n\t\tsrtUtils.simpleDateFormat = new SimpleDateFormat(\"HH:mm:ss,SSS\");\n\t\tsrtUtils.separator = separator ? separatorChar : \"\";\n\t\tsrtUtils.padding = space ? SrtUtils.SPACE : SrtUtils.HARD_SPACE;\n\t\tsrtUtils.usingSpace = space;\n\t\tsrtUtils.usingSeparator = separator;\n\t\tsrtUtils.horizontal = horizontal;\n\t\tsrtUtils.separatorWidth = separator & !horizontal ? getWidth(srtUtils.separator)\n\t\t\t\t: 0;\n\n\t\t// Even if hard space is used, the width of the padding is the same\n\t\t// as the normal space\n\t\tsrtUtils.spaceWidth = getWidth(SPACE);\n\n\t\t// Gap of two characters (space + separator)\n\t\tsrtUtils.halfWidth = (srtUtils.maxWidth / 2) - 2\n\t\t\t\t* (srtUtils.spaceWidth + srtUtils.separatorWidth);\n\n\t\t// Blank line\n\t\tint numSpaces = (int) Math.round(srtUtils.halfWidth / getSpaceWidth());\n\n\t\tif (separator) {\n\t\t\tsrtUtils.blankLine = SrtUtils.getSeparator()\n\t\t\t\t\t+ repeat(SrtUtils.getPadding(), numSpaces)\n\t\t\t\t\t+ SrtUtils.getSeparator();\n\t\t} else {\n\t\t\tsrtUtils.blankLine = repeat(SrtUtils.getPadding(), numSpaces);\n\t\t}\n\t}\n\n\tpublic static int getWidth(String message) {\n\t\tfinal int width = SrtUtils.getSingleton().fontMetrics\n\t\t\t\t.stringWidth(message);\n\t\tlog.debug(\"getWidth \" + message + \" \" + width);\n\t\treturn width;\n\t}\n\n\t/**\n\t * \n\t * @param str\n\t * @param times\n\t * @return\n\t */\n\tpublic static String repeat(String str, int times) {\n\t\treturn new String(new char[times]).replace(\"\\0\", str);\n\t}\n\n\t/**\n\t * It reads the initial time of a subtitle entry\n\t * \n\t * @param line\n\t * @return\n\t * @throws ParseException\n\t */\n\tpublic static Date getInitTime(String line) throws ParseException {\n\t\tDate out = null;\n\t\tint i = line.indexOf(SrtUtils.SEP_SRT);\n\t\tif (i != -1) {\n\t\t\tString time = line.substring(0, i).trim();\n\t\t\tif (time.length() == 8) {\n\t\t\t\t// Time without milliseconds (e.g. 01:27:40)\n\t\t\t\ttime += \",000\";\n\t\t\t}\n\t\t\tout = SrtUtils.getSingleton().parse(time);\n\t\t}\n\t\treturn out;\n\t}\n\n\t/**\n\t * It reads the ending time of a subtitle entry\n\t * \n\t * @param line\n\t * @return\n\t * @throws ParseException\n\t */\n\tpublic static Date getEndTime(String line) throws ParseException {\n\t\tDate out = null;\n\t\tint i = line.indexOf(SrtUtils.SEP_SRT);\n\t\tif (i != -1) {\n\t\t\tString time = line.substring(i + SrtUtils.SEP_SRT.length());\n\t\t\tif (time.length() == 8) {\n\t\t\t\t// Time without milliseconds (e.g. 01:27:40)\n\t\t\t\ttime += \",000\";\n\t\t\t}\n\t\t\tout = SrtUtils.getSingleton().parse(time);\n\n\t\t}\n\t\treturn out;\n\t}\n\n\tpublic static String createSrtTime(Date dateFrom, Date dateTo) {\n\t\treturn SrtUtils.format(dateFrom) + SrtUtils.SEP_SRT\n\t\t\t\t+ SrtUtils.format(dateTo);\n\t}\n\n\tpublic static Font getFont() {\n\t\treturn SrtUtils.getSingleton().font;\n\t}\n\n\tpublic static float getMaxWidth() {\n\t\treturn SrtUtils.getSingleton().maxWidth;\n\t}\n\n\tpublic static FontMetrics getFontMetrics() {\n\t\treturn SrtUtils.getSingleton().fontMetrics;\n\t}\n\n\tpublic static float getSeparatorWidth() {\n\t\treturn SrtUtils.getSingleton().separatorWidth;\n\t}\n\n\tpublic static float getSpaceWidth() {\n\t\treturn SrtUtils.getSingleton().spaceWidth;\n\t}\n\n\tpublic static float getHalfWidth() {\n\t\treturn SrtUtils.getSingleton().halfWidth;\n\t}\n\n\tpublic static String format(Date date) {\n\t\treturn SrtUtils.getSingleton().simpleDateFormat.format(date);\n\t}\n\n\tpublic Date parse(String date) throws ParseException {\n\t\tDate out = null;\n\t\ttry {\n\t\t\tout = SrtUtils.getSingleton().simpleDateFormat.parse(date);\n\t\t} catch (ParseException e) {\n\t\t\tout = new SimpleDateFormat(\"HH:mm:ss.SSS\").parse(date);\n\t\t}\n\t\treturn out;\n\t}\n\n\tpublic static String getBlankLine() {\n\t\treturn SrtUtils.getSingleton().blankLine;\n\t}\n\n\tpublic static String getSeparator() {\n\t\treturn SrtUtils.getSingleton().separator;\n\t}\n\n\tpublic static String getPadding() {\n\t\treturn SrtUtils.getSingleton().padding;\n\t}\n\n\tpublic static boolean isUsingSpace() {\n\t\treturn SrtUtils.getSingleton().usingSpace;\n\t}\n\n\tpublic static boolean isUsingSeparator() {\n\t\treturn SrtUtils.getSingleton().usingSeparator;\n\t}\n\n\tpublic static String getSpace() {\n\t\treturn SrtUtils.SPACE;\n\t}\n\n\tpublic static boolean isHorizontal() {\n\t\treturn SrtUtils.getSingleton().horizontal;\n\t}\n\n\tpublic static String getLeftColor() {\n\t\treturn SrtUtils.getSingleton().leftColor;\n\t}\n\n\tpublic static String getParsedLeftColor() {\n\t\treturn getLeftColor() != null ? String\n\t\t\t\t.format(FONT_INIT, getLeftColor()) + FONT_END : \"%s\";\n\t}\n\n\tpublic static String getRightColor() {\n\t\treturn SrtUtils.getSingleton().rightColor;\n\t}\n\n\tpublic static String getParsedRightColor() {\n\t\treturn getRightColor() != null ? String.format(FONT_INIT,\n\t\t\t\tgetRightColor()) + FONT_END : \"%s\";\n\t}\n\n\tpublic static void setLeftColor(String leftColor) {\n\t\tSrtUtils.getSingleton().leftColor = leftColor;\n\t}\n\n\tpublic static void setRightColor(String rightColor) {\n\t\tSrtUtils.getSingleton().rightColor = rightColor;\n\t}\n\n}",
"public class Charset {\n\n\tpublic static String ISO88591 = \"ISO-8859-1\";\n\tpublic static String UTF8 = \"UTF-8\";\n\n\tprivate static Charset singleton = null;\n\n\tprivate UniversalDetector detector;\n\n\tpublic Charset() {\n\t\tdetector = new UniversalDetector(null);\n\t}\n\n\tpublic static Charset getSingleton() {\n\t\tif (singleton == null) {\n\t\t\tsingleton = new Charset();\n\t\t}\n\t\treturn singleton;\n\t}\n\n\tpublic static String detect(String file) throws IOException {\n\t\tInputStream inputStream = Thread.currentThread()\n\t\t\t\t.getContextClassLoader().getResourceAsStream(file);\n\t\tif (inputStream == null) {\n\t\t\tinputStream = new BufferedInputStream(new FileInputStream(file));\n\t\t}\n\t\treturn Charset.detect(inputStream);\n\t}\n\n\tpublic static String detect(InputStream inputStream) throws IOException {\n\t\tUniversalDetector detector = Charset.getSingleton()\n\t\t\t\t.getCharsetDetector();\n\t\tbyte[] buf = new byte[4096];\n\t\tint nread;\n\t\twhile ((nread = inputStream.read(buf)) > 0 && !detector.isDone()) {\n\t\t\tdetector.handleData(buf, 0, nread);\n\t\t}\n\t\tdetector.dataEnd();\n\t\tString encoding = detector.getDetectedCharset();\n\t\tdetector.reset();\n\t\tinputStream.close();\n\t\tif (encoding == null) {\n\t\t\t// If none encoding is detected, we assume UTF-8\n\t\t\tencoding = UTF8;\n\t\t}\n\t\treturn encoding;\n\t}\n\n\tpublic UniversalDetector getCharsetDetector() {\n\t\treturn detector;\n\t}\n\n}"
] | import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.github.bonigarcia.dualsub.srt.DualSrt;
import io.github.bonigarcia.dualsub.srt.Merger;
import io.github.bonigarcia.dualsub.srt.Srt;
import io.github.bonigarcia.dualsub.srt.SrtUtils;
import io.github.bonigarcia.dualsub.util.Charset;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.util.Properties;
import org.junit.Assert;
import org.junit.Before; | /*
* (C) Copyright 2014 Boni Garcia (http://bonigarcia.github.io/)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package io.github.bonigarcia.dualsub.test;
/**
* TestSynchronization.
*
* @author Boni Garcia (boni.gg@gmail.com)
* @since 1.0.0
*/
public class TestSynchronization {
private static final Logger log = LoggerFactory
.getLogger(TestSynchronization.class);
private Properties properties;
@Before
public void setup() throws IOException {
properties = new Properties();
InputStream inputStream = Thread.currentThread()
.getContextClassLoader()
.getResourceAsStream("dualsub.properties");
properties.load(inputStream);
}
@Test
public void testDesynchronization() throws ParseException, IOException {
// Initial configuration | SrtUtils.init("624", "Tahoma", 17, true, true, ".", 50, false, null, | 3 |
roscrazy/Android-RealtimeUpdate-CleanArchitecture | mvvm/src/main/java/com/mike/feed/mapper/FeedModelMapper.java | [
"public class Deleted {\n}",
"public class Feed {\n private String title;\n private String body;\n private String image;\n private String key;\n private int index;\n\n public String getTitle() {\n return title;\n }\n\n public void setTitle(String title) {\n this.title = title;\n }\n\n public String getBody() {\n return body;\n }\n\n public void setBody(String body) {\n this.body = body;\n }\n\n public String getImage() {\n return image;\n }\n\n public void setImage(String image) {\n this.image = image;\n }\n\n public String getKey() {\n return key;\n }\n\n public void setKey(String key) {\n this.key = key;\n }\n\n public int getIndex() {\n return index;\n }\n\n public void setIndex(int index) {\n this.index = index;\n }\n}",
"public class FeedChangedInfo {\n public enum EventType { Added, Changed, Removed, Moved }\n\n private EventType type;\n private String previousChildKey;\n private String key;\n private Feed feed;\n\n public String getKey() {\n return key;\n }\n\n public void setKey(String key) {\n this.key = key;\n }\n\n public EventType getType() {\n return type;\n }\n\n public void setType(EventType type) {\n this.type = type;\n }\n\n public String getPreviousChildKey() {\n return previousChildKey;\n }\n\n public void setPreviousChildKey(String previousChildKey) {\n this.previousChildKey = previousChildKey;\n }\n\n public Feed getFeed() {\n return feed;\n }\n\n public void setFeed(Feed feed) {\n this.feed = feed;\n }\n}",
"public class Written {\n}",
"public class DeletedModel {\n}",
"public class FeedChangedInfoModel {\n public enum EventType { Added, Changed, Removed, Moved }\n\n private EventType type;\n private String previousChildKey;\n private String key;\n private FeedModel feed;\n\n public EventType getType() {\n return type;\n }\n\n public void setType(EventType type) {\n this.type = type;\n }\n\n public String getPreviousChildKey() {\n return previousChildKey;\n }\n\n public void setPreviousChildKey(String previousChildKey) {\n this.previousChildKey = previousChildKey;\n }\n\n public String getKey() {\n return key;\n }\n\n public void setKey(String key) {\n this.key = key;\n }\n\n public FeedModel getFeed() {\n return feed;\n }\n\n public void setFeed(FeedModel feed) {\n this.feed = feed;\n }\n}",
"public class FeedModel {\n private String title;\n private String body;\n private String image;\n private int index;\n\n public int getIndex() {\n return index;\n }\n\n public void setIndex(int index) {\n this.index = index;\n }\n\n\n public String getTitle() {\n return title;\n }\n\n public void setTitle(String title) {\n this.title = title;\n }\n\n public String getBody() {\n return body;\n }\n\n public void setBody(String body) {\n this.body = body;\n }\n\n public String getImage() {\n return image;\n }\n\n public void setImage(String image) {\n this.image = image;\n }\n}",
"public class WrittenModel {\n\n}"
] | import com.mike.feed.domain.Deleted;
import com.mike.feed.domain.Feed;
import com.mike.feed.domain.FeedChangedInfo;
import com.mike.feed.domain.Written;
import com.mike.feed.model.DeletedModel;
import com.mike.feed.model.FeedChangedInfoModel;
import com.mike.feed.model.FeedModel;
import com.mike.feed.model.WrittenModel;
import javax.inject.Inject;
import javax.inject.Singleton; | package com.mike.feed.mapper;
/**
* Created by MinhNguyen on 8/24/16.
*/
@Singleton
public class FeedModelMapper {
@Inject
public FeedModelMapper(){
}
| public Feed transform(FeedModel entity){ | 6 |
shagwood/micro-genie | micro-genie-dw-service/src/main/java/io/microgenie/service/AppConfiguration.java | [
"public abstract class ApplicationFactory implements Closeable{\n\n\tpublic ApplicationFactory(){}\n\n\tpublic abstract EventFactory events();\n\tpublic abstract QueueFactory queues();\n\tpublic abstract FileStoreFactory blobs();\n\tpublic abstract <T extends DatabaseFactory> T database();\n}",
"public class StateChangeConfiguration{\n\tprivate Map<String, Map<String, String>> events;\n\tpublic StateChangeConfiguration(){}\n\tpublic StateChangeConfiguration(final Map<String, Map<String, String>> events){\n\t\tthis.events = events;\n\t}\n\tpublic Map<String, Map<String, String>> getEvents() {\n\t\treturn events;\n\t}\n\tpublic void setEvents(Map<String, Map<String, String>> events) {\n\t\tthis.events = events;\n\t}\n}",
"public class AwsApplicationFactory extends ApplicationFactory {\n\n\n\tprivate final ObjectMapper mapper;\n\tprivate final AwsConfig config;\n\n\tprivate S3BlobFactory files;\n\tprivate KinesisEventFactory events;\n\tprivate SqsFactory queues;\n\tprivate DynamoDbMapperFactory databases;\n\n\t/** Amazon Clients **/\n\tprivate AmazonDynamoDBClient dynamoClient;\n\tprivate AmazonCloudWatchClient cloudwatchClient;\n\tprivate AmazonKinesisClient kinesisClient;\n\tprivate AmazonSQSClient sqsClient;\n\tprivate AmazonS3Client s3Client;\n\n\t/**\n\t * Default Constructor to close thread group factory\n\t * \n\t * @param config\n\t * - AWS configuration\n\t */\n\tpublic AwsApplicationFactory(final AwsConfig config,final ObjectMapper mapper) {\n\t\tthis.config = config;\n\t\tthis.mapper = mapper;\n\t\tthis.createConfiguredFactories(config);\n\t}\n\n\t/***\n\t * Implementations that subclass {@link AwsApplicationFactory} should\n\t * override this method to create implementation specific factories for\n\t * events, http, queues, etc.. where an AWS service is not being used.\n\t * \n\t * @param config\n\t */\n\tprotected void createConfiguredFactories(final AwsConfig config) {\n\n\t\t\n\t\t/*** Create any clients that have been configured **/\n\t\tif (config != null) {\n\t\t\t\n\t\t\tif (config.getKinesis() != null || config.getDynamo() != null) {\n\n\t\t\t\t/** both kinesis and dynamodb rely on the AmazonDynamoDbClient **/\n\t\t\t\tthis.dynamoClient = new AmazonDynamoDBClient();\n\t\t\t\t\n\t\t\t\t/** Kinesis KCL uses the cloudwatchClient **/\n\t\t\t\tif (this.config.getKinesis() != null) {\n\t\t\t\t\tthis.kinesisClient = new AmazonKinesisClient();\n\t\t\t\t\tthis.cloudwatchClient = new AmazonCloudWatchClient();\n\t\t\t\t\tevents = new KinesisEventFactory(kinesisClient, this.dynamoClient, this.cloudwatchClient, this.mapper);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif (config.getS3() != null) {\n\t\t\t\tthis.s3Client = new AmazonS3Client();\n\t\t\t\tfiles = new S3BlobFactory(this.s3Client, config.getS3().getDefaultDrive());\n\t\t\t}\n\t\t\tif (config.getDynamo() != null) {\n\t\t\t\tdatabases = new DynamoDbMapperFactory(this.dynamoClient);\n\t\t\t}\n\t\t\tif (config.getSqs() != null) {\n\t\t\t\tthis.sqsClient = new AmazonSQSClient();\n\t\t\t\tqueues = new SqsFactory(this.sqsClient, config.getSqs());\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tpublic EventFactory events() {\n\t\treturn events;\n\t}\n\n\t@Override\n\tpublic QueueFactory queues() {\n\t\treturn queues;\n\t}\n\n\t@Override\n\tpublic FileStoreFactory blobs() {\n\t\treturn files;\n\t}\n\n\t\n\t@SuppressWarnings(\"unchecked\")\n\t@Override\n\tpublic <T extends DatabaseFactory> T database() {\n\t\treturn (T)databases;\n\t}\n\n\t@Override\n\tpublic void close() {\n\n\t\tCloseableUtil.closeQuietly(databases);\n\t\tCloseableUtil.closeQuietly(files);\n\t\tCloseableUtil.closeQuietly(queues);\n\t\tCloseableUtil.closeQuietly(events);\n\t\t\n\t\tif (this.kinesisClient != null) {\n\t\t\tthis.kinesisClient.shutdown();\n\t\t}\n\t\tif (this.cloudwatchClient != null) {\n\t\t\tthis.cloudwatchClient.shutdown();\n\t\t}\n\t\tif (this.sqsClient != null) {\n\t\t\tthis.sqsClient.shutdown();\n\t\t}\n\t\tif (this.dynamoClient != null) {\n\t\t\tthis.dynamoClient.shutdown();\n\t\t}\n\t\tif (this.kinesisClient != null) {\n\t\t\tthis.kinesisClient.shutdown();\n\t\t}\n\t\tif (this.s3Client != null) {\n\t\t\tthis.s3Client.shutdown();\n\t\t}\n\t}\n}",
"public class AwsConfig {\n\t\n\tprivate String region;\n\tprivate String accessKey;\n\tprivate String secretKey;\n\tprivate DynamoDbConfig dynamo;\n\tprivate SqsConfig sqs;\n\tprivate List<KinesisConfig> kinesis;\n\tprivate S3Config s3;\n\t\n\t\n\tpublic AwsConfig(){}\n\t\n\t\n\t@JsonProperty(\"region\")\n\tpublic String getRegion() {\n\t\treturn region;\n\t}\n\t@JsonProperty(\"region\")\n\tpublic void setRegion(String region) {\n\t\tthis.region = region;\n\t}\n\t@JsonProperty(\"accessKey\")\n\tpublic String getAccessKey() {\n\t\treturn accessKey;\n\t}\n\t@JsonProperty(\"accessKey\")\n\tpublic void setAccessKey(String accessKey) {\n\t\tthis.accessKey = accessKey;\n\t}\n\t@JsonProperty(\"secretKey\")\n\tpublic String getSecretKey() {\n\t\treturn secretKey;\n\t}\n\t@JsonProperty(\"secretKey\")\n\tpublic void setSecretKey(String secretKey) {\n\t\tthis.secretKey = secretKey;\n\t}\n\t@JsonProperty(\"s3\")\n\tpublic S3Config getS3() {\n\t\treturn s3;\n\t}\n\t@JsonProperty(\"s3\")\n\tpublic void setS3(S3Config s3) {\n\t\tthis.s3 = s3;\n\t}\n\t@JsonProperty(\"dynamo\")\n\tpublic DynamoDbConfig getDynamo() {\n\t\treturn dynamo;\n\t}\n\t@JsonProperty(\"dynamo\")\n\tpublic void setDynamo(DynamoDbConfig dynamo) {\n\t\tthis.dynamo = dynamo;\n\t}\n\t@JsonProperty(\"kinesis\")\n\tpublic List<KinesisConfig> getKinesis() {\n\t\treturn kinesis;\n\t}\n\t@JsonProperty(\"kinesis\")\n\tpublic void setKinesis(List<KinesisConfig> kinesis) {\n\t\tthis.kinesis = kinesis;\n\t}\n\t@JsonProperty(\"sqs\")\n\tpublic SqsConfig getSqs() {\n\t\treturn sqs;\n\t}\n\t@JsonProperty(\"sqs\")\n\tpublic void setSqs(SqsConfig sqs) {\n\t\tthis.sqs = sqs;\n\t}\n\t\n\t\n\tpublic static class AwsConfigBuilder{\n\t\tprivate String region;\n\t\tprivate String accessKey;\n\t\tprivate String secretKey;\n\t\tprivate DynamoDbConfig dynamo;\n\t\tprivate SqsConfig sqs;\n\t\tprivate List<KinesisConfig> kinesis;\n\t\tprivate S3Config s3;\n\n\t\tpublic AwsConfigBuilder withRegion(final String region){\n\t\t\tthis.region = region;\n\t\t\treturn this;\n\t\t}\n\t\t\n\t\tpublic AwsConfigBuilder withAccessKey(final String accessKey){\n\t\t\tthis.accessKey = accessKey;\n\t\t\treturn this;\n\t\t}\n\t\t\n\t\tpublic AwsConfigBuilder withSecretKey(final String secretKey){\n\t\t\tthis.secretKey = secretKey;\n\t\t\treturn this;\n\t\t}\n\t\t\n\t\tpublic AwsConfigBuilder withDynamo(final DynamoDbConfig dynamo){\n\t\t\tthis.dynamo = dynamo;\n\t\t\treturn this;\n\t\t}\n\t\t\n\t\t\n\t\tpublic AwsConfigBuilder withSqs(final SqsConfig sqs){\n\t\t\tthis.sqs = sqs;\n\t\t\treturn this;\n\t\t}\n\t\t\n\t\t\n\t\tpublic AwsConfigBuilder withKinesis(final KinesisConfig ...kinesis){\n\t\t\tif(this.kinesis==null){\n\t\t\t\tthis.kinesis = Lists.newArrayList(kinesis);\n\t\t\t}else{\n\t\t\t\tthis.kinesis.addAll(Lists.newArrayList(kinesis));\n\t\t\t}\n\t\t\treturn this;\n\t\t}\n\t\t\n\t\tpublic AwsConfigBuilder withS3(final S3Config s3){\n\t\t\tthis.s3 = s3;\n\t\t\treturn this;\n\t\t}\n\t\t\n\t\t\n\t\tpublic AwsConfig build(){\n\t\t\tfinal AwsConfig config = new AwsConfig();\n\t\t\tconfig.setRegion(this.region);\n\t\t\tconfig.setAccessKey(this.accessKey);\n\t\t\tconfig.setSecretKey(this.secretKey);\n\t\t\tconfig.setDynamo(this.dynamo);\n\t\t\tconfig.setKinesis(this.kinesis);\n\t\t\tconfig.setSqs(this.sqs);\n\t\t\tconfig.setS3(this.s3);\n\t\t\treturn config;\n\t\t}\n\t}\n}",
"public class CommandConfiguration extends Configuration{\n\n\t@JsonProperty(value=\"consume\")\n\tprivate KinesisConsumerConfig kinesisConsumer;\n\t\n\tpublic static class KinesisConsumerConfig{\n\t\tprivate String topic;\n\t\tprivate String clientId;\n\t\t@JsonProperty(value=\"topic\")\n\t\tpublic String getTopic() {\n\t\t\treturn topic;\n\t\t}\n\t\t@JsonProperty(value=\"topic\")\n\t\tpublic void setTopic(String topic) {\n\t\t\tthis.topic = topic;\n\t\t}\n\t\t@JsonProperty(value=\"clientId\")\n\t\tpublic String getClientId() {\n\t\t\treturn clientId;\n\t\t}\n\t\t@JsonProperty(value=\"clientId\")\n\t\tpublic void setClientId(String clientId) {\n\t\t\tthis.clientId = clientId;\n\t\t}\n\t}\n\n\t@JsonProperty(value=\"kinesisConsumer\")\n\tpublic KinesisConsumerConfig getKinesisConsumer() {\n\t\treturn kinesisConsumer;\n\t}\n\t@JsonProperty(value=\"kinesisConsumer\")\n\tpublic void setKinesisConsumer(KinesisConsumerConfig kinesisConsumer) {\n\t\tthis.kinesisConsumer = kinesisConsumer;\n\t}\n}"
] | import io.dropwizard.Configuration;
import io.microgenie.application.ApplicationFactory;
import io.microgenie.application.StateChangeConfiguration;
import io.microgenie.aws.AwsApplicationFactory;
import io.microgenie.aws.config.AwsConfig;
import io.microgenie.service.commands.CommandConfiguration;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper; | package io.microgenie.service;
/***
* Application Configuration Factory
* <p>
* This class contains common configuration elements to configure micro-genie service
* functionality
* @author shawn
*/
public class AppConfiguration extends Configuration {
private static final String ISO_8601_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
private String dateFormat = ISO_8601_DATE_FORMAT; /** default to ISO 8601 UTC date format **/
private ApiConfiguration api;
private StateChangeConfiguration stateChanges;
private CommandConfiguration commands; | private AwsConfig aws; | 3 |
jrimum/domkee | src/main/java/org/jrimum/domkee/financeiro/banco/febraban/Banco.java | [
"public class NumeroDeTelefone{\r\n\r\n\tprivate int ddi;\r\n\r\n\tprivate int ddd;\r\n\r\n\tprivate int prefixo;\r\n\r\n\tprivate int sufixo;\r\n\t\r\n\tprivate String telefone;\r\n\r\n\tpublic NumeroDeTelefone() {}\r\n\t\r\n\tpublic int getDDI() {\r\n\t\treturn ddi;\r\n\t}\r\n\r\n\tpublic void setDDI(int ddi) {\r\n\t\tthis.ddi = ddi;\r\n\t}\r\n\r\n\tpublic int getDDD() {\r\n\t\treturn ddd;\r\n\t}\r\n\r\n\tpublic void setDDD(int ddd) {\r\n\t\tthis.ddd = ddd;\r\n\t}\r\n\r\n\tpublic int getPrefixo() {\r\n\t\treturn prefixo;\r\n\t}\r\n\r\n\tpublic void setPrefixo(int prefixo) {\r\n\t\tthis.prefixo = prefixo;\r\n\t}\r\n\r\n\tpublic int getSufixo() {\r\n\t\treturn sufixo;\r\n\t}\r\n\r\n\tpublic void setSufixo(int sufixo) {\r\n\t\tthis.sufixo = sufixo;\r\n\t}\r\n\t\r\n\tpublic String getTelefone() {\r\n\t\treturn telefone;\r\n\t}\r\n\r\n\tpublic void setTelefone(String telefone) {\r\n\t\tthis.telefone = telefone;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic String toString() {\r\n\t\treturn Objects.toString(this);\r\n\t}\r\n}\r",
"public class Endereco {\r\n\r\n\t/**\r\n\t * Nome da rua, avenida, etc.\r\n\t */\r\n\tprivate String logradouro;\r\n\t\r\n\t/**\r\n\t * Número que identifica o lugar no logradouro (ex: número da casa).\r\n\t */\r\n\tprivate String numero;\r\n\t\r\n\t/**\r\n\t * Informação adicional para identificar o estabelecimento na rua.\r\n\t */\r\n\tprivate String complemento;\r\n\t\r\n\t/**\r\n\t * Cada uma das divisões de uma cidade ou povoação.\r\n\t */\r\n\tprivate String bairro;\r\n\t\r\n\t/**\r\n\t * Cidade, município, etc.\r\n\t */\r\n\tprivate String localidade;\r\n\t\r\n\t/**\r\n\t * @see CEP\r\n\t */\r\n\tprivate CEP cep;\r\n\t\r\n\t/**\r\n\t * @see UnidadeFederativa\r\n\t */\r\n\tprivate UnidadeFederativa uf;\r\n\t\r\n\tprivate String pais;\r\n\t\t\r\n\tpublic Endereco() {}\r\n\r\n\tpublic String getBairro() {\r\n\t\treturn bairro;\r\n\t}\r\n\r\n\tpublic void setBairro(String bairro) {\r\n\t\tthis.bairro = bairro;\r\n\t}\r\n\r\n\t/**\r\n\t * @return the localidade\r\n\t */\r\n\tpublic String getLocalidade() {\r\n\t\treturn localidade;\r\n\t}\r\n\r\n\t/**\r\n\t * @param localidade the localidade to set\r\n\t */\r\n\tpublic void setLocalidade(String localidade) {\r\n\t\tthis.localidade = localidade;\r\n\t}\r\n\r\n\tpublic String getLogradouro() {\r\n\t\treturn logradouro;\r\n\t}\r\n\r\n\tpublic void setLogradouro(String logradouro) {\r\n\t\tthis.logradouro = logradouro;\r\n\t}\r\n\r\n\tpublic String getNumero() {\r\n\t\treturn numero;\r\n\t}\r\n\r\n\tpublic void setNumero(String numero) {\r\n\t\tthis.numero = numero;\r\n\t}\r\n\r\n\tpublic UnidadeFederativa getUF() {\r\n\t\treturn uf;\r\n\t}\r\n\r\n\tpublic void setUF(UnidadeFederativa uf) {\r\n\t\tthis.uf = uf;\r\n\t}\r\n\r\n\tpublic String getComplemento() {\r\n\t\treturn complemento;\r\n\t}\r\n\r\n\tpublic void setComplemento(String complemento) {\r\n\t\tthis.complemento = complemento;\r\n\t}\r\n\r\n\tpublic CEP getCEP() {\r\n\t\treturn cep;\r\n\t}\r\n\r\n\tpublic void setCep(CEP cep) {\r\n\t\tthis.cep = cep;\r\n\t}\r\n\t\r\n\tpublic void setCep(String cep) {\r\n\t\tsetCep(new CEP(cep));\r\n\t}\r\n\r\n\t/**\r\n\t * @return the pais\r\n\t */\r\n\tpublic String getPais() {\r\n\t\treturn pais;\r\n\t}\r\n\r\n\t/**\r\n\t * @param pais the pais to set\r\n\t */\r\n\tpublic void setPais(String pais) {\r\n\t\tthis.pais = pais;\r\n\t}\r\n\t\r\n\t@Override\r\n\tpublic String toString() {\r\n\t\treturn Objects.toString(this);\r\n\t}\r\n}\r",
"public class CNPJ extends AbstractCPRF {\r\n\r\n\tpublic CNPJ(Long numCNPJ) {\r\n\r\n\t\ttry {\r\n\r\n\t\t\tif (AbstractCPRFValidator.isParametrosValidos(\r\n\t\t\t\t\tString.valueOf(numCNPJ), TipoDeCPRF.CNPJ)) {\r\n\r\n\t\t\t\tthis.autenticadorCP = AbstractCPRFValidator.create(fillWithZeroLeft(numCNPJ, 14));\r\n\r\n\t\t\t\tif (autenticadorCP.isValido()){\r\n\t\t\t\t\t\r\n\t\t\t\t\tinitFromNumber(numCNPJ);\r\n\t\t\t\t\t\r\n\t\t\t\t}else{\r\n\t\t\t\t\t\r\n\t\t\t\t\tExceptions.throwIllegalArgumentException(\"O cadastro de pessoa [ \\\"\" + numCNPJ+ \"\\\" ] não é válido.\");\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t} catch (Exception e) {\r\n\t\t\tif (!(e instanceof CNPJException))\r\n\t\t\t\tthrow new CNPJException(e);\r\n\t\t}\r\n\r\n\t}\r\n\r\n\tpublic CNPJ(String strCNPJ) {\r\n\r\n\t\tthis.autenticadorCP = AbstractCPRFValidator.create(strCNPJ);\r\n\r\n\t\tif (autenticadorCP.isValido()) {\r\n\t\t\t\r\n\t\t\tif(isNumeric(strCNPJ)){\r\n\t\t\t\t\r\n\t\t\t\tinitFromNotFormattedString(strCNPJ);\r\n\t\t\t\t\r\n\t\t\t}else{\r\n\t\t\t\t\r\n\t\t\t\tinitFromFormattedString(strCNPJ);\r\n\t\t\t\t\r\n\t\t\t}\r\n\t\t\t\r\n\t\t} else {\r\n\t\t\tthrow new CNPJException(new IllegalArgumentException(\r\n\t\t\t\t\t\"O cadastro de pessoa [ \\\"\" + strCNPJ + \"\\\" ] não é válido.\"));\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic boolean isMatriz(){\r\n\t\t\r\n\t\treturn getSufixoFormatado().equals(\"0001\");\r\n\t}\r\n\t\r\n\tpublic boolean isSufixoEquals(String sufixoFormatado){\r\n\t\t\r\n\t\tStrings.checkNotNumeric(sufixoFormatado, String.format(\"O sufixo [%s] deve ser um número natural diferente de zero!\", sufixoFormatado));\r\n\t\t\r\n\t\treturn isSufixoEquals(Integer.valueOf(sufixoFormatado));\r\n\t}\r\n\r\n\tpublic boolean isSufixoEquals(Integer sufixo){\r\n\t\t\r\n\t\tObjects.checkNotNull(sufixo,\"Sufixo nulo!\");\r\n\t\tObjects.checkArgument(sufixo > 0, String.format(\"O sufixo [%s] deve ser um número natural diferente de zero!\", sufixo));\r\n\t\t\r\n\t\treturn getSufixo().equals(sufixo);\r\n\t}\r\n\t\r\n\tpublic Integer getSufixo(){\r\n\t\t\r\n\t\treturn Integer.valueOf(getSufixoFormatado());\r\n\t}\r\n\t\r\n\tpublic String getSufixoFormatado(){\r\n\t\t\r\n\t\treturn getCodigoFormatado().split(\"-\")[0].split(\"/\")[1];\r\n\t}\r\n\r\n\tprivate void initFromNumber(Long numCNPJ) {\r\n\r\n\t\ttry {\r\n\r\n\t\t\tthis.setCodigoFormatado(format(fillWithZeroLeft(numCNPJ, 14)));\r\n\t\t\tthis.setCodigo(numCNPJ);\r\n\r\n\t\t} catch (Exception e) {\r\n\t\t\tthrow new CNPJException(e);\r\n\t\t}\r\n\t}\r\n\tprivate void initFromFormattedString(String strCNPJ) {\r\n\t\t\r\n\t\ttry {\r\n\t\t\t\r\n\t\t\tthis.setCodigoFormatado(strCNPJ);\r\n\t\t\tthis.setCodigo(Long.parseLong(removeFormat(strCNPJ)));\r\n\t\t\t\r\n\t\t} catch (Exception e) {\r\n\t\t\tthrow new CNPJException(e);\r\n\t\t}\r\n\t}\r\n\t\r\n\tprivate void initFromNotFormattedString(String strCNPJ) {\r\n\t\t\r\n\t\ttry {\r\n\t\t\t\r\n\t\t\tthis.setCodigoFormatado(format(strCNPJ));\r\n\t\t\tthis.setCodigo(Long.parseLong(strCNPJ));\r\n\t\t\t\r\n\t\t} catch (Exception e) {\r\n\t\t\tthrow new CNPJException(e);\r\n\t\t}\r\n\t}\r\n\r\n\tprivate String format(String strCNPJ) {\r\n\t\t\r\n\t\tStringBuilder codigoFormatado = new StringBuilder(strCNPJ);\r\n\t\t\r\n\t\tcodigoFormatado.insert(2, '.');\r\n\t\tcodigoFormatado.insert(6, '.');\r\n\t\tcodigoFormatado.insert(10, '/');\r\n\t\tcodigoFormatado.insert(15, '-');\r\n\t\t\r\n\t\treturn codigoFormatado.toString();\r\n\t}\r\n\r\n\tprivate String removeFormat(String codigo) {\r\n\r\n\t\tcodigo = codigo.replace(\".\", \"\");\r\n\t\tcodigo = codigo.replace(\"/\", \"\");\r\n\t\tcodigo = codigo.replace(\"-\", \"\");\r\n\r\n\t\treturn codigo;\r\n\t}\r\n\t\r\n}\r",
"public interface CPRF extends Comparable<Object>{\r\n\r\n\tpublic boolean isFisica();\r\n\r\n\tpublic boolean isJuridica();\r\n\r\n\tpublic Long getCodigo();\r\n\r\n\tpublic String getCodigoComZeros();\r\n\t\r\n\tpublic String getCodigoFormatado();\r\n\t\r\n\tpublic Long getRaiz();\r\n\r\n\tpublic String getRaizComZeros();\r\n\t\r\n\tpublic String getRaizFormatada();\r\n\t\r\n\tpublic Integer getDv();\r\n\r\n\tpublic String getDvComZeros();\r\n}\r",
"public class Pessoa implements org.jrimum.domkee.comum.pessoa.Pessoa {\r\n\t\r\n\tprivate String nome;\r\n\t\r\n\t/**\r\n\t * @see CPRF\r\n\t */\r\n\tprivate CPRF cprf;\r\n\t\r\n\t/**\r\n\t * @see NumeroDeTelefone\r\n\t */\r\n\tprivate Collection<NumeroDeTelefone> telefones;\r\n\t\r\n\t/**\r\n\t * @see Endereco\r\n\t */\r\n\tprivate Collection<Endereco> enderecos;\r\n\t\r\n\t/**\r\n\t * @see ContaBancaria\r\n\t */\r\n\tprivate Collection<ContaBancaria> contasBancarias;\r\n\t\r\n\tpublic Pessoa() {}\r\n\t\r\n\tpublic Pessoa(String nome) {\r\n\t\t\r\n\t\tthis.nome = nome;\r\n\t}\r\n\r\n\tpublic Pessoa(String nome, String cadastroDePessoa) {\r\n\t\t\r\n\t\tthis.nome = nome;\r\n\t\tthis.cprf = AbstractCPRF.create(cadastroDePessoa);\r\n\t}\r\n\t\r\n\tpublic Pessoa(String nome, CPRF cadastroDePessoa) {\r\n\t\t\r\n\t\tthis.nome = nome;\r\n\t\tthis.cprf = cadastroDePessoa;\r\n\t}\r\n\r\n\t/**\r\n\t * @see ContaBancaria\r\n\t */\r\n\tpublic void addContaBancaria(ContaBancaria contaBancaria) {\r\n\t\t\r\n\t\tif(isNull(contasBancarias)){\r\n\t\t\t\r\n\t\t\tcontasBancarias = new ArrayList<ContaBancaria>();\r\n\t\t}\r\n\t\t\r\n\t\tcontasBancarias.add(contaBancaria);\r\n\t}\r\n\t\r\n\t/** \r\n\t * Verifica se esta pessoa tem alguma conta bancária.\r\n\t * \r\n\t * @see ContaBancaria\r\n\t */\r\n\t\r\n\tpublic boolean hasContaBancaria(){\r\n\t\t\r\n\t\treturn hasElement(getContasBancarias());\r\n\t}\r\n\t\r\n\t/**\r\n\t * @see Endereco\r\n\t */\r\n\tpublic void addEndereco(Endereco endereco) {\r\n\r\n\t\tif(isNull(enderecos)){\r\n\t\t\t\r\n\t\t\tenderecos = new ArrayList<Endereco>();\r\n\t\t}\r\n\t\t\r\n\t\tenderecos.add(endereco);\r\n\t}\r\n\r\n\t/**\r\n\t * @see NumeroDeTelefone\r\n\t */\r\n\tpublic void addTelefone(NumeroDeTelefone telefone) {\r\n\t\t\r\n\t\tif(isNull(telefones)){\r\n\t\t\t\r\n\t\t\ttelefones = new ArrayList<NumeroDeTelefone>();\r\n\t\t}\r\n\t\t\r\n\t\ttelefones.add(telefone);\r\n\t}\r\n\r\n\t/**\r\n\t * @see CPRF\r\n\t */\r\n\t\r\n\tpublic CPRF getCPRF() {\r\n\t\t\r\n\t\treturn cprf;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Retorna o resultado de uma chamada a {@code iterator.next()} de\r\n\t * {@linkplain #getContasBancarias()}, caso exista alguma conta, ou null, caso\r\n\t * não exista {@linkplain #contasBancarias}.\r\n\t * \r\n\t * @return Chamada a {@code iterator.next()}, caso exista algum endereço ou\r\n\t * null.\r\n\t */\r\n\tpublic ContaBancaria getNextContaBancaria(){\r\n\t\t\r\n\t\tif(hasElement(getContasBancarias())){\r\n\t\t\r\n\t\t\treturn getContasBancarias().iterator().next();\r\n\t\t}\r\n\t\t\r\n\t\treturn null; \r\n\t}\r\n\r\n\t/**\r\n\t * @see ContaBancaria\r\n\t * @see Collection\r\n\t */\r\n\tpublic Collection<ContaBancaria> getContasBancarias() {\r\n\r\n\t\treturn contasBancarias;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Retorna o resultado de uma chamada a {@code iterator.next()} de\r\n\t * {@linkplain #getEnderecos()}, caso exista algum endereço, ou null, caso\r\n\t * não exista {@linkplain #enderecos}.\r\n\t * \r\n\t * @return Chamada a {@code iterator.next()}, caso exista algum endereço ou\r\n\t * null.\r\n\t */\r\n\tpublic Endereco getNextEndereco(){\r\n\t\t\r\n\t\tif(hasElement(getEnderecos())){\r\n\t\t\r\n\t\t\treturn getEnderecos().iterator().next();\r\n\t\t}\r\n\t\t\r\n\t\treturn null; \r\n\t}\r\n\r\n\t/**\r\n\t * @see Endereco\r\n\t * @see Collection\r\n\t */\r\n\tpublic Collection<Endereco> getEnderecos() {\r\n\r\n\t\treturn enderecos;\r\n\t}\r\n\t\r\n\tpublic String getNome() {\r\n\r\n\t\treturn nome;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Retorna o resultado de uma chamada a {@code iterator.next()} de\r\n\t * {@linkplain #getTelefones()}, caso exista algum telefone, ou null, caso\r\n\t * não exista {@linkplain #telefones}.\r\n\t * \r\n\t * @return Chamada a {@code iterator.next()}, caso exista algum endereço ou\r\n\t * null.\r\n\t */\r\n\tpublic NumeroDeTelefone getNextTelefone(){\r\n\t\t\r\n\t\tif(hasElement(getTelefones())){\r\n\t\t\r\n\t\t\treturn getTelefones().iterator().next();\r\n\t\t}\r\n\t\t\r\n\t\treturn null; \r\n\t}\r\n\r\n\t/**\r\n\t * @see NumeroDeTelefone\r\n\t * @see Collection\r\n\t */\r\n\tpublic Collection<NumeroDeTelefone> getTelefones() {\r\n\t\t\r\n\t\treturn telefones;\r\n\t}\r\n\r\n\t/**\r\n\t * @see CPRF\r\n\t */\r\n\tpublic void setCPRF(CPRF cprf) {\r\n\t\t\r\n\t\tthis.cprf = cprf;\r\n\t}\r\n\r\n\t/**\r\n\t * @see ContaBancaria\r\n\t * @see Collection\r\n\t */\r\n\tpublic void setContasBancarias(Collection<ContaBancaria> contasBancarias) {\r\n\t\t\r\n\t\tthis.contasBancarias = contasBancarias;\r\n\t}\r\n\r\n\t/**\r\n\t * @see Endereco\r\n\t * @see Collection\r\n\t */\r\n\tpublic void setEnderecos(Collection<Endereco> enderecos) {\r\n\t\t\r\n\t\tthis.enderecos = enderecos;\r\n\t}\r\n\r\n\tpublic void setNome(String nome) {\r\n\t\r\n\t\tthis.nome = nome;\r\n\t}\r\n\r\n\t/**\r\n\t * @see NumeroDeTelefone\r\n\t * @see Collection\r\n\t */\r\n\tpublic void setTelefones(Collection<NumeroDeTelefone> telefones) {\r\n\t\t\r\n\t\tthis.telefones = telefones;\r\n\t}\r\n\r\n\t/** \r\n\t * Verifica se esta pessoa é uma instância de <code>PessoaFisica</code>.\r\n\t * \r\n\t * @see org.jrimum.domkee.comum.pessoa.Pessoa#isFisica()\r\n\t */\r\n\tpublic boolean isFisica() {\r\n\t\t\r\n\t\treturn (this instanceof PessoaFisica);\r\n\t}\r\n\r\n\t/** \r\n\t * Verifica se esta pessoa é uma instância de <code>PessoaJuridica</code>.\r\n\t * \r\n\t * @see org.jrimum.domkee.comum.pessoa.Pessoa#isJuridica()\r\n\t */\r\n\tpublic boolean isJuridica() {\r\n\t\t\r\n\t\treturn (this instanceof PessoaJuridica);\r\n\t}\r\n\t\r\n\t@Override\r\n\tpublic String toString() {\r\n\t\treturn Objects.toString(this);\r\n\t}\r\n}\r",
"public class PessoaJuridica extends Pessoa implements org.jrimum.domkee.comum.pessoa.PessoaJuridica {\r\n\r\n\tprivate Long inscricaoEstadual;\r\n\t\r\n\tprivate Long inscricaoMunicipal;\r\n\t\r\n\t/**\r\n\t * Título do estabelecimento, diferente do <code>nome</code> (NOME EMPRESARIAL). \r\n\t */\r\n\tprivate String nomeFantasia;\r\n\r\n\t\r\n\tpublic Long getInscricaoEstadual() {\r\n\r\n\t\treturn inscricaoEstadual;\r\n\t}\r\n\r\n\t\r\n\tpublic Long getInscricaoMunicipal() {\r\n\r\n\t\treturn inscricaoMunicipal;\r\n\t}\r\n\r\n\t\r\n\tpublic String getNomeFantasia() {\r\n\r\n\t\treturn nomeFantasia;\r\n\t}\r\n\r\n\t\r\n\tpublic void setInscricaoEstadual(Long inscricaoEstadual) {\r\n\r\n\t\tthis.inscricaoEstadual = inscricaoEstadual;\r\n\t}\r\n\r\n\t\r\n\tpublic void setInscricaoMunicipal(Long inscricaoMunicipal) {\r\n\r\n\t\tthis.inscricaoMunicipal = inscricaoMunicipal;\r\n\t}\r\n\r\n\t\r\n\tpublic void setNomeFantasia(String nomeFantasia) {\r\n\r\n\t\tthis.nomeFantasia = nomeFantasia;\r\n\t}\r\n\r\n}\r"
] | import java.awt.Image;
import java.util.Collection;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.log4j.Logger;
import org.jrimum.domkee.comum.pessoa.contato.NumeroDeTelefone;
import org.jrimum.domkee.comum.pessoa.endereco.Endereco;
import org.jrimum.domkee.comum.pessoa.id.cprf.CNPJ;
import org.jrimum.domkee.comum.pessoa.id.cprf.CPRF;
import org.jrimum.domkee.financeiro.banco.Pessoa;
import org.jrimum.domkee.financeiro.banco.PessoaJuridica;
import static org.jrimum.utilix.Objects.isNotNull;
| /*
* Copyright 2008 JRimum Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by
* applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
* OF ANY KIND, either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*
* Created at: 30/03/2008 - 18:57:43
*
* ================================================================================
*
* Direitos autorais 2008 JRimum Project
*
* Licenciado sob a Licença Apache, Versão 2.0 ("LICENÇA"); você não pode usar
* esse arquivo exceto em conformidade com a esta LICENÇA. Você pode obter uma
* cópia desta LICENÇA em http://www.apache.org/licenses/LICENSE-2.0 A menos que
* haja exigência legal ou acordo por escrito, a distribuição de software sob
* esta LICENÇA se dará “COMO ESTÁ”, SEM GARANTIAS OU CONDIÇÕES DE QUALQUER
* TIPO, sejam expressas ou tácitas. Veja a LICENÇA para a redação específica a
* reger permissões e limitações sob esta LICENÇA.
*
* Criado em: 30/03/2008 - 18:57:43
*
*/
package org.jrimum.domkee.financeiro.banco.febraban;
/**
*
* <p>
* Um Banco (instituição financeira) supervisionada pelo <a href="http://www.bcb.gov.br/">BACEN</a>.
* </p>
*
* @author <a href="http://gilmatryx.googlepages.com/">Gilmar P.S.L.</a>
*
* @since 0.2
*
* @version 0.2
*/
public class Banco implements org.jrimum.domkee.financeiro.banco.Banco {
private static Logger log = Logger.getLogger(Banco.class);
private CodigoDeCompensacaoBACEN codigoDeCompensacaoBACEN;
private String segmento;
private Image imgLogo;
| private PessoaJuridica pessoaJuridica;
| 5 |
1gravity/Android-ContactPicker | library/src/main/java/com/onegravity/contactpicker/core/PagerAdapter.java | [
"public enum ContactDescription {\n PHONE,\n EMAIL,\n ADDRESS;\n\n public static ContactDescription lookup(String name) {\n try {\n return ContactDescription.valueOf(name);\n }\n catch (IllegalArgumentException ignore) {\n Log.e(ContactDescription.class.getSimpleName(), ignore.getMessage());\n return ADDRESS;\n }\n }\n\n}",
"public class ContactFragment extends BaseFragment {\n\n private static final String REQUEST_SORT_ORDER = \"sortOrder\";\n private static final String REQUEST_PICTURE_TYPE = \"pictureType\";\n private static final String REQUEST_CONTACT_DESCRIPTION = \"contactDescription\";\n private static final String REQUEST_DESCRIPTION_TYPE = \"descriptionType\";\n\n private ContactSortOrder mSortOrder;\n private ContactPictureType mPictureType;\n private ContactDescription mDescription;\n private int mDescriptionType;\n\n /**\n * The list of all contacts.\n * This is only used as a reference to the original data set while we actually use\n * mFilteredContacts.\n */\n private List<? extends Contact> mContacts = new ArrayList<>();\n\n /**\n * The list of all visible and filtered contacts.\n */\n private List<? extends Contact> mFilteredContacts = new ArrayList<>();\n\n private ContactAdapter mAdapter;\n\n public static ContactFragment newInstance(ContactSortOrder sortOrder,\n ContactPictureType pictureType,\n ContactDescription contactDescription,\n int descriptionType) {\n Bundle args = new Bundle();\n args.putString(REQUEST_SORT_ORDER, sortOrder.name());\n args.putString(REQUEST_PICTURE_TYPE, pictureType.name());\n args.putString(REQUEST_CONTACT_DESCRIPTION, contactDescription.name());\n args.putInt(REQUEST_DESCRIPTION_TYPE, descriptionType);\n ContactFragment fragment = new ContactFragment();\n fragment.setArguments(args);\n return fragment;\n }\n\n public ContactFragment() {}\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n Bundle args = getArguments();\n mSortOrder = ContactSortOrder.lookup( args.getString(REQUEST_SORT_ORDER) );\n mPictureType = ContactPictureType.lookup( args.getString(REQUEST_PICTURE_TYPE) );\n mDescription = ContactDescription.lookup( args.getString(REQUEST_CONTACT_DESCRIPTION) );\n mDescriptionType = args.getInt(REQUEST_DESCRIPTION_TYPE);\n }\n\n @Override\n public final View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {\n mAdapter = new ContactAdapter(getContext(), null, mSortOrder, mPictureType, mDescription, mDescriptionType);\n\n View rootLayout = super.createView(inflater, R.layout.cp_contact_list, mAdapter, mContacts);\n\n // configure fast scroll\n RecyclerView recyclerView = (RecyclerView) rootLayout.findViewById(android.R.id.list);\n VerticalRecyclerViewFastScroller fastScroller = (VerticalRecyclerViewFastScroller) rootLayout.findViewById(R.id.fast_scroller);\n fastScroller.setRecyclerView(recyclerView);\n recyclerView.addOnScrollListener(fastScroller.getOnScrollListener());\n\n // configure section indexer\n SectionTitleIndicator sectionTitleIndicator = (SectionTitleIndicator ) rootLayout.findViewById(R.id.fast_scroller_section_title_indicator);\n fastScroller.setSectionIndicator(sectionTitleIndicator);\n\n return rootLayout;\n }\n\n @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)\n public void onEventMainThread(ContactsLoaded event) {\n EventBus.getDefault().removeStickyEvent(event);\n\n mContacts = event.getContacts();\n mFilteredContacts = mContacts;\n mAdapter.setData(mFilteredContacts);\n\n updateEmptyViewVisibility(mContacts);\n }\n\n @Override\n protected void checkAll() {\n if (mFilteredContacts == null) return;\n\n // determine if all contacts are checked\n boolean allChecked = true;\n for (Contact contact : mFilteredContacts) {\n if (! contact.isChecked()) {\n allChecked = false;\n break;\n }\n }\n\n // if all are checked then un-check the contacts, otherwise check them all\n boolean isChecked = ! allChecked;\n for (Contact contact : mFilteredContacts) {\n if (contact.isChecked() != isChecked) {\n contact.setChecked(isChecked, true);\n\n }\n }\n\n ContactSelectionChanged.post();\n\n mAdapter.notifyDataSetChanged();\n }\n\n @Override\n protected void performFiltering(String[] queryStrings) {\n if (mContacts == null) return;\n\n if (queryStrings == null || queryStrings.length == 0) {\n mFilteredContacts = mContacts;\n }\n else {\n List<Contact> filteredElements = new ArrayList<>();\n for (Contact contact : mContacts) {\n if (contact.matchesQuery(queryStrings)) {\n filteredElements.add(contact);\n }\n }\n mFilteredContacts = filteredElements;\n }\n\n mAdapter.setData(mFilteredContacts);\n }\n\n}",
"public enum ContactSortOrder {\n FIRST_NAME, // sort by first name\n LAST_NAME, // sort by last name\n AUTOMATIC; // sort by display name (device specific)\n\n public static ContactSortOrder lookup(String name) {\n try {\n return ContactSortOrder.valueOf(name);\n }\n catch (IllegalArgumentException ignore) {\n Log.e(ContactSortOrder.class.getSimpleName(), ignore.getMessage());\n return AUTOMATIC;\n }\n }\n\n}",
"public class GroupFragment extends BaseFragment {\n\n /**\n * The list of all visible groups.\n * This is only used as a reference to the original data set while we actually use\n * mFilteredGroups.\n */\n private List<? extends Group> mGroups = new ArrayList<>();\n\n /**\n * The list of all visible and filtered groups.\n */\n private List<? extends Group> mFilteredGroups = new ArrayList<>();\n\n private GroupAdapter mAdapter;\n\n public static GroupFragment newInstance() {\n return new GroupFragment();\n }\n\n public GroupFragment() {}\n\n @Override\n public final View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {\n mAdapter = new GroupAdapter(null);\n return super.createView(inflater, R.layout.cp_group_list, mAdapter, mGroups);\n }\n\n @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)\n public void onEventMainThread(GroupsLoaded event) {\n EventBus.getDefault().removeStickyEvent(event);\n\n mGroups = event.getGroups();\n mFilteredGroups = mGroups;\n mAdapter.setData(mFilteredGroups);\n\n updateEmptyViewVisibility(mGroups);\n }\n\n @Override\n protected void checkAll() {\n if (mFilteredGroups == null) return;\n\n // determine if all groups are checked\n boolean allChecked = true;\n for (Group group : mFilteredGroups) {\n if (! group.isChecked()) {\n allChecked = false;\n break;\n }\n }\n\n // if all are checked then un-check the groups, otherwise check them all\n boolean isChecked = ! allChecked;\n for (Group group : mFilteredGroups) {\n if (group.isChecked() != isChecked) {\n group.setChecked(isChecked, false);\n }\n }\n\n mAdapter.notifyDataSetChanged();\n }\n\n @Override\n protected void performFiltering(String[] queryStrings) {\n if (mGroups == null) return;\n\n if (queryStrings == null || queryStrings.length == 0) {\n mFilteredGroups = mGroups;\n }\n else {\n List<Group> filteredElements = new ArrayList<>();\n for (Group group : mGroups) {\n if (group.matchesQuery(queryStrings)) {\n filteredElements.add(group);\n }\n }\n mFilteredGroups = filteredElements;\n }\n\n mAdapter.setData(mFilteredGroups);\n }\n\n}",
"public enum ContactPictureType {\n NONE,\n ROUND,\n SQUARE;\n\n public static ContactPictureType lookup(String name) {\n try {\n return ContactPictureType.valueOf(name);\n }\n catch (IllegalArgumentException ignore) {\n Log.e(ContactPictureType.class.getSimpleName(), ignore.getMessage());\n return ROUND;\n }\n }\n\n}"
] | import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import com.onegravity.contactpicker.contact.ContactDescription;
import com.onegravity.contactpicker.contact.ContactFragment;
import com.onegravity.contactpicker.contact.ContactSortOrder;
import com.onegravity.contactpicker.group.GroupFragment;
import com.onegravity.contactpicker.picture.ContactPictureType; | /*
* Copyright (C) 2015-2017 Emanuel Moecklin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.onegravity.contactpicker.core;
public class PagerAdapter extends FragmentStatePagerAdapter {
final private int mNumOfTabs;
final private ContactSortOrder mSortOrder;
final private ContactPictureType mBadgeType;
final private ContactDescription mDescription;
final private int mDescriptionType;
public PagerAdapter(FragmentManager fm, int numOfTabs, ContactSortOrder sortOrder,
ContactPictureType badgeType, ContactDescription description, int descriptionType) {
super(fm);
mNumOfTabs = numOfTabs;
mSortOrder = sortOrder;
mBadgeType = badgeType;
mDescription = description;
mDescriptionType = descriptionType;
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0: | return ContactFragment.newInstance(mSortOrder, mBadgeType, mDescription, mDescriptionType); | 1 |
hlavki/g-suite-identity-sync | services/synchronize/api/src/main/java/eu/hlavki/identity/services/sync/impl/AccountSyncServiceImpl.java | [
"public interface AppConfiguration {\n\n Optional<String> getExternalAccountsGroup();\n\n\n void setExternalAccountsGroup(String groupName);\n}",
"public interface GSuiteDirectoryService {\n\n /**\n * Retrieve all groups for a member.\n *\n * @param userKey The userKey can be the user's primary email address, the user's alias email address, a\n * group's primary email address, a group's email alias, or the user's unique id.\n * @return all groups for a member\n */\n GroupList getUserGroups(String userKey);\n\n\n /**\n * Read basic group information. This result does not contain group members. Call\n * {@link #getGroupMembers(java.lang.String)} to obtain members.\n *\n * @param groupKey group identifier (email or ID)\n * @return group info\n * @throws eu.hlavki.identity.services.google.ResourceNotFoundException\n */\n GSuiteGroup getGroup(String groupKey) throws ResourceNotFoundException;\n\n\n /**\n * Read all members for group.\n *\n * @param groupKey group identifier (email or ID)\n * @return group info and members\n */\n GroupMembership getGroupMembers(String groupKey) throws ResourceNotFoundException;\n\n\n /**\n * Read all GSuite groups. This result does not contain group members. Call\n * {@link #getGroupMembers(java.lang.String)} to obtain members.\n *\n * @return all GSuite groups\n */\n GroupList getAllGroups();\n\n\n /**\n * Read members for all GSuite groups. Because it is very expesive operation, you can use cached values.\n * Cache expires in 15 minutes. To use cache set useCache parameter to true.\n *\n *\n * @return members for all GSuite groups. Key is group info object and value is membership\n */\n Map<GSuiteGroup, GroupMembership> getAllGroupMembership();\n\n\n /**\n * Retrieves a gsuite user from Directory API\n *\n * @param userKey Identifies the user in the API request. The value can be the user's primary email\n * address, alias email address, or unique user ID.\n * @return gsuite user\n */\n GSuiteUser getUser(String userKey);\n\n\n /**\n * Retrieves list of users or all users in a domain.\n *\n * @return list of gsuite users\n */\n GSuiteUsers getAllUsers();\n\n\n void updateUserPassword(String userKey, String password) throws InvalidPasswordException;\n\n\n String getDomainName();\n\n\n String getImplicitGroup();\n\n\n String completeGroupEmail(String groupName);\n}",
"public class ResourceNotFoundException extends RuntimeException {\n\n private static final long serialVersionUID = 1L;\n\n\n public ResourceNotFoundException() {\n }\n\n\n public ResourceNotFoundException(String message) {\n super(message);\n }\n\n\n public ResourceNotFoundException(String message, Throwable cause) {\n super(message, cause);\n }\n\n\n public ResourceNotFoundException(Throwable cause) {\n super(cause);\n }\n\n\n public ResourceNotFoundException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {\n super(message, cause, enableSuppression, writableStackTrace);\n }\n}",
"public interface LdapAccountService {\n\n boolean accountExists(String subject);\n\n\n Optional<LdapAccount> getAccountBySubject(String subject);\n\n\n Optional<LdapAccount> getAccountByEmail(String email);\n\n\n List<LdapAccount> searchAccounts(Role role);\n\n\n List<LdapAccount> getAllAccounts();\n\n\n void createAccount(LdapAccount account);\n\n\n void updateAccount(LdapAccount account);\n\n\n LdapGroup getGroup(String groupName);\n\n\n Set<String> getAllGroupNames();\n\n\n List<LdapGroup> getAccountGroups(String accountDN);\n\n\n String getAccountDN(String subject);\n\n\n String getAccountDN(LdapAccount account);\n\n\n void addGroupMember(String accountDN, String groupName);\n\n\n void deleteGroupMember(String accountDN, String groupName);\n\n\n void deleteGroup(String name);\n\n\n LdapGroup createOrUpdateGroup(LdapGroup group);\n\n\n void deleteUser(LdapAccount account);\n\n\n void deleteUserByEmail(String email);\n}",
"@Getter\n@Setter\n@NoArgsConstructor\npublic class LdapAccount {\n\n public enum Role {\n EXTERNAL, INTERNAL\n }\n\n private String dn;\n private String name;\n private String givenName;\n private String familyName;\n private String username;\n private String subject;\n private Set<String> emails;\n private String password;\n private Role role;\n\n\n public LdapAccount(String dn) {\n this.dn = dn;\n }\n\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder(\"[\");\n sb.append(\"givenName=\").append(givenName).\n append(\", familyName=\").append(familyName).\n append(\", name=\").append(name).\n append(\", username=\").append(username).\n append(\", subject=\").append(subject).\n append(\", emails=\").append(emails).\n append(\", role=\").append(role).append(\"]\");\n return sb.toString();\n }\n\n public String getValueByAttr(String attr) {\n switch (attr) {\n case \"cn\": return getName();\n case \"uid\": return getUsername();\n default: return null;\n }\n }\n}",
"public class LdapGroup {\n\n private String name;\n private String dn;\n private String description;\n private Set<String> membersDn;\n\n\n public LdapGroup() {\n }\n\n\n public LdapGroup(String name, String dn, String description, Set<String> members) {\n this.name = name;\n this.dn = dn;\n this.membersDn = members;\n }\n\n\n public String getName() {\n return name;\n }\n\n\n public void setName(String name) {\n this.name = name;\n }\n\n\n public String getDn() {\n return dn;\n }\n\n\n public void setDn(String dn) {\n this.dn = dn;\n }\n\n\n /**\n * Return set of membersDn DN.\n *\n * @return set of membersDn DN.\n */\n public Set<String> getMembersDn() {\n return membersDn;\n }\n\n\n public void setMembersDn(Set<String> membersDn) {\n this.membersDn = membersDn;\n }\n\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder(\"[\");\n sb.append(\"name=\").append(name).append(\", dn=\").append(dn).\n append(\", membersDN=\").append(membersDn).append(\", desc=\").append(description).append(\"]\");\n return sb.toString();\n }\n\n\n public String getDescription() {\n return description;\n }\n\n\n public void setDescription(String description) {\n this.description = description;\n }\n}",
"public interface AccountSyncService {\n\n void synchronizeUserGroups(UserInfo userInfo);\n\n\n void synchronizeGroup(String groupEmail) throws ResourceNotFoundException;\n\n\n void removeGroup(String groupEmail);\n\n\n void synchronizeAllGroups();\n\n\n void synchronizeGSuiteUser(String email);\n\n\n void synchronizeGSuiteUsers();\n\n\n void removeUserByEmail(String email);\n\n\n void cleanExternalUsers();\n}",
"public static final boolean isInternalAccount(UserInfo info, String gsuiteDomain) {\n return gsuiteDomain.equals(info.getProperty(\"hd\"));\n}"
] | import eu.hlavki.identity.services.config.AppConfiguration;
import eu.hlavki.identity.services.google.GSuiteDirectoryService;
import eu.hlavki.identity.services.google.ResourceNotFoundException;
import eu.hlavki.identity.services.google.model.*;
import eu.hlavki.identity.services.ldap.LdapAccountService;
import eu.hlavki.identity.services.ldap.model.LdapAccount;
import eu.hlavki.identity.services.ldap.model.LdapGroup;
import eu.hlavki.identity.services.sync.AccountSyncService;
import static eu.hlavki.identity.services.sync.impl.AccountUtil.isInternalAccount;
import java.util.*;
import static java.util.Collections.emptySet;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.toSet;
import org.apache.cxf.rs.security.oidc.common.UserInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | package eu.hlavki.identity.services.sync.impl;
public class AccountSyncServiceImpl implements AccountSyncService {
private static final Logger LOG = LoggerFactory.getLogger(AccountSyncServiceImpl.class);
private final LdapAccountService ldapService;
private final GSuiteDirectoryService gsuiteDirService;
private final AppConfiguration appConfig;
public AccountSyncServiceImpl(LdapAccountService ldapService, GSuiteDirectoryService gsuiteDirService,
AppConfiguration appConfig) {
this.ldapService = ldapService;
this.gsuiteDirService = gsuiteDirService;
this.appConfig = appConfig;
}
@Override
public void synchronizeUserGroups(UserInfo userInfo) {
String accountDN = ldapService.getAccountDN(userInfo.getSubject());
GroupList gsuiteGroups = gsuiteDirService.getUserGroups(userInfo.getSubject());
List<LdapGroup> ldapGroups = ldapService.getAccountGroups(accountDN);
Set<String> asIs = ldapGroups.stream()
.filter(g -> g.getMembersDn().contains(accountDN))
.map(g -> g.getDn())
.collect(Collectors.toSet());
List<GSuiteGroup> gg = gsuiteGroups.getGroups() != null ? gsuiteGroups.getGroups() : Collections.emptyList();
Set<String> toBe = gg.stream()
.map(group -> AccountUtil.getLdapGroupName(group))
.collect(Collectors.toSet());
// Workaround for implicit group mapping
boolean implicitGroup = gsuiteDirService.getImplicitGroup() != null;
if (isInternalAccount(userInfo, gsuiteDirService.getDomainName()) && implicitGroup) {
toBe.add(AccountUtil.getLdapGroupName(gsuiteDirService.getImplicitGroup()));
}
Set<String> toRemove = new HashSet<>(asIs);
toRemove.removeAll(toBe);
Set<String> toAdd = new HashSet<>(toBe);
toAdd.removeAll(asIs);
LOG.info("Remove membership for user {} from groups {}", userInfo.getEmail(), toRemove);
LOG.info("Add membership for user {} to groups {}", userInfo.getEmail(), toAdd);
for (String group : toRemove) {
ldapService.deleteGroupMember(accountDN, group);
}
for (String group : toAdd) {
ldapService.addGroupMember(accountDN, group);
}
}
@Override
public void synchronizeAllGroups() {
Map<GSuiteGroup, GroupMembership> gsuiteGroups = gsuiteDirService.getAllGroupMembership();
Set<String> ldapGroups = ldapService.getAllGroupNames();
GSuiteUsers allGsuiteUsers = gsuiteDirService.getAllUsers();
| Map<String, LdapAccount> emailAccountMap = new HashMap<>(); | 4 |
CraftedCart/SMBLevelWorkshop | src/main/java/craftedcart/smblevelworkshop/ui/component/transform/PlaceableScaleTextFields.java | [
"public class Placeable implements Cloneable, ITransformable {\n\n @NotNull private IAsset asset;\n\n @NotNull private PosXYZ position = new PosXYZ();\n @NotNull private PosXYZ rotation = new PosXYZ();\n @NotNull private PosXYZ scale = new PosXYZ(1, 1, 1);\n\n public Placeable(@NotNull IAsset asset) {\n this.asset = asset;\n }\n\n public Placeable(@NotNull Goal goal) {\n asset = new AssetGoal();\n position = new PosXYZ(goal.pos);\n rotation = new PosXYZ(goal.rot);\n\n String type;\n switch (goal.type) {\n case BLUE:\n type = \"blueGoal\";\n break;\n case GREEN:\n type = \"greenGoal\";\n break;\n case RED:\n type = \"redGoal\";\n break;\n default:\n //This shouldn't happen! Default to blue\n type = \"blueGoal\";\n }\n\n asset.setType(type);\n }\n\n public Placeable(@NotNull Bumper bumper) {\n asset = new AssetBumper();\n position = new PosXYZ(bumper.pos);\n rotation = new PosXYZ(bumper.rot);\n scale = new PosXYZ(bumper.scl);\n }\n\n public Placeable(@NotNull Jamabar jamabar) {\n asset = new AssetJamabar();\n position = new PosXYZ(jamabar.pos);\n rotation = new PosXYZ(jamabar.rot);\n scale = new PosXYZ(jamabar.scl);\n }\n\n public Placeable(@NotNull Banana banana) {\n asset = new AssetBanana();\n position = new PosXYZ(banana.pos);\n\n String type;\n switch (banana.type) {\n case SINGLE:\n type = \"singleBanana\";\n break;\n case BUNCH:\n type = \"bunchBanana\";\n break;\n default:\n //This shouldn't happen! Default to single\n type = \"singleBanana\";\n }\n\n asset.setType(type);\n }\n\n public Placeable(@NotNull Wormhole wormhole) {\n AssetWormhole aWormhole = new AssetWormhole();\n asset = aWormhole;\n position = new PosXYZ(wormhole.pos);\n rotation = new PosXYZ(wormhole.rot);\n aWormhole.setDestinationName(wormhole.destinationName);\n }\n\n public void setAsset(@NotNull IAsset asset) {\n this.asset = asset;\n }\n\n @NotNull\n public IAsset getAsset() {\n return asset;\n }\n\n public void setPosition(@NotNull PosXYZ position) {\n this.position = position;\n }\n\n @NotNull\n public PosXYZ getPosition() {\n return position;\n }\n\n @Override\n public boolean canMoveX() {\n return getAsset().canGrabX();\n }\n\n @Override\n public boolean canMoveY() {\n return getAsset().canGrabY();\n }\n\n @Override\n public boolean canMoveZ() {\n return getAsset().canGrabZ();\n }\n\n @Override\n public boolean canRotate() {\n return getAsset().canRotate();\n }\n\n @Override\n public boolean canScale() {\n return getAsset().canScale();\n }\n\n public void setRotation(@NotNull PosXYZ rotation) {\n this.rotation = rotation;\n }\n\n @NotNull\n public PosXYZ getRotation() {\n return rotation;\n }\n\n public void setScale(@NotNull PosXYZ scale) {\n this.scale = scale;\n }\n\n @NotNull\n public PosXYZ getScale() {\n return scale;\n }\n\n public Placeable getCopy() {\n try {\n IAsset newAsset = asset.getCopy();\n Placeable newPlaceable = (Placeable) clone();\n newPlaceable.setAsset(newAsset);\n return newPlaceable;\n } catch (CloneNotSupportedException e) {\n LogHelper.error(getClass(), \"Failed to clone Placeable\");\n LogHelper.error(getClass(), e);\n return null;\n }\n }\n\n}",
"public class ProjectManager {\n\n private static Project currentProject;\n\n public static void setCurrentProject(Project currentProject) {\n ProjectManager.currentProject = currentProject;\n }\n\n public static Project getCurrentProject() {\n return currentProject;\n }\n\n public static LevelData getCurrentLevelData() {\n return getCurrentProject().clientLevelData.getLevelData();\n }\n\n public static ClientLevelData getCurrentClientLevelData() {\n return getCurrentProject().clientLevelData;\n }\n\n}",
"public class LangManager {\n\n // <Locale, <Key , Value >>\n @NotNull private static Map<String, Map<String, String>> localeMap = new HashMap<>();\n @NotNull private static String selectedLang = \"en_US\";\n\n /**\n * Add an item given a locale, key and value\n *\n * @param locale The language locale (eg: en_US)\n * @param key The identifier\n * @param value The translated string\n */\n public static void addItem(String locale, String key, String value) {\n if (localeMap.containsKey(locale)) {\n Map<String, String> langMap = localeMap.get(locale);\n langMap.put(key, value);\n localeMap.put(locale, langMap);\n } else {\n Map<String, String> langMap = new HashMap<>();\n langMap.put(key, value);\n localeMap.put(locale, langMap);\n }\n }\n\n /**\n * Get a translated string, given a locale and key\n *\n * @param locale The language locale (eg: en_US)\n * @param key The identifier\n * @return The translated string, or the key if the entry wasn't found\n */\n public static String getItem(String locale, String key) {\n if (localeMap.containsKey(locale)) {\n if (localeMap.get(locale).containsKey(key)) {\n return localeMap.get(locale).get(key);\n } else {\n return key;\n }\n } else {\n return key;\n }\n }\n\n public static String getItem(String key) {\n return getItem(selectedLang, key);\n }\n\n public static void setSelectedLang(@NotNull String selectedLang) {\n LangManager.selectedLang = selectedLang;\n }\n\n @NotNull\n public static String getSelectedLang() {\n return selectedLang;\n }\n\n}",
"public class MainScreen extends FluidUIScreen {\n\n private static final double TIMELINE_HEIGHT = 136;\n\n //Camera\n @NotNull private PosXYZ cameraPos = new PosXYZ(5, 5, 5);\n @NotNull private PosXY cameraRot = new PosXY(-45, 35);\n\n //UI\n private final Image modeCursor = new Image();\n private final Component mainUI = new Component();\n private final Label modeLabel = new Label();\n private final Label modeDirectionLabel = new Label();\n private final Panel notifPanel = new Panel();\n private final Timeline timeline = new Timeline(this);\n private final Panel onScreenCameraControlsPanel = new Panel();\n private final FPSOverlay fpsOverlay = new FPSOverlay();\n\n private EnumObjectMode objectMode = EnumObjectMode.PLACEABLE_EDIT;\n\n //UI: Left Panel\n public final Panel addPlaceablePanel = new Panel();\n public final Panel outlinerPlaceablesPanel = new Panel();\n public final ListBox outlinerPlaceablesListBox = new ListBox();\n public final Panel outlinerObjectsPanel = new Panel();\n public final ListBox outlinerObjectsListBox = new ListBox();\n\n private final TextButton importObjButton = new TextButton();\n private final TextButton importConfigButton = new TextButton();\n private final TextButton exportButton = new TextButton();\n private final TextButton settingsButton = new TextButton();\n private final TextButton projectSettingsButton = new TextButton();\n\n //UI: Placeable Properties\n private final ListBox propertiesPlaceablesListBox = new ListBox();\n private final ListBox propertiesObjectsListBox = new ListBox();\n\n private final PlaceableScaleTextFields placeableScaleTextFields = new PlaceableScaleTextFields(this, null);\n private final PlaceableRotationTextFields placeableRotationTextFields = new PlaceableRotationTextFields(this, placeableScaleTextFields.getFirstTextField());\n private final PlaceablePositionTextFields placeablePositionTextFields = new PlaceablePositionTextFields(this, placeableRotationTextFields.getFirstTextField());\n\n private final TextButton typeButton = new TextButton();\n @Nullable private List<String> typeList = null;\n\n private final TextButton placeableItemGroupButton = new TextButton();\n\n //UI: Object Properties\n private final TextButton objectItemGroupButton = new TextButton();\n\n //UI: Text Fields\n private Set<TextField> textFields;\n\n //UI: Input Overlay\n private final InputOverlay inputOverlay = new InputOverlay();\n\n //Undo\n @NotNull private List<UndoCommand> undoCommandList = new ArrayList<>();\n @NotNull private List<UndoCommand> redoCommandList = new ArrayList<>();\n\n private boolean preventRendering = false; //Used when unloading textures and VBOs\n private boolean isLoadingProject = false; //Just in case disabling the button is too slow\n\n //Notifications\n private int notificationID = 0;\n\n //Mouse & Scroll Wheel Delta (For snapping)\n private double deltaX = 0;\n\n //Locks\n private final Object outlinerPlaceablesListBoxLock = new Object();\n private final Object outlinerObjectsListBoxLock = new Object();\n private final Object renderingLock = new Object();\n\n private final Set<UIAction> nextFrameActions = new HashSet<>();\n\n public MainScreen() {\n init();\n }\n\n private void init() {\n\n if (textFields == null) {\n textFields = new HashSet<>();\n }\n\n try {\n Window.drawable.makeCurrent();\n } catch (LWJGLException e) {\n e.printStackTrace();\n }\n\n //Defined at class level\n modeCursor.setOnInitAction(() -> {\n modeCursor.setTopLeftPos(-16, -16);\n modeCursor.setBottomRightPos(16, 16);\n modeCursor.setTopLeftAnchor(0.5, 0.5);\n modeCursor.setBottomRightAnchor(0.5, 0.5);\n modeCursor.setVisible(false);\n modeCursor.setTexture(ResourceManager.getTexture(\"image/modeEditCursor\").getTexture());\n modeCursor.setColor(UIColor.matGreen());\n });\n addChildComponent(\"modeCursor\", modeCursor);\n\n //Defined at class level\n mainUI.setOnInitAction(() -> {\n mainUI.setTopLeftPos(0, 0);\n mainUI.setBottomRightPos(0, 0);\n mainUI.setTopLeftAnchor(0, 0);\n mainUI.setBottomRightAnchor(1, 1);\n mainUI.setTheme(new DefaultUITheme());\n });\n addChildComponent(\"mainUI\", mainUI);\n\n //<editor-fold desc=\"Bottom Panel\">\n final Panel bottomPanel = new Panel();\n bottomPanel.setOnInitAction(() -> {\n bottomPanel.setBackgroundColor(UIColor.matGrey900(0.75));\n bottomPanel.setTopLeftPos(260, -50 - TIMELINE_HEIGHT);\n bottomPanel.setBottomRightPos(-260, -4 - TIMELINE_HEIGHT);\n bottomPanel.setTopLeftAnchor(0, 1);\n bottomPanel.setBottomRightAnchor(1, 1);\n });\n mainUI.addChildComponent(\"bottomPanel\", bottomPanel);\n //</editor-fold>\n\n //<editor-fold desc=\"ProjectManager.getCurrentProject().mode Label\">\n //Defined at class level\n modeLabel.setOnInitAction(() -> {\n modeLabel.setTopLeftPos(4, 0);\n modeLabel.setBottomRightPos(-4, 24);\n modeLabel.setTopLeftAnchor(0, 0);\n modeLabel.setBottomRightAnchor(1, 0);\n modeLabel.setTextColor(UIColor.matWhite());\n });\n bottomPanel.addChildComponent(\"modeLabel\", modeLabel);\n //</editor-fold>\n\n //<editor-fold desc=\"ProjectManager.getCurrentProject().mode Direction Label\">\n //Defined at class level\n modeDirectionLabel.setOnInitAction(() -> {\n modeDirectionLabel.setTopLeftPos(4, 24);\n modeDirectionLabel.setBottomRightPos(-4, 48);\n modeDirectionLabel.setTopLeftAnchor(0, 0);\n modeDirectionLabel.setBottomRightAnchor(1, 0);\n });\n bottomPanel.addChildComponent(\"modeDirectionLabel\", modeDirectionLabel);\n //</editor-fold>\n\n final Panel leftPanel = new Panel();\n leftPanel.setOnInitAction(() -> {\n leftPanel.setBackgroundColor(UIColor.matGrey900(0.75));\n leftPanel.setTopLeftPos(0, 0);\n leftPanel.setBottomRightPos(256, 0 - TIMELINE_HEIGHT);\n leftPanel.setTopLeftAnchor(0, 0);\n leftPanel.setBottomRightAnchor(0, 1);\n });\n mainUI.addChildComponent(\"leftPanel\", leftPanel);\n\n //<editor-fold desc=\"Placeables / Objects mode buttons\">\n final TextButton outlinerPlaceablesTabButton = new TextButton();\n final TextButton outlinerObjectsTabButton = new TextButton();\n\n //Defined above\n outlinerPlaceablesTabButton.setOnInitAction(() -> {\n outlinerPlaceablesTabButton.setTopLeftPos(0, 0);\n outlinerPlaceablesTabButton.setBottomRightPos(-1, 24);\n outlinerPlaceablesTabButton.setTopLeftAnchor(0, 0);\n outlinerPlaceablesTabButton.setBottomRightAnchor(0.5, 0);\n outlinerPlaceablesTabButton.setText(LangManager.getItem(\"placeables\"));\n outlinerPlaceablesTabButton.setBackgroundIdleColor(UIColor.matBlue900());\n });\n outlinerPlaceablesTabButton.setOnLMBAction(() -> {\n outlinerPlaceablesTabButton.setBackgroundIdleColor(UIColor.matBlue900());\n outlinerObjectsTabButton.setBackgroundIdleColor(UIColor.matBlue());\n\n addPlaceablePanel.setVisible(true);\n outlinerPlaceablesPanel.setVisible(true);\n outlinerObjectsPanel.setVisible(false);\n\n propertiesPlaceablesListBox.setVisible(true);\n propertiesObjectsListBox.setVisible(false);\n\n if (ProjectManager.getCurrentProject() != null && ProjectManager.getCurrentClientLevelData() != null) {\n ProjectManager.getCurrentClientLevelData().clearSelectedObjects();\n }\n\n objectMode = EnumObjectMode.PLACEABLE_EDIT;\n });\n leftPanel.addChildComponent(\"outlinerPlaceablesTabButton\", outlinerPlaceablesTabButton);\n\n //Defined above\n outlinerObjectsTabButton.setOnInitAction(() -> {\n outlinerObjectsTabButton.setTopLeftPos(1, 0);\n outlinerObjectsTabButton.setBottomRightPos(0, 24);\n outlinerObjectsTabButton.setTopLeftAnchor(0.5, 0);\n outlinerObjectsTabButton.setBottomRightAnchor(1, 0);\n outlinerObjectsTabButton.setText(LangManager.getItem(\"objects\"));\n outlinerObjectsTabButton.setBackgroundIdleColor(UIColor.matBlue());\n });\n outlinerObjectsTabButton.setOnLMBAction(() -> {\n outlinerPlaceablesTabButton.setBackgroundIdleColor(UIColor.matBlue());\n outlinerObjectsTabButton.setBackgroundIdleColor(UIColor.matBlue900());\n\n addPlaceablePanel.setVisible(false);\n outlinerPlaceablesPanel.setVisible(false);\n outlinerObjectsPanel.setVisible(true);\n\n propertiesPlaceablesListBox.setVisible(false);\n propertiesObjectsListBox.setVisible(true);\n\n if (ProjectManager.getCurrentProject() != null && ProjectManager.getCurrentClientLevelData() != null) {\n ProjectManager.getCurrentClientLevelData().clearSelectedPlaceables();\n }\n\n objectMode = EnumObjectMode.OBJECT_EDIT;\n });\n leftPanel.addChildComponent(\"outlinerObjectsTabButton\", outlinerObjectsTabButton);\n //</editor-fold>\n\n //Defined at class level\n addPlaceablePanel.setOnInitAction(() -> {\n addPlaceablePanel.setTopLeftPos(0, 24);\n addPlaceablePanel.setBottomRightPos(0, 168);\n addPlaceablePanel.setTopLeftAnchor(0, 0);\n addPlaceablePanel.setBottomRightAnchor(1, 0);\n addPlaceablePanel.setBackgroundColor(UIColor.transparent());\n });\n leftPanel.addChildComponent(\"addPlaceablePanel\", addPlaceablePanel);\n\n final Label addPlaceableLabel = new Label();\n addPlaceableLabel.setOnInitAction(() -> {\n addPlaceableLabel.setText(LangManager.getItem(\"addPlaceable\"));\n addPlaceableLabel.setHorizontalAlign(EnumHAlignment.centre);\n addPlaceableLabel.setVerticalAlign(EnumVAlignment.centre);\n addPlaceableLabel.setTopLeftPos(4, 0);\n addPlaceableLabel.setBottomRightPos(-4, 24);\n addPlaceableLabel.setTopLeftAnchor(0, 0);\n addPlaceableLabel.setBottomRightAnchor(1, 0);\n });\n addPlaceablePanel.addChildComponent(\"addPlaceableLabel\", addPlaceableLabel);\n\n final ListBox addPlaceableListBox = new ListBox();\n addPlaceableListBox.setOnInitAction(() -> {\n addPlaceableListBox.setBackgroundColor(UIColor.transparent());\n addPlaceableListBox.setTopLeftPos(0, 24);\n addPlaceableListBox.setBottomRightPos(0, 0);\n addPlaceableListBox.setTopLeftAnchor(0, 0);\n addPlaceableListBox.setBottomRightAnchor(1, 1);\n addPlaceableListBox.setCanScroll(false);\n });\n addPlaceablePanel.addChildComponent(\"addPlaceableListBox\", addPlaceableListBox);\n\n //<editor-fold desc=\"Add placeable buttons\">\n for (IAsset asset : AssetManager.getAvaliableAssets()) {\n final TextButton placeableButton = new TextButton();\n placeableButton.setOnInitAction(() -> {\n placeableButton.setText(LangManager.getItem(asset.getName()));\n placeableButton.setTopLeftPos(0, 0);\n placeableButton.setBottomRightPos(0, 18);\n });\n placeableButton.setOnLMBAction(() -> addPlaceable(new Placeable(asset.getCopy())));\n addPlaceableListBox.addChildComponent(asset.getName() + \"AddPlaceableButton\", placeableButton);\n }\n //</editor-fold>\n\n //<editor-fold desc=\"Outliner placeables panel\">\n //Defined at class level\n outlinerPlaceablesPanel.setOnInitAction(() -> {\n outlinerPlaceablesPanel.setTopLeftPos(0, 168);\n outlinerPlaceablesPanel.setBottomRightPos(0, 0);\n outlinerPlaceablesPanel.setTopLeftAnchor(0, 0);\n outlinerPlaceablesPanel.setBottomRightAnchor(1, 1);\n outlinerPlaceablesPanel.setBackgroundColor(UIColor.transparent());\n });\n leftPanel.addChildComponent(\"outlinerPlaceablesPanel\", outlinerPlaceablesPanel);\n\n final Label outlinerPlaceablesLabel = new Label();\n outlinerPlaceablesLabel.setOnInitAction(() -> {\n outlinerPlaceablesLabel.setText(LangManager.getItem(\"outliner\"));\n outlinerPlaceablesLabel.setHorizontalAlign(EnumHAlignment.centre);\n outlinerPlaceablesLabel.setVerticalAlign(EnumVAlignment.centre);\n outlinerPlaceablesLabel.setTopLeftPos(4, 0);\n outlinerPlaceablesLabel.setBottomRightPos(-4, 24);\n outlinerPlaceablesLabel.setTopLeftAnchor(0, 0);\n outlinerPlaceablesLabel.setBottomRightAnchor(1, 0);\n });\n outlinerPlaceablesPanel.addChildComponent(\"outlinerPlaceablesLabel\", outlinerPlaceablesLabel);\n\n //Defined at class level\n outlinerPlaceablesListBox.setOnInitAction(() -> {\n outlinerPlaceablesListBox.setBackgroundColor(UIColor.transparent());\n outlinerPlaceablesListBox.setTopLeftPos(0, 24);\n outlinerPlaceablesListBox.setBottomRightPos(0, 0);\n outlinerPlaceablesListBox.setTopLeftAnchor(0, 0);\n outlinerPlaceablesListBox.setBottomRightAnchor(1, 1);\n });\n outlinerPlaceablesPanel.addChildComponent(\"outlinerPlaceablesListBox\", outlinerPlaceablesListBox);\n //</editor-fold>\n\n //<editor-fold desc=\"Outliner objects panel\">\n //Defined at class level\n outlinerObjectsPanel.setOnInitAction(() -> {\n outlinerObjectsPanel.setTopLeftPos(0, 24);\n outlinerObjectsPanel.setBottomRightPos(0, 0);\n outlinerObjectsPanel.setTopLeftAnchor(0, 0);\n outlinerObjectsPanel.setBottomRightAnchor(1, 1);\n outlinerObjectsPanel.setBackgroundColor(UIColor.transparent());\n outlinerObjectsPanel.setVisible(false); //Hidden by default\n });\n leftPanel.addChildComponent(\"outlinerObjectsPanel\", outlinerObjectsPanel);\n\n final Label outlinerObjectsLabel = new Label();\n outlinerObjectsLabel.setOnInitAction(() -> {\n outlinerObjectsLabel.setText(LangManager.getItem(\"outliner\"));\n outlinerObjectsLabel.setHorizontalAlign(EnumHAlignment.centre);\n outlinerObjectsLabel.setVerticalAlign(EnumVAlignment.centre);\n outlinerObjectsLabel.setTopLeftPos(4, 0);\n outlinerObjectsLabel.setBottomRightPos(-4, 24);\n outlinerObjectsLabel.setTopLeftAnchor(0, 0);\n outlinerObjectsLabel.setBottomRightAnchor(1, 0);\n });\n outlinerObjectsPanel.addChildComponent(\"outlinerObjectsLabel\", outlinerObjectsLabel);\n\n //Defined at class level\n outlinerObjectsListBox.setOnInitAction(() -> {\n outlinerObjectsListBox.setBackgroundColor(UIColor.transparent());\n outlinerObjectsListBox.setTopLeftPos(0, 24);\n// outlinerObjectsListBox.setBottomRightPos(0, -24); //TODO: When external backgrounds are figured out, uncomment this\n outlinerObjectsListBox.setBottomRightPos(0, 0);\n outlinerObjectsListBox.setTopLeftAnchor(0, 0);\n outlinerObjectsListBox.setBottomRightAnchor(1, 1);\n });\n outlinerObjectsPanel.addChildComponent(\"outlinerObjectsListBox\", outlinerObjectsListBox);\n //</editor-fold>\n\n// final TextField addExternalBackgroundObjectTextField = new TextField();\n// addExternalBackgroundObjectTextField.setOnInitAction(() -> {\n// addExternalBackgroundObjectTextField.setTopLeftPos(0, -24);\n// addExternalBackgroundObjectTextField.setBottomRightPos(0, 0);\n// addExternalBackgroundObjectTextField.setTopLeftAnchor(0, 1);\n// addExternalBackgroundObjectTextField.setBottomRightAnchor(1, 1);\n// addExternalBackgroundObjectTextField.setPlaceholder(LangManager.getItem(\"addExternalBackgroundObject\"));\n// addExternalBackgroundObjectTextField.setBackgroundColor(UIColor.transparent());\n// });\n// addExternalBackgroundObjectTextField.setOnReturnAction(() -> {\n// if (ProjectManager.getCurrentProject() != null && ProjectManager.getCurrentClientLevelData() != null) {\n// if (!Objects.equals(addExternalBackgroundObjectTextField.value, \"\")) {\n// if (!ProjectManager.getCurrentLevelData().isObjectBackgroundExternal(addExternalBackgroundObjectTextField.text) &&\n// !ProjectManager.getCurrentLevelData().getModel().hasObject(addExternalBackgroundObjectTextField.text)) {\n// ProjectManager.getCurrentLevelData().addBackgroundExternalObject(addExternalBackgroundObjectTextField.text);\n//\n// outlinerObjectsListBox.addChildComponent(getOutlinerExternalBackgroundObjectComponent(addExternalBackgroundObjectTextField.text));\n// } else {\n// sendNotif(LangManager.getItem(\"alreadyObject\"), UIColor.matRed());\n// }\n//\n// addExternalBackgroundObjectTextField.setValue(\"\"); //Clear text field\n// } else {\n// //Text field is blank\n// sendNotif(LangManager.getItem(\"noObjectSpecified\"), UIColor.matRed());\n// }\n// } else {\n// sendNotif(LangManager.getItem(\"noLevelLoaded\"), UIColor.matRed());\n// }\n// });\n// outlinerObjectsPanel.addChildComponent(\"addExternalBackgroundObjectTextField\", addExternalBackgroundObjectTextField);\n// textFields.add(addExternalBackgroundObjectTextField);\n\n final Panel rightPanel = new Panel();\n rightPanel.setOnInitAction(() -> {\n rightPanel.setBackgroundColor(UIColor.matGrey900(0.75));\n rightPanel.setTopLeftPos(-256, 0);\n rightPanel.setBottomRightPos(0, 0 - TIMELINE_HEIGHT);\n rightPanel.setTopLeftAnchor(1, 0);\n rightPanel.setBottomRightAnchor(1, 1);\n });\n mainUI.addChildComponent(\"rightPanel\", rightPanel);\n\n final ListBox actionsListBox = new ListBox();\n actionsListBox.setOnInitAction(() -> {\n actionsListBox.setTopLeftPos(0, 0);\n actionsListBox.setBottomRightPos(0, 130);\n actionsListBox.setTopLeftAnchor(0, 0);\n actionsListBox.setBottomRightAnchor(1, 0);\n actionsListBox.setBackgroundColor(UIColor.transparent());\n });\n rightPanel.addChildComponent(\"actionsListBox\", actionsListBox);\n\n //<editor-fold desc=\"ImportObj TextButton\">\n //Defined at class level\n importObjButton.setOnInitAction(() -> {\n importObjButton.setText(LangManager.getItem(\"importObj\"));\n importObjButton.setTopLeftPos(0, 0);\n importObjButton.setBottomRightPos(0, 24);\n });\n importObjButton.setOnLMBAction(this::importObj);\n actionsListBox.addChildComponent(\"importObjButton\", importObjButton);\n //</editor-fold>\n\n //<editor-fold desc=\"ImportConfig TextButton\">\n //Defined at class level\n importConfigButton.setOnInitAction(() -> {\n importConfigButton.setText(LangManager.getItem(\"importConfig\"));\n importConfigButton.setTopLeftPos(0, 0);\n importConfigButton.setBottomRightPos(0, 24);\n });\n importConfigButton.setOnLMBAction(this::importConfig);\n actionsListBox.addChildComponent(\"importConfigButton\", importConfigButton);\n //</editor-fold>\n\n //<editor-fold desc=\"Export TextButton\">\n //Defined at class level\n exportButton.setOnInitAction(() -> {\n exportButton.setText(LangManager.getItem(\"export\"));\n exportButton.setTopLeftPos(0, 0);\n exportButton.setBottomRightPos(0, 24);\n });\n exportButton.setOnLMBAction(this::export);\n actionsListBox.addChildComponent(\"exportButton\", exportButton);\n //</editor-fold>\n\n //<editor-fold desc=\"Settings TextButton\">\n //Defined at class level\n settingsButton.setOnInitAction(() -> {\n settingsButton.setText(LangManager.getItem(\"settings\"));\n settingsButton.setTopLeftPos(0, 0);\n settingsButton.setBottomRightPos(0, 24);\n });\n settingsButton.setOnLMBAction(this::showSettings);\n actionsListBox.addChildComponent(\"settingsButton\", settingsButton);\n //</editor-fold>\n\n //<editor-fold desc=\"Project Settings TextButton\">\n //Defined at class level\n projectSettingsButton.setOnInitAction(() -> {\n projectSettingsButton.setText(LangManager.getItem(\"projectSettings\"));\n projectSettingsButton.setTopLeftPos(0, 0);\n projectSettingsButton.setBottomRightPos(0, 24);\n });\n projectSettingsButton.setOnLMBAction(this::showProjectSettings);\n actionsListBox.addChildComponent(\"projectSettingsButton\", projectSettingsButton);\n //</editor-fold>\n\n //<editor-fold desc=\"Placeable Properties\">\n //Defined at class level\n propertiesPlaceablesListBox.setOnInitAction(() -> {\n propertiesPlaceablesListBox.setTopLeftPos(0, 130);\n propertiesPlaceablesListBox.setBottomRightPos(0, 0);\n propertiesPlaceablesListBox.setTopLeftAnchor(0, 0);\n propertiesPlaceablesListBox.setBottomRightAnchor(1, 1);\n propertiesPlaceablesListBox.setBackgroundColor(UIColor.transparent());\n });\n rightPanel.addChildComponent(\"propertiesPlaceablesListBox\", propertiesPlaceablesListBox);\n\n final Label placeablesPropertiesLabel = new Label();\n placeablesPropertiesLabel.setOnInitAction(() -> {\n placeablesPropertiesLabel.setText(LangManager.getItem(\"properties\"));\n placeablesPropertiesLabel.setHorizontalAlign(EnumHAlignment.centre);\n placeablesPropertiesLabel.setVerticalAlign(EnumVAlignment.centre);\n placeablesPropertiesLabel.setTopLeftPos(0, 0);\n placeablesPropertiesLabel.setBottomRightPos(0, 28);\n placeablesPropertiesLabel.setTopLeftAnchor(0, 0);\n placeablesPropertiesLabel.setBottomRightAnchor(1, 0);\n });\n propertiesPlaceablesListBox.addChildComponent(\"placeablesPropertiesLabel\", placeablesPropertiesLabel);\n\n final Label placeablePositionLabel = new Label();\n placeablePositionLabel.setOnInitAction(() -> {\n placeablePositionLabel.setText(LangManager.getItem(\"position\"));\n placeablePositionLabel.setVerticalAlign(EnumVAlignment.centre);\n placeablePositionLabel.setTopLeftPos(0, 0);\n placeablePositionLabel.setBottomRightPos(0, 24);\n });\n propertiesPlaceablesListBox.addChildComponent(\"placeablePositionLabel\", placeablePositionLabel);\n\n //Defined at class level\n placeablePositionTextFields.setOnInitAction(() -> {\n placeablePositionTextFields.setTopLeftPos(0, 0);\n placeablePositionTextFields.setBottomRightPos(0, 76);\n });\n propertiesPlaceablesListBox.addChildComponent(\"placeablePositionTextFields\", placeablePositionTextFields);\n\n final Label rotationLabel = new Label();\n rotationLabel.setOnInitAction(() -> {\n rotationLabel.setText(LangManager.getItem(\"rotation\"));\n rotationLabel.setVerticalAlign(EnumVAlignment.centre);\n rotationLabel.setTopLeftPos(0, 0);\n rotationLabel.setBottomRightPos(0, 24);\n });\n propertiesPlaceablesListBox.addChildComponent(\"rotationLabel\", rotationLabel);\n\n //Defined at class level\n placeableRotationTextFields.setOnInitAction(() -> {\n placeableRotationTextFields.setTopLeftPos(0, 0);\n placeableRotationTextFields.setBottomRightPos(0, 76);\n });\n propertiesPlaceablesListBox.addChildComponent(\"placeableRotationTextFields\", placeableRotationTextFields);\n\n final Label scaleLabel = new Label();\n scaleLabel.setOnInitAction(() -> {\n scaleLabel.setText(LangManager.getItem(\"scale\"));\n scaleLabel.setVerticalAlign(EnumVAlignment.centre);\n scaleLabel.setTopLeftPos(0, 0);\n scaleLabel.setBottomRightPos(0, 24);\n });\n propertiesPlaceablesListBox.addChildComponent(\"scaleLabel\", scaleLabel);\n\n //Defined at class level\n placeableScaleTextFields.setOnInitAction(() -> {\n placeableScaleTextFields.setTopLeftPos(0, 0);\n placeableScaleTextFields.setBottomRightPos(0, 76);\n });\n propertiesPlaceablesListBox.addChildComponent(\"placeableScaleTextFields\", placeableScaleTextFields);\n\n final Label typeLabel = new Label();\n typeLabel.setOnInitAction(() -> {\n typeLabel.setText(LangManager.getItem(\"type\"));\n typeLabel.setVerticalAlign(EnumVAlignment.centre);\n typeLabel.setTopLeftPos(0, 0);\n typeLabel.setBottomRightPos(0, 24);\n });\n propertiesPlaceablesListBox.addChildComponent(\"typeLabel\", typeLabel);\n\n //Defined at class level\n typeButton.setOnInitAction(() -> {\n typeButton.setText(LangManager.getItem(\"noTypes\"));\n typeButton.setEnabled(false);\n typeButton.setTopLeftPos(0, 0);\n typeButton.setBottomRightPos(0, 24);\n });\n typeButton.setOnLMBAction(() -> {\n assert mousePos != null;\n setOverlayUiScreen(getTypeSelectorOverlayScreen(mousePos.y));\n });\n propertiesPlaceablesListBox.addChildComponent(\"typeButton\", typeButton);\n\n final Label placeableItemGroupLabel = new Label();\n placeableItemGroupLabel.setOnInitAction(() -> {\n placeableItemGroupLabel.setText(LangManager.getItem(\"itemGroup\"));\n placeableItemGroupLabel.setVerticalAlign(EnumVAlignment.centre);\n placeableItemGroupLabel.setTopLeftPos(0, 0);\n placeableItemGroupLabel.setBottomRightPos(0, 24);\n });\n propertiesPlaceablesListBox.addChildComponent(\"itemGroupLabel\", placeableItemGroupLabel);\n\n //Defined at class level\n placeableItemGroupButton.setOnInitAction(() -> {\n placeableItemGroupButton.setText(LangManager.getItem(\"nothingSelected\"));\n placeableItemGroupButton.setEnabled(false);\n placeableItemGroupButton.setTopLeftPos(0, 0);\n placeableItemGroupButton.setBottomRightPos(0, 24);\n });\n placeableItemGroupButton.setOnLMBAction(() -> {\n assert mousePos != null;\n setOverlayUiScreen(getItemGroupSelectorOverlayScreen(mousePos.x, mousePos.y));\n });\n propertiesPlaceablesListBox.addChildComponent(\"placeableItemGroupButton\", placeableItemGroupButton);\n //</editor-fold>\n\n //<editor-fold desc=\"Object Properties\">\n //Defined at class level\n propertiesObjectsListBox.setOnInitAction(() -> {\n propertiesObjectsListBox.setTopLeftPos(0, 130);\n propertiesObjectsListBox.setBottomRightPos(0, 0);\n propertiesObjectsListBox.setTopLeftAnchor(0, 0);\n propertiesObjectsListBox.setBottomRightAnchor(1, 1);\n propertiesObjectsListBox.setBackgroundColor(UIColor.transparent());\n propertiesObjectsListBox.setVisible(false);\n });\n rightPanel.addChildComponent(\"propertiesObjectsListBox\", propertiesObjectsListBox);\n\n final Label objectsPropertiesLabel = new Label();\n objectsPropertiesLabel.setOnInitAction(() -> {\n objectsPropertiesLabel.setText(LangManager.getItem(\"properties\"));\n objectsPropertiesLabel.setHorizontalAlign(EnumHAlignment.centre);\n objectsPropertiesLabel.setVerticalAlign(EnumVAlignment.centre);\n objectsPropertiesLabel.setTopLeftPos(0, 0);\n objectsPropertiesLabel.setBottomRightPos(0, 28);\n objectsPropertiesLabel.setTopLeftAnchor(0, 0);\n objectsPropertiesLabel.setBottomRightAnchor(1, 0);\n });\n propertiesObjectsListBox.addChildComponent(\"objectsPropertiesLabel\", objectsPropertiesLabel);\n\n final Label objectItemGroupLabel = new Label();\n objectItemGroupLabel.setOnInitAction(() -> {\n objectItemGroupLabel.setText(LangManager.getItem(\"itemGroup\"));\n objectItemGroupLabel.setVerticalAlign(EnumVAlignment.centre);\n objectItemGroupLabel.setTopLeftPos(0, 0);\n objectItemGroupLabel.setBottomRightPos(0, 24);\n });\n propertiesObjectsListBox.addChildComponent(\"objectItemGroupLabel\", objectItemGroupLabel);\n\n //Defined at class level\n objectItemGroupButton.setOnInitAction(() -> {\n objectItemGroupButton.setText(LangManager.getItem(\"nothingSelected\"));\n objectItemGroupButton.setEnabled(false);\n objectItemGroupButton.setTopLeftPos(0, 0);\n objectItemGroupButton.setBottomRightPos(0, 24);\n });\n objectItemGroupButton.setOnLMBAction(() -> {\n assert mousePos != null;\n setOverlayUiScreen(getItemGroupSelectorOverlayScreen(mousePos.x, mousePos.y));\n });\n propertiesObjectsListBox.addChildComponent(\"objectItemGroupButton\", objectItemGroupButton);\n //</editor-fold>\n\n //Defined at class level\n notifPanel.setOnInitAction(() -> {\n notifPanel.setTopLeftPos(0, 0);\n notifPanel.setBottomRightPos(0, 0);\n notifPanel.setTopLeftAnchor(0, 0);\n notifPanel.setBottomRightAnchor(1, 1);\n notifPanel.setBackgroundColor(UIColor.transparent());\n });\n mainUI.addChildComponent(\"notifPanel\", notifPanel);\n\n //Defined at class level\n timeline.setOnInitAction(() -> {\n timeline.setTopLeftPos(0, -TIMELINE_HEIGHT);\n timeline.setBottomRightPos(0, 0);\n timeline.setTopLeftAnchor(0, 1);\n timeline.setBottomRightAnchor(1, 1);\n timeline.setBackgroundColor(UIColor.matGrey900(0.75));\n });\n mainUI.addChildComponent(\"timeline\", timeline);\n\n //<editor-fold desc=\"On screen camera controls\">\n //On screen camera controls - For those with difficulty controlling the camera with MMB / WASDQE\n //Declared at class level\n onScreenCameraControlsPanel.setOnInitAction(() -> {\n onScreenCameraControlsPanel.setBackgroundColor(UIColor.matGrey900(0.75));\n onScreenCameraControlsPanel.setTopLeftAnchor(0.5, 1);\n onScreenCameraControlsPanel.setBottomRightAnchor(0.5, 1);\n onScreenCameraControlsPanel.setTopLeftPos(-36, -72 -TIMELINE_HEIGHT - 52);\n onScreenCameraControlsPanel.setBottomRightPos(36, -TIMELINE_HEIGHT - 52);\n onScreenCameraControlsPanel.setVisible(false);\n });\n mainUI.addChildComponent(\"onScreenCameraControlsPanel\", onScreenCameraControlsPanel);\n\n final Button cameraPanDownButton = new Button();\n cameraPanDownButton.setOnInitAction(() -> {\n cameraPanDownButton.setTopLeftAnchor(0, 0);\n cameraPanDownButton.setBottomRightAnchor(0, 0);\n cameraPanDownButton.setTopLeftPos(0, 0);\n cameraPanDownButton.setBottomRightPos(24, 24);\n cameraPanDownButton.setTexture(ResourceManager.getTexture(\"image/arrowRightDown\").getTexture());\n });\n cameraPanDownButton.addPlugin(new AbstractComponentPlugin() {\n @Override\n public void onPostDraw() {\n if (linkedComponent.mouseOver && Mouse.isButtonDown(0)) {\n double speed = Window.isShiftDown() ? SMBLWSettings.cameraSprintSpeedMultiplier * SMBLWSettings.cameraSpeed : SMBLWSettings.cameraSpeed;\n cameraPos = cameraPos.add(0, -UIUtils.getDelta() * speed, 0);\n }\n }\n });\n onScreenCameraControlsPanel.addChildComponent(\"cameraPanDownButton\", cameraPanDownButton);\n\n final Button cameraPanLeftButton = new Button();\n cameraPanLeftButton.setOnInitAction(() -> {\n cameraPanLeftButton.setTopLeftAnchor(0, 0);\n cameraPanLeftButton.setBottomRightAnchor(0, 0);\n cameraPanLeftButton.setTopLeftPos(0, 24);\n cameraPanLeftButton.setBottomRightPos(24, 48);\n cameraPanLeftButton.setTexture(ResourceManager.getTexture(\"image/arrowLeft\").getTexture());\n });\n cameraPanLeftButton.addPlugin(new AbstractComponentPlugin() {\n @Override\n public void onPostDraw() {\n if (linkedComponent.mouseOver && Mouse.isButtonDown(0)) {\n double speed = Window.isShiftDown() ? SMBLWSettings.cameraSprintSpeedMultiplier * SMBLWSettings.cameraSpeed : SMBLWSettings.cameraSpeed;\n PosXYZ rightVector = new PosXYZ(Math.sin(Math.toRadians(cameraRot.x + 90)), 0, -Math.cos(Math.toRadians(cameraRot.x + 90)));\n cameraPos = cameraPos.subtract(rightVector.multiply(UIUtils.getDelta()).multiply(speed));\n }\n }\n });\n onScreenCameraControlsPanel.addChildComponent(\"cameraPanLeftButton\", cameraPanLeftButton);\n\n final Button cameraPanForwardButton = new Button();\n cameraPanForwardButton.setOnInitAction(() -> {\n cameraPanForwardButton.setTopLeftAnchor(0, 0);\n cameraPanForwardButton.setBottomRightAnchor(0, 0);\n cameraPanForwardButton.setTopLeftPos(24, 0);\n cameraPanForwardButton.setBottomRightPos(48, 24);\n cameraPanForwardButton.setTexture(ResourceManager.getTexture(\"image/arrowUp\").getTexture());\n });\n cameraPanForwardButton.addPlugin(new AbstractComponentPlugin() {\n @Override\n public void onPostDraw() {\n if (linkedComponent.mouseOver && Mouse.isButtonDown(0)) {\n double speed = Window.isShiftDown() ? SMBLWSettings.cameraSprintSpeedMultiplier * SMBLWSettings.cameraSpeed : SMBLWSettings.cameraSpeed;\n PosXYZ forwardVector = new PosXYZ(Math.sin(Math.toRadians(cameraRot.x)), 0, -Math.cos(Math.toRadians(cameraRot.x)));\n cameraPos = cameraPos.add(forwardVector.multiply(UIUtils.getDelta()).multiply(speed));\n }\n }\n });\n onScreenCameraControlsPanel.addChildComponent(\"cameraPanForwardButton\", cameraPanForwardButton);\n\n final Image cameraPanIcon = new Image();\n cameraPanIcon.setOnInitAction(() -> {\n cameraPanIcon.setTexture(ResourceManager.getTexture(\"image/arrowAll\").getTexture());\n cameraPanIcon.setTopLeftAnchor(0, 0);\n cameraPanIcon.setBottomRightAnchor(0, 0);\n cameraPanIcon.setTopLeftPos(24, 24);\n cameraPanIcon.setBottomRightPos(48, 48);\n });\n onScreenCameraControlsPanel.addChildComponent(\"cameraPanIcon\", cameraPanIcon);\n\n final Button cameraPanBackwardsButton = new Button();\n cameraPanBackwardsButton.setOnInitAction(() -> {\n cameraPanBackwardsButton.setTopLeftAnchor(0, 0);\n cameraPanBackwardsButton.setBottomRightAnchor(0, 0);\n cameraPanBackwardsButton.setTopLeftPos(24, 48);\n cameraPanBackwardsButton.setBottomRightPos(48, 72);\n cameraPanBackwardsButton.setTexture(ResourceManager.getTexture(\"image/arrowDown\").getTexture());\n });\n cameraPanBackwardsButton.addPlugin(new AbstractComponentPlugin() {\n @Override\n public void onPostDraw() {\n if (linkedComponent.mouseOver && Mouse.isButtonDown(0)) {\n double speed = Window.isShiftDown() ? SMBLWSettings.cameraSprintSpeedMultiplier * SMBLWSettings.cameraSpeed : SMBLWSettings.cameraSpeed;\n PosXYZ forwardVector = new PosXYZ(Math.sin(Math.toRadians(cameraRot.x)), 0, -Math.cos(Math.toRadians(cameraRot.x)));\n cameraPos = cameraPos.subtract(forwardVector.multiply(UIUtils.getDelta()).multiply(speed));\n }\n }\n });\n onScreenCameraControlsPanel.addChildComponent(\"cameraPanBackwardsButton\", cameraPanBackwardsButton);\n\n final Button cameraPanUpButton = new Button();\n cameraPanUpButton.setOnInitAction(() -> {\n cameraPanUpButton.setTopLeftAnchor(0, 0);\n cameraPanUpButton.setBottomRightAnchor(0, 0);\n cameraPanUpButton.setTopLeftPos(48, 0);\n cameraPanUpButton.setBottomRightPos(72, 24);\n cameraPanUpButton.setTexture(ResourceManager.getTexture(\"image/arrowLeftUp\").getTexture());\n });\n cameraPanUpButton.addPlugin(new AbstractComponentPlugin() {\n @Override\n public void onPostDraw() {\n if (linkedComponent.mouseOver && Mouse.isButtonDown(0)) {\n double speed = Window.isShiftDown() ? SMBLWSettings.cameraSprintSpeedMultiplier * SMBLWSettings.cameraSpeed : SMBLWSettings.cameraSpeed;\n cameraPos = cameraPos.add(0, UIUtils.getDelta() * speed, 0);\n }\n }\n });\n onScreenCameraControlsPanel.addChildComponent(\"cameraPanUpButton\", cameraPanUpButton);\n\n final Button cameraPanRightButton = new Button();\n cameraPanRightButton.setOnInitAction(() -> {\n cameraPanRightButton.setTopLeftAnchor(0, 0);\n cameraPanRightButton.setBottomRightAnchor(0, 0);\n cameraPanRightButton.setTopLeftPos(48, 24);\n cameraPanRightButton.setBottomRightPos(72, 48);\n cameraPanRightButton.setTexture(ResourceManager.getTexture(\"image/arrowRight\").getTexture());\n });\n cameraPanRightButton.addPlugin(new AbstractComponentPlugin() {\n @Override\n public void onPostDraw() {\n if (linkedComponent.mouseOver && Mouse.isButtonDown(0)) {\n double speed = Window.isShiftDown() ? SMBLWSettings.cameraSprintSpeedMultiplier * SMBLWSettings.cameraSpeed : SMBLWSettings.cameraSpeed;\n PosXYZ rightVector = new PosXYZ(Math.sin(Math.toRadians(cameraRot.x + 90)), 0, -Math.cos(Math.toRadians(cameraRot.x + 90)));\n cameraPos = cameraPos.add(rightVector.multiply(UIUtils.getDelta()).multiply(speed));\n }\n }\n });\n onScreenCameraControlsPanel.addChildComponent(\"cameraPanRightButton\", cameraPanRightButton);\n //</editor-fold>\n\n //Defined at class level\n inputOverlay.setOnInitAction(() -> {\n inputOverlay.setTopLeftPos(256, 0);\n inputOverlay.setBottomRightPos(-256, -TIMELINE_HEIGHT);\n inputOverlay.setTopLeftAnchor(0, 0);\n inputOverlay.setBottomRightAnchor(1, 1);\n inputOverlay.setBackgroundColor(UIColor.transparent());\n });\n mainUI.addChildComponent(\"inputOverlay\", inputOverlay);\n\n //Defined at class level\n fpsOverlay.setOnInitAction(() -> {\n fpsOverlay.setTopLeftPos(260, 4);\n fpsOverlay.setBottomRightPos(516, 28);\n fpsOverlay.setTopLeftAnchor(0, 0);\n fpsOverlay.setBottomRightAnchor(0, 0);\n fpsOverlay.setBackgroundColor(UIColor.matGrey900(0.75));\n fpsOverlay.setVisible(false);\n });\n mainUI.addChildComponent(\"fpsOverlay\", fpsOverlay);\n\n Window.logOpenGLError(\"After MainScreen.init()\");\n\n try {\n Window.drawable.releaseContext();\n } catch (LWJGLException e) {\n e.printStackTrace();\n }\n\n }\n\n @Override\n public void preDraw() {\n super.preDraw();\n\n Window.logOpenGLError(\"After MainScreen.super.preDraw()\");\n\n //Run next frame actions\n nextFrameActions.forEach(UIAction::execute);\n nextFrameActions.clear();\n\n //Show on screen camera controls if setting enabled\n onScreenCameraControlsPanel.setVisible(SMBLWSettings.showOnScreenCameraControls);\n //Show on screen input if setting enabled\n inputOverlay.setVisible(SMBLWSettings.showOnScreenInput);\n //Show FPS if setting enabled\n fpsOverlay.setVisible(SMBLWSettings.showFPSOverlay);\n\n if (ProjectManager.getCurrentClientLevelData() != null) {\n ProjectManager.getCurrentClientLevelData().update((float) UIUtils.getDelta());\n }\n\n if (Mouse.isButtonDown(2)) { //If MMB down\n //<editor-fold desc=\"Rotate camera on MMB & Move camera with MMB & WASDQE\">\n cameraRot = cameraRot.add(UIUtils.getMouseDelta().toPosXY());\n\n //X\n if (cameraRot.x >= 360) {\n cameraRot.x -= 360;\n } else if (cameraRot.x <= -360) {\n cameraRot.x += 360;\n }\n\n //Y\n if (cameraRot.y > 90) {\n cameraRot.y = 90;\n } else if (cameraRot.y < -90) {\n cameraRot.y = -90;\n }\n\n PosXYZ forwardVector = new PosXYZ(Math.sin(Math.toRadians(cameraRot.x)), 0, -Math.cos(Math.toRadians(cameraRot.x)));\n PosXYZ rightVector = new PosXYZ(Math.sin(Math.toRadians(cameraRot.x + 90)), 0, -Math.cos(Math.toRadians(cameraRot.x + 90)));\n\n double speed = Window.isShiftDown() ? SMBLWSettings.cameraSprintSpeedMultiplier * SMBLWSettings.cameraSpeed : SMBLWSettings.cameraSpeed;\n\n if (Keyboard.isKeyDown(Keyboard.KEY_Q)) { //Q: Go Down\n cameraPos = cameraPos.add(0, -UIUtils.getDelta() * speed, 0);\n }\n\n if (Keyboard.isKeyDown(Keyboard.KEY_E)) { //E: Go Up\n cameraPos = cameraPos.add(0, UIUtils.getDelta() * speed, 0);\n }\n\n if (Keyboard.isKeyDown(Keyboard.KEY_W)) { //W: Go Forwards\n cameraPos = cameraPos.add(forwardVector.multiply(UIUtils.getDelta()).multiply(speed));\n }\n\n if (Keyboard.isKeyDown(Keyboard.KEY_S)) { //S: Go Backwards\n cameraPos = cameraPos.subtract(forwardVector.multiply(UIUtils.getDelta()).multiply(speed));\n }\n\n if (Keyboard.isKeyDown(Keyboard.KEY_D)) { //D: Go Right\n cameraPos = cameraPos.add(rightVector.multiply(UIUtils.getDelta()).multiply(speed));\n }\n\n if (Keyboard.isKeyDown(Keyboard.KEY_A)) { //A: Go Left\n cameraPos = cameraPos.subtract(rightVector.multiply(UIUtils.getDelta()).multiply(speed));\n }\n //</editor-fold>\n } else if (ProjectManager.getCurrentClientLevelData() != null) {\n if (ProjectManager.getCurrentProject().mode == EnumActionMode.GRAB_PLACEABLE) {\n //<editor-fold desc=\"Grab\">\n\n for (String key : ProjectManager.getCurrentClientLevelData().getSelectedPlaceables()) {\n Placeable placeable = ProjectManager.getCurrentLevelData().getPlaceable(key);\n\n if ((ProjectManager.getCurrentProject().modeDirection.equals(new PosXYZ(1, 0, 0)) && placeable.getAsset().canGrabX()) ||\n (ProjectManager.getCurrentProject().modeDirection.equals(new PosXYZ(0, 1, 0)) && placeable.getAsset().canGrabY()) ||\n (ProjectManager.getCurrentProject().modeDirection.equals(new PosXYZ(0, 0, 1)) && placeable.getAsset().canGrabZ()) ||\n (placeable.getAsset().canGrabX() && placeable.getAsset().canGrabY()) && placeable.getAsset().canGrabZ()) { //If can grab in selected direction\n if (Window.isAltDown()) { //Snap with Alt\n if (Window.isShiftDown()) {\n deltaX += UIUtils.getMouseDelta().x * SMBLWSettings.modeMouseShiftSensitivity;\n deltaX += UIUtils.getMouseDWheel() * SMBLWSettings.modeMouseWheelShiftSensitivity;\n } else {\n deltaX += UIUtils.getMouseDelta().x * SMBLWSettings.modeMouseSensitivity;\n deltaX += UIUtils.getMouseDWheel() * SMBLWSettings.modeMouseWheelSensitivity;\n }\n\n if (deltaX >= SMBLWSettings.grabSnap || deltaX <= -SMBLWSettings.grabSnap) {\n placeable.setPosition(placeable.getPosition().add(ProjectManager.getCurrentProject().modeDirection.multiply(\n SMBLWSettings.grabSnap * Math.round(deltaX / SMBLWSettings.grabSnap))));\n\n deltaX = deltaX % SMBLWSettings.grabSnap;\n }\n } else if (Window.isShiftDown()) { //Precise movement with Shift\n placeable.setPosition(placeable.getPosition().add(ProjectManager.getCurrentProject().modeDirection.multiply(UIUtils.getMouseDelta().x * SMBLWSettings.modeMouseShiftSensitivity)));\n placeable.setPosition(placeable.getPosition().add(ProjectManager.getCurrentProject().modeDirection.multiply(UIUtils.getMouseDWheel() * SMBLWSettings.modeMouseWheelShiftSensitivity)));\n } else {\n placeable.setPosition(placeable.getPosition().add(ProjectManager.getCurrentProject().modeDirection.multiply(UIUtils.getMouseDelta().x * SMBLWSettings.modeMouseSensitivity)));\n placeable.setPosition(placeable.getPosition().add(ProjectManager.getCurrentProject().modeDirection.multiply(UIUtils.getMouseDWheel() * SMBLWSettings.modeMouseWheelSensitivity)));\n }\n }\n }\n //</editor-fold>\n } else if (ProjectManager.getCurrentProject().mode == EnumActionMode.ROTATE_PLACEABLE) {\n //<editor-fold desc=\"Rotate\">\n for (String key : ProjectManager.getCurrentClientLevelData().getSelectedPlaceables()) {\n Placeable placeable = ProjectManager.getCurrentLevelData().getPlaceable(key);\n\n if (placeable.getAsset().canRotate()) { //If can rotate\n if (Window.isAltDown()) { //Snap with Alt\n if (Window.isShiftDown()) {\n deltaX += UIUtils.getMouseDelta().x * SMBLWSettings.modeMouseShiftSensitivity;\n deltaX += UIUtils.getMouseDWheel() * SMBLWSettings.modeMouseWheelShiftSensitivity;\n } else {\n deltaX += UIUtils.getMouseDelta().x * SMBLWSettings.modeMouseSensitivity;\n deltaX += UIUtils.getMouseDWheel() * SMBLWSettings.modeMouseWheelSensitivity;\n }\n\n if (deltaX >= SMBLWSettings.rotationSnap || deltaX <= -SMBLWSettings.rotationSnap) {\n placeable.setRotation(placeable.getRotation().add(ProjectManager.getCurrentProject().modeDirection.multiply(\n SMBLWSettings.rotationSnap * Math.round(deltaX / SMBLWSettings.rotationSnap))));\n\n deltaX = deltaX % SMBLWSettings.rotationSnap;\n }\n } else if (Window.isShiftDown()) { //Precise movement with Shift\n placeable.setRotation(MathUtils.normalizeRotation(placeable.getRotation()\n .add(ProjectManager.getCurrentProject().modeDirection.multiply(UIUtils.getMouseDelta().x * SMBLWSettings.modeMouseShiftSensitivity))));\n placeable.setRotation(MathUtils.normalizeRotation(placeable.getRotation()\n .add(ProjectManager.getCurrentProject().modeDirection.multiply(UIUtils.getMouseDWheel() * SMBLWSettings.modeMouseWheelShiftSensitivity))));\n } else {\n placeable.setRotation(MathUtils.normalizeRotation(placeable.getRotation()\n .add(ProjectManager.getCurrentProject().modeDirection.multiply(UIUtils.getMouseDelta().x * SMBLWSettings.modeMouseSensitivity))));\n placeable.setRotation(MathUtils.normalizeRotation(placeable.getRotation()\n .add(ProjectManager.getCurrentProject().modeDirection.multiply(UIUtils.getMouseDWheel() * SMBLWSettings.modeMouseWheelSensitivity))));\n }\n }\n }\n //</editor-fold>\n } else if (ProjectManager.getCurrentProject().mode == EnumActionMode.SCALE_PLACEABLE) {\n //<editor-fold desc=\"Scale\">\n for (String key : ProjectManager.getCurrentClientLevelData().getSelectedPlaceables()) {\n Placeable placeable = ProjectManager.getCurrentLevelData().getPlaceable(key);\n\n if (placeable.getAsset().canScale()) { //If can scale\n if (Window.isAltDown()) { //Snap with Alt\n if (Window.isShiftDown()) {\n deltaX += UIUtils.getMouseDelta().x * SMBLWSettings.modeMouseShiftSensitivity;\n deltaX += UIUtils.getMouseDWheel() * SMBLWSettings.modeMouseWheelShiftSensitivity;\n } else {\n deltaX += UIUtils.getMouseDelta().x * SMBLWSettings.modeMouseSensitivity;\n deltaX += UIUtils.getMouseDWheel() * SMBLWSettings.modeMouseWheelSensitivity;\n }\n\n if (deltaX >= SMBLWSettings.scaleSnap || deltaX <= -SMBLWSettings.scaleSnap) {\n placeable.setScale(placeable.getScale().add(ProjectManager.getCurrentProject().modeDirection.multiply(\n SMBLWSettings.scaleSnap * Math.round(deltaX / SMBLWSettings.scaleSnap))));\n\n deltaX = deltaX % SMBLWSettings.scaleSnap;\n }\n } else if (Window.isShiftDown()) { //Precise movement with shift\n placeable.setScale(placeable.getScale().add(ProjectManager.getCurrentProject().modeDirection.multiply(UIUtils.getMouseDelta().x * SMBLWSettings.modeMouseShiftSensitivity)));\n placeable.setScale(placeable.getScale().add(ProjectManager.getCurrentProject().modeDirection.multiply(UIUtils.getMouseDWheel() * SMBLWSettings.modeMouseWheelShiftSensitivity)));\n } else {\n placeable.setScale(placeable.getScale().add(ProjectManager.getCurrentProject().modeDirection.multiply(UIUtils.getMouseDelta().x * SMBLWSettings.modeMouseSensitivity)));\n placeable.setScale(placeable.getScale().add(ProjectManager.getCurrentProject().modeDirection.multiply(UIUtils.getMouseDWheel() * SMBLWSettings.modeMouseWheelSensitivity)));\n }\n }\n }\n //</editor-fold>\n } else if (ProjectManager.getCurrentProject().mode == EnumActionMode.GRAB_KEYFRAME) {\n //TODO: Grab keyframes\n// //<editor-fold desc=\"Grab\">\n// for (Map.Entry<String, BufferedAnimData> entry : ProjectManager.getCurrentClientLevelData().getAnimDataBufferMap().entrySet()) {\n// BufferedAnimData bad = entry.getValue();\n//\n// if (Window.isAltDown()) { //Snap with Alt\n// float snapToTranslation = Window.isShiftDown() ? SMBLWSettings.animSnapShift : SMBLWSettings.animSnap; //Precise movement with shift\n// bad.setSnapToTranslation(snapToTranslation);\n// } else {\n// bad.setSnapToTranslation(null);\n// }\n//\n// if (Window.isShiftDown()) { //Precise movement with Shift\n// float newTranslation = (float) (bad.getKeyframeBufferTranslation() + UIUtils.getMouseDelta().x * SMBLWSettings.modeKeyframeMouseShiftSensitivity +\n// UIUtils.getMouseDWheel() * SMBLWSettings.modeKeyframeMouseWheelShiftSensitivity);\n// bad.setKeyframeBufferTranslation(newTranslation);\n// } else {\n// float newTranslation = (float) (bad.getKeyframeBufferTranslation() + UIUtils.getMouseDelta().x * SMBLWSettings.modeKeyframeMouseSensitivity +\n// UIUtils.getMouseDWheel() * SMBLWSettings.modeKeyframeMouseWheelSensitivity);\n// bad.setKeyframeBufferTranslation(newTranslation);\n// }\n// }\n// //</editor-fold>\n } else if (ProjectManager.getCurrentProject().mode == EnumActionMode.SCALE_KEYFRAME) {\n //TODO: Scale keyframes\n }\n\n if (ProjectManager.getCurrentProject().mode != EnumActionMode.NONE) {\n updatePropertiesPlaceablesPanel();\n }\n }\n\n\n //<editor-fold desc=\"Set ProjectManager.getCurrentProject().mode Label\">\n String modeStringKey;\n switch (ProjectManager.getCurrentProject().mode) {\n case NONE:\n modeStringKey = \"none\";\n break;\n case GRAB_PLACEABLE:\n modeStringKey = \"grabPlaceable\";\n break;\n case ROTATE_PLACEABLE:\n modeStringKey = \"rotatePlaceable\";\n break;\n case SCALE_PLACEABLE:\n modeStringKey = \"scalePlaceable\";\n break;\n case GRAB_KEYFRAME:\n modeStringKey = \"grabKeyframe\";\n break;\n case SCALE_KEYFRAME:\n modeStringKey = \"scaleKeyframe\";\n break;\n default:\n //This shouldn't happen\n modeStringKey = \"invalid\";\n break;\n }\n\n modeLabel.setText(String.format(LangManager.getItem(\"modeLabelFormat\"), LangManager.getItem(modeStringKey)));\n //</editor-fold>\n\n //<editor-fold desc=\"ProjectManager.getCurrentProject().mode Direction Label\">\n String modeDirectionString;\n if (ProjectManager.getCurrentProject().modeDirection.equals(new PosXYZ(1, 0, 0))) {\n modeDirectionString = LangManager.getItem(\"axisX\");\n } else if (ProjectManager.getCurrentProject().modeDirection.equals(new PosXYZ(0, 1, 0))) {\n modeDirectionString = LangManager.getItem(\"axisY\");\n } else if (ProjectManager.getCurrentProject().modeDirection.equals(new PosXYZ(0, 0, 1))) {\n modeDirectionString = LangManager.getItem(\"axisZ\");\n } else if (ProjectManager.getCurrentProject().modeDirection.equals(new PosXYZ(1, 1, 1))) {\n modeDirectionString = LangManager.getItem(\"axisUniform\");\n } else {\n modeDirectionString = String.format(\"%.2f, %.2f, %.2f\", ProjectManager.getCurrentProject().modeDirection.x, ProjectManager.getCurrentProject().modeDirection.y, ProjectManager.getCurrentProject().modeDirection.z);\n }\n\n modeDirectionLabel.setText(String.format(LangManager.getItem(\"modeDirectionLabelFormat\"), modeDirectionString));\n //</editor-fold>\n\n if (ProjectManager.getCurrentProject().mode == EnumActionMode.NONE) {\n modeCursor.setVisible(false);\n } else {\n modeCursor.setVisible(true);\n }\n\n if (Mouse.isButtonDown(2) ||\n ProjectManager.getCurrentProject().mode != EnumActionMode.NONE) {\n if (!Mouse.isGrabbed()) {\n Mouse.setGrabbed(true);\n }\n } else {\n if (Mouse.isGrabbed()) {\n Mouse.setGrabbed(false);\n }\n }\n\n Window.logOpenGLError(\"After MainScreen.preDraw()\");\n\n }\n\n @Override\n public void draw() {\n Window.logOpenGLError(\"Before MainScreen.draw()\");\n\n topLeftPos = new PosXY(0, 0);\n topLeftPx = new PosXY(0, 0);\n bottomRightPos = new PosXY(Display.getWidth(), Display.getHeight());\n bottomRightPx = new PosXY(Display.getWidth(), Display.getHeight());\n\n if (overlayUiScreen == null) {\n getParentMousePos();\n } else {\n mousePos = null;\n }\n\n preDraw();\n if (!preventRendering) {\n drawViewport();\n }\n postDraw();\n\n if (overlayUiScreen != null) {\n overlayUiScreen.draw();\n }\n\n Window.logOpenGLError(\"After MainScreen.draw()\");\n }\n\n private void drawViewport() { //TODO: Draw per item group\n synchronized (renderingLock) {\n Window.logOpenGLError(\"Before MainScreen.drawViewport()\");\n\n GL11.glEnable(GL11.GL_DEPTH_TEST);\n\n //<editor-fold desc=\"Setup the matrix\">\n GL11.glViewport(0, 0, Display.getWidth(), Display.getHeight());\n GL11.glMatrixMode(GL11.GL_PROJECTION);\n GL11.glLoadIdentity();\n GLU.gluPerspective(90, Display.getWidth() / (float) Display.getHeight(), 0.5f, 1000f);\n //</editor-fold>\n\n GL11.glPushMatrix();\n\n Window.logOpenGLError(\"After MainScreen.drawViewport() - Matrix setup\");\n\n GL11.glRotated(cameraRot.y, 1, 0, 0);\n GL11.glRotated(cameraRot.x, 0, 1, 0);\n\n GL11.glTranslated(-cameraPos.x, -cameraPos.y, -cameraPos.z);\n\n GL11.glLineWidth(2);\n\n //<editor-fold desc=\"Draw X line\">\n UIColor.matRed().bindColor();\n GL11.glBegin(GL11.GL_LINES);\n GL11.glVertex3d(-10000, 0, 0);\n GL11.glVertex3d(10000, 0, 0);\n GL11.glEnd();\n //</editor-fold>\n\n //<editor-fold desc=\"Draw Z line\">\n UIColor.matBlue().bindColor();\n GL11.glBegin(GL11.GL_LINES);\n GL11.glVertex3d(0, 0, -10000);\n GL11.glVertex3d(0, 0, 10000);\n GL11.glEnd();\n //</editor-fold>\n\n Window.logOpenGLError(\"After MainScreen.drawViewport() - Drawing global X & Z lines\");\n\n GL11.glLineWidth(4);\n\n UIColor.pureWhite().bindColor();\n\n if (ProjectManager.getCurrentClientLevelData() != null) {\n //<editor-fold desc=\"Draw model with wireframes\">\n GL11.glEnable(GL11.GL_DEPTH_TEST);\n\n ResourceShaderProgram currentShaderProgram = getCurrentShader();\n boolean useTextures = isCurrentShaderTextured();\n\n if (!SMBLWSettings.showTextures) {\n UIColor.pureWhite().bindColor();\n }\n\n\n float time = ProjectManager.getCurrentClientLevelData().getTimelinePos();\n\n GL20.glUseProgram(currentShaderProgram.getProgramID());\n for (ResourceModel model : ProjectManager.getCurrentLevelData().getModels()) {\n for (OBJObject object : model.scene.getObjectList()){\n GL11.glPushMatrix();\n\n //Transform at current time\n transformObjectAtTime(object.name, time);\n\n if (!ProjectManager.getCurrentClientLevelData().isObjectHidden(object.name)) {\n model.drawModelObject(currentShaderProgram, useTextures, object.name);\n }\n\n GL11.glPopMatrix();\n }\n }\n GL20.glUseProgram(0);\n\n Window.logOpenGLError(\"After MainScreen.drawViewport() - Drawing model filled\");\n\n if (SMBLWSettings.showAllWireframes) {\n\n for (ResourceModel model : ProjectManager.getCurrentLevelData().getModels()) {\n for (OBJObject object : model.scene.getObjectList()) {\n GL11.glPushMatrix();\n\n transformObjectAtTime(object.name);\n\n if (!ProjectManager.getCurrentClientLevelData().isObjectHidden(object.name)) {\n GL11.glColor4f(0, 0, 0, 1);\n model.drawModelObjectWireframe(null, false, object.name);\n\n GL11.glDisable(GL11.GL_DEPTH_TEST);\n\n GL11.glColor4f(0, 0, 0, 0.01f);\n model.drawModelObjectWireframe(null, false, object.name);\n\n GL11.glEnable(GL11.GL_DEPTH_TEST);\n }\n\n GL11.glPopMatrix();\n }\n }\n }\n Window.logOpenGLError(\"After MainScreen.drawViewport() - Drawing model wireframes\");\n\n //</editor-fold>\n\n //<editor-fold desc=\"Draw placeables\">\n List<DepthSortedPlaceable> depthSortedMap = new ArrayList<>();\n\n synchronized (ProjectManager.getCurrentLevelData().getPlacedObjects()) {\n\n for (Map.Entry<String, Placeable> placeableEntry : ProjectManager.getCurrentLevelData().getPlacedObjects().entrySet()) {\n Placeable placeable = placeableEntry.getValue();\n\n double distance;\n\n if (placeable.getAsset() instanceof AssetFalloutY) {\n// distance = getDistance(cameraPos, new PosXYZ(cameraPos.x, placeable.getPosition().y, cameraPos.z));\n distance = 0; //Always render the fallout plane last\n } else {\n distance = getDistance(cameraPos, placeable.getPosition());\n }\n\n depthSortedMap.add(new DepthSortedPlaceable(distance, placeableEntry));\n }\n\n }\n\n Collections.sort(depthSortedMap, new DepthComparator());\n\n for (DepthSortedPlaceable placeableEntry : depthSortedMap) {\n String name = placeableEntry.entry.getKey();\n Placeable placeable = placeableEntry.entry.getValue();\n boolean isSelected = ProjectManager.getCurrentClientLevelData().isPlaceableSelected(name);\n\n drawPlaceable(placeable, isSelected);\n\n }\n //</editor-fold>\n\n //<editor-fold desc=\"Draw selected stuff\">\n drawSelectedPlaceables(ProjectManager.getCurrentClientLevelData().getSelectedPlaceables(),\n ProjectManager.getCurrentLevelData());\n\n //<editor-fold desc=\"Draw selected objects\">\n UIColor.matBlue().bindColor();\n UIUtils.drawWithStencilOutside(\n () -> {\n for (String name : ProjectManager.getCurrentClientLevelData().getSelectedObjects()) {\n GL11.glPushMatrix();\n\n transformObjectAtTime(name);\n\n if (!ProjectManager.getCurrentClientLevelData().isObjectHidden(name)) {\n for (ResourceModel model : ProjectManager.getCurrentLevelData().getModels()) {\n if (model.hasObject(name)) {\n model.drawModelObject(null, false, name);\n }\n }\n }\n\n GL11.glPopMatrix();\n }\n },\n () -> {\n GL11.glDisable(GL11.GL_DEPTH_TEST);\n for (String name : ProjectManager.getCurrentClientLevelData().getSelectedObjects()) {\n GL11.glPushMatrix();\n\n transformObjectAtTime(name);\n\n if (!ProjectManager.getCurrentClientLevelData().isObjectHidden(name)) {\n for (ResourceModel model : ProjectManager.getCurrentLevelData().getModels()) {\n if (model.hasObject(name)) {\n model.drawModelObjectWireframe(null, false, name);\n }\n }\n }\n\n GL11.glPopMatrix();\n }\n GL11.glEnable(GL11.GL_DEPTH_TEST);\n });\n\n Window.logOpenGLError(\"After MainScreen.drawViewport() - Drawing model selection wireframes\");\n //</editor-fold>\n //</editor-fold>\n\n }\n\n GL11.glPopMatrix();\n\n GL11.glColor3f(1, 1, 1);\n GL11.glDisable(GL11.GL_DEPTH_TEST);\n\n Window.setMatrix();\n\n Window.logOpenGLError(\"After MainScreen.drawViewport()\");\n }\n }\n\n private void drawPlaceable(Placeable placeable, boolean isSelected) {\n ResourceModel model = placeable.getAsset().getModel();\n\n GL11.glPushMatrix();\n\n GL11.glTranslated(placeable.getPosition().x, placeable.getPosition().y, placeable.getPosition().z);\n GL11.glRotated(placeable.getRotation().z, 0, 0, 1);\n GL11.glRotated(placeable.getRotation().y, 0, 1, 0);\n GL11.glRotated(placeable.getRotation().x, 1, 0, 0);\n\n GL11.glEnable(GL11.GL_DEPTH_TEST);\n\n GL11.glScaled(placeable.getScale().x, placeable.getScale().y, placeable.getScale().z);\n GL20.glUseProgram(placeable.getAsset().getShaderProgram().getProgramID());\n model.drawModel(placeable.getAsset().getShaderProgram(), placeable.getAsset().isShaderTextured(), placeable.getAsset().getColor());\n GL20.glUseProgram(0);\n\n Window.logOpenGLError(\"After MainScreen.drawPlaceable() - Drawing placeable \" + name + \" filled\");\n\n //<editor-fold desc=\"Draw blue wireframe and direction line if selected, else draw orange wireframe\">\n GL11.glLineWidth(2);\n\n if (isSelected) {\n if (ProjectManager.getCurrentProject().mode.isPlaceableMode()) {\n GL11.glPushMatrix();\n\n GL11.glRotated(-placeable.getRotation().x, 1, 0, 0);\n GL11.glRotated(-placeable.getRotation().y, 0, 1, 0);\n GL11.glRotated(-placeable.getRotation().z, 0, 0, 1);\n\n if (ProjectManager.getCurrentProject().modeDirection.equals(new PosXYZ(1, 0, 0))) {\n //<editor-fold desc=\"Draw X line\">\n UIColor.matRed(0.75).bindColor();\n GL11.glBegin(GL11.GL_LINES);\n GL11.glVertex3d(-10000, 0, 0);\n GL11.glVertex3d(10000, 0, 0);\n GL11.glEnd();\n //</editor-fold>\n } else if (ProjectManager.getCurrentProject().modeDirection.equals(new PosXYZ(0, 1, 0))) {\n //<editor-fold desc=\"Draw Y line\">\n UIColor.matGreen(0.75).bindColor();\n GL11.glBegin(GL11.GL_LINES);\n GL11.glVertex3d(0, -10000, 0);\n GL11.glVertex3d(0, 10000, 0);\n GL11.glEnd();\n //</editor-fold>\n } else if (ProjectManager.getCurrentProject().modeDirection.equals(new PosXYZ(0, 0, 1))) {\n //<editor-fold desc=\"Draw Z line\">\n UIColor.matBlue(0.75).bindColor();\n GL11.glBegin(GL11.GL_LINES);\n GL11.glVertex3d(0, 0, -10000);\n GL11.glVertex3d(0, 0, 10000);\n GL11.glEnd();\n //</editor-fold>\n }\n\n GL11.glPopMatrix();\n }\n\n UIColor.matBlue().bindColor();\n } else {\n UIColor.matOrange().bindColor();\n }\n\n if (SMBLWSettings.showAllWireframes) {\n model.drawModelWireframe(null, false);\n }\n //</editor-fold>\n\n Window.logOpenGLError(\"After MainScreen.drawPlaceable() - Drawing placeable \" + name + \" wireframe (Depth test on)\");\n\n GL11.glDisable(GL11.GL_DEPTH_TEST);\n\n// //<editor-fold desc=\"Draw blue wireframe if selected, else draw orange wireframe (Ignores depth test - Is semi transparent)\">\n// if (isSelected) {\n// UIColor.matBlue(0.05).bindColor();\n// } else {\n// UIColor.matOrange(0.02).bindColor();\n// }\n//\n// if (SMBLWSettings.showAllWireframes || isSelected) {\n// model.drawModelWireframe(null, false);\n// }\n// //</editor-fold>\n\n Window.logOpenGLError(\"After MainScreen.drawPlaceable() - Drawing placeable \" + name + \" wireframe (Depth test off)\");\n\n GL11.glPopMatrix();\n }\n\n private void drawSelectedPlaceables(Collection<String> placeables, LevelData levelData) {\n UIColor.matBlue().bindColor();\n UIUtils.drawWithStencilOutside(\n () -> {\n for (String name : placeables) {\n Placeable placeable = levelData.getPlaceable(name);\n\n GL11.glPushMatrix();\n\n GL11.glTranslated(placeable.getPosition().x, placeable.getPosition().y, placeable.getPosition().z);\n GL11.glRotated(placeable.getRotation().z, 0, 0, 1);\n GL11.glRotated(placeable.getRotation().y, 0, 1, 0);\n GL11.glRotated(placeable.getRotation().x, 1, 0, 0);\n GL11.glScaled(placeable.getScale().x, placeable.getScale().y, placeable.getScale().z);\n\n placeable.getAsset().getModel().drawModel(null, false);\n\n GL11.glPopMatrix();\n }\n },\n () -> {\n GL11.glLineWidth(4);\n GL11.glDisable(GL11.GL_DEPTH_TEST);\n for (String name : placeables) {\n Placeable placeable = levelData.getPlaceable(name);\n\n GL11.glPushMatrix();\n\n GL11.glTranslated(placeable.getPosition().x, placeable.getPosition().y, placeable.getPosition().z);\n GL11.glRotated(placeable.getRotation().z, 0, 0, 1);\n GL11.glRotated(placeable.getRotation().y, 0, 1, 0);\n GL11.glRotated(placeable.getRotation().x, 1, 0, 0);\n GL11.glScaled(placeable.getScale().x, placeable.getScale().y, placeable.getScale().z);\n\n placeable.getAsset().getModel().drawModelWireframe(null, false);\n\n GL11.glPopMatrix();\n }\n GL11.glEnable(GL11.GL_DEPTH_TEST);\n });\n }\n\n @Override\n public void onClick(int button, PosXY mousePos) {\n if (button == 0 && ProjectManager.getCurrentProject().mode != EnumActionMode.NONE) { //LMB: Confirm action\n confirmModeAction();\n } else if (button == 1 && ProjectManager.getCurrentProject().mode != EnumActionMode.NONE) { //RMB: Discard action\n discardModeAction();\n } else {\n super.onClick(button, mousePos);\n }\n }\n\n @Override\n public void onKeyDown(int key, char keyChar) {\n inputOverlay.onKeyDownManual(key, keyChar);\n\n if (overlayUiScreen != null) {\n overlayUiScreen.onKeyDown(key, keyChar);\n } else {\n\n boolean isTextFieldSelected = false;\n for (TextField textField : textFields) {\n if (textField.isSelected) {\n isTextFieldSelected = true;\n break;\n }\n }\n\n if (!isTextFieldSelected) {\n if (!Mouse.isButtonDown(2)) { //If MMB not down\n if (key == Keyboard.KEY_F1) { //F1 to hide / show the ui\n mainUI.setVisible(!mainUI.isVisible());\n\n } else if (ProjectManager.getCurrentClientLevelData() != null) {\n if (ProjectManager.getCurrentProject().mode == EnumActionMode.NONE) {\n if (key == Keyboard.KEY_G) { //G: Grab\n //TODO: Timeline keyframes\n if (timeline.mouseOver) { //Grab keyframes when the cursor is over the timeline\n// addUndoCommand(new UndoModifyKeyframes(ProjectManager.getCurrentClientLevelData(), this,\n// ProjectManager.getCurrentLevelData().getObjectAnimDataMap()));\n// moveSelectedKeyframesToBuffer(false);\n// ProjectManager.getCurrentProject().mode = EnumActionMode.GRAB_KEYFRAME;\n } else {\n addUndoCommand(new UndoAssetTransform(ProjectManager.getCurrentClientLevelData(), ProjectManager.getCurrentClientLevelData().getSelectedPlaceables()));\n ProjectManager.getCurrentProject().mode = EnumActionMode.GRAB_PLACEABLE;\n }\n } else if (key == Keyboard.KEY_R) { //R: Rotate\n if (!timeline.mouseOver) { //Do nothing if the cursor is over the timeline\n addUndoCommand(new UndoAssetTransform(ProjectManager.getCurrentClientLevelData(), ProjectManager.getCurrentClientLevelData().getSelectedPlaceables()));\n ProjectManager.getCurrentProject().mode = EnumActionMode.ROTATE_PLACEABLE;\n }\n } else if (key == Keyboard.KEY_S) { //S: Scale\n if (timeline.mouseOver) { //Scale keyframes when the cursor is over the timeline\n// addUndoCommand(new UndoModifyKeyframes(ProjectManager.getCurrentClientLevelData(), this,\n// ProjectManager.getCurrentLevelData().getObjectAnimDataMap()));\n// moveSelectedKeyframesToBuffer(false);\n// ProjectManager.getCurrentProject().mode = EnumActionMode.SCALE_KEYFRAME;\n } else {\n addUndoCommand(new UndoAssetTransform(ProjectManager.getCurrentClientLevelData(), ProjectManager.getCurrentClientLevelData().getSelectedPlaceables()));\n ProjectManager.getCurrentProject().mode = EnumActionMode.SCALE_PLACEABLE;\n }\n\n } else if (key == Keyboard.KEY_Z) { //Ctrl / Cmd Z: Undo - Ctrl / Cmd Shift Z: Redo\n if (Window.isCtrlOrCmdDown()) {\n if (Window.isShiftDown()) {\n //Redo\n redo();\n } else {\n //Undo\n undo();\n }\n }\n } else if (key == Keyboard.KEY_Y) {\n if (Window.isCtrlOrCmdDown()) {\n redo();\n }\n\n } else if (key == Keyboard.KEY_DELETE) { //Delete: Remove placeables / Remove keyframes if mouse over timeline\n if (timeline.mouseOver) {\n //TODO: Keyframe deletion\n// if (\n// //Pos\n// ProjectManager.getCurrentClientLevelData().getSelectedPosXKeyframes().size() > 0 ||\n// ProjectManager.getCurrentClientLevelData().getSelectedPosYKeyframes().size() > 0 ||\n// ProjectManager.getCurrentClientLevelData().getSelectedPosZKeyframes().size() > 0 ||\n// //Rot\n// ProjectManager.getCurrentClientLevelData().getSelectedRotXKeyframes().size() > 0 ||\n// ProjectManager.getCurrentClientLevelData().getSelectedRotYKeyframes().size() > 0 ||\n// ProjectManager.getCurrentClientLevelData().getSelectedRotZKeyframes().size() > 0\n// ) {\n//\n// addUndoCommand(new UndoModifyKeyframes(ProjectManager.getCurrentClientLevelData(), this,\n// ProjectManager.getCurrentLevelData().getObjectAnimDataMap()));\n//\n// int keyframesRemoved = 0;\n//\n// //Pos\n// for (KeyframeEntry entry : ProjectManager.getCurrentClientLevelData().getSelectedPosXKeyframes()) {\n// ProjectManager.getCurrentLevelData().getObjectAnimData(entry.getObjectName()).removePosXFrame(entry.getTime());\n// keyframesRemoved++;\n// }\n//\n// for (KeyframeEntry entry : ProjectManager.getCurrentClientLevelData().getSelectedPosYKeyframes()) {\n// ProjectManager.getCurrentLevelData().getObjectAnimData(entry.getObjectName()).removePosYFrame(entry.getTime());\n// keyframesRemoved++;\n// }\n//\n// for (KeyframeEntry entry : ProjectManager.getCurrentClientLevelData().getSelectedPosZKeyframes()) {\n// ProjectManager.getCurrentLevelData().getObjectAnimData(entry.getObjectName()).removePosZFrame(entry.getTime());\n// keyframesRemoved++;\n// }\n//\n// //Rot\n// for (KeyframeEntry entry : ProjectManager.getCurrentClientLevelData().getSelectedRotXKeyframes()) {\n// ProjectManager.getCurrentLevelData().getObjectAnimData(entry.getObjectName()).removeRotXFrame(entry.getTime());\n// keyframesRemoved++;\n// }\n//\n// for (KeyframeEntry entry : ProjectManager.getCurrentClientLevelData().getSelectedRotYKeyframes()) {\n// ProjectManager.getCurrentLevelData().getObjectAnimData(entry.getObjectName()).removeRotYFrame(entry.getTime());\n// keyframesRemoved++;\n// }\n//\n// for (KeyframeEntry entry : ProjectManager.getCurrentClientLevelData().getSelectedRotZKeyframes()) {\n// ProjectManager.getCurrentLevelData().getObjectAnimData(entry.getObjectName()).removeRotZFrame(entry.getTime());\n// keyframesRemoved++;\n// }\n//\n// ProjectManager.getCurrentClientLevelData().clearSelectedKeyframes();\n//\n// if (keyframesRemoved > 1) {\n// sendNotif(String.format(LangManager.getItem(\"keyframeRemovedPlural\"), keyframesRemoved));\n// } else {\n// sendNotif(LangManager.getItem(\"keyframeRemoved\"));\n// }\n//\n// } else {\n// sendNotif(LangManager.getItem(\"nothingSelected\"));\n// }\n\n } else {\n if (ProjectManager.getCurrentClientLevelData().getSelectedPlaceables().size() > 0) {\n\n List<String> toDelete = new ArrayList<>();\n\n for (String name : new HashSet<>(ProjectManager.getCurrentClientLevelData().getSelectedPlaceables())) {\n if (!(ProjectManager.getCurrentLevelData().getPlaceable(name).getAsset() instanceof AssetStartPos) && //Don't delete the start pos\n !(ProjectManager.getCurrentLevelData().getPlaceable(name).getAsset() instanceof AssetFalloutY)) { //Don't delete the fallout Y\n toDelete.add(name);\n }\n }\n\n removePlaceables(toDelete);\n\n if (toDelete.size() > 1) {\n sendNotif(String.format(LangManager.getItem(\"placeableRemovedPlural\"), toDelete.size()));\n } else {\n sendNotif(LangManager.getItem(\"placeableRemoved\"));\n }\n\n } else {\n sendNotif(LangManager.getItem(\"nothingSelected\"));\n }\n }\n\n } else if (key == Keyboard.KEY_D && Window.isCtrlOrCmdDown()) { //Ctrl / Cmd D: Duplicate\n\n if (timeline.mouseOver) { //Duplicate keyframes when the cursor is over the timeline\n //TODO: Duplicate keyframes\n //TODO: Undo command\n// moveSelectedKeyframesToBuffer(true);\n// ProjectManager.getCurrentProject().mode = EnumActionMode.GRAB_KEYFRAME;\n\n } else {\n Set<String> selectedPlaceables = new HashSet<>(ProjectManager.getCurrentClientLevelData().getSelectedPlaceables());\n ProjectManager.getCurrentClientLevelData().clearSelectedPlaceables();\n\n Map<String, Placeable> newPlaceables = new HashMap<>();\n\n int duplicated = 0;\n\n for (String name : selectedPlaceables) {\n Placeable placeable = ProjectManager.getCurrentLevelData().getPlaceable(name);\n if (!(placeable.getAsset() instanceof AssetStartPos) &&\n !(placeable.getAsset() instanceof AssetFalloutY)) { //If the placeable isn't the start pos or fallout Y\n\n duplicated++;\n\n Placeable newPlaceable = placeable.getCopy();\n String newPlaceableName = ProjectManager.getCurrentLevelData().addPlaceable(newPlaceable);\n newPlaceables.put(newPlaceableName, newPlaceable);\n\n synchronized (outlinerPlaceablesListBoxLock) {\n outlinerPlaceablesListBox.addChildComponent(getOutlinerPlaceableComponent(newPlaceableName));\n }\n\n updateOutlinerPlaceablesPanel();\n\n ProjectManager.getCurrentClientLevelData().addSelectedPlaceable(newPlaceableName); //Select duplicated placeables\n }\n }\n\n if (duplicated > 0) {\n addUndoCommand(new UndoAddPlaceable(ProjectManager.getCurrentClientLevelData(), this, new ArrayList<>(newPlaceables.keySet()), new ArrayList<>(newPlaceables.values())));\n\n //Grab after duplicating\n addUndoCommand(new UndoAssetTransform(ProjectManager.getCurrentClientLevelData(), ProjectManager.getCurrentClientLevelData().getSelectedPlaceables()));\n ProjectManager.getCurrentProject().mode = EnumActionMode.GRAB_PLACEABLE;\n }\n }\n\n } else if (key == Keyboard.KEY_SPACE) { //Spacebar: Play / pause animation\n if (ProjectManager.getCurrentClientLevelData().getPlaybackSpeed() != 0) {\n ProjectManager.getCurrentClientLevelData().setPlaybackSpeed(0.0f);\n } else {\n ProjectManager.getCurrentClientLevelData().setPlaybackSpeed(1.0f);\n }\n\n } else if (key == Keyboard.KEY_J) { //J: Rewind animation\n if (Window.isAltDown()) { //Snap when holding alt\n float currentTime = ProjectManager.getCurrentClientLevelData().getTimelinePosSeconds();\n float snapTo = Window.isShiftDown() ? SMBLWSettings.animSnapShift : SMBLWSettings.animSnap;\n float newTime = currentTime - snapTo;\n float roundMultiplier = 1.0f / snapTo;\n float newTimeSnapped = Math.round(newTime * roundMultiplier) / roundMultiplier;\n\n ProjectManager.getCurrentClientLevelData().setTimelinePosSeconds(newTimeSnapped);\n\n } else {\n float currentSpeed = ProjectManager.getCurrentClientLevelData().getPlaybackSpeed();\n\n if (currentSpeed > 1) ProjectManager.getCurrentClientLevelData().setPlaybackSpeed(currentSpeed * 0.5f);\n else if (currentSpeed < 0) ProjectManager.getCurrentClientLevelData().setPlaybackSpeed(currentSpeed * 2.0f);\n else if (currentSpeed == 0) ProjectManager.getCurrentClientLevelData().setPlaybackSpeed(-1.0f);\n else if (currentSpeed > 0) ProjectManager.getCurrentClientLevelData().setPlaybackSpeed(0.0f);\n }\n\n } else if (key == Keyboard.KEY_K) { //K: Stop animation\n ProjectManager.getCurrentClientLevelData().setPlaybackSpeed(0.0f);\n\n } else if (key == Keyboard.KEY_L) { //L: Forward animation\n\n if (Window.isAltDown()) { //Snap when holding alt\n float currentTime = ProjectManager.getCurrentClientLevelData().getTimelinePosSeconds();\n float snapTo = Window.isShiftDown() ? SMBLWSettings.animSnapShift : SMBLWSettings.animSnap;\n float newTime = currentTime + snapTo;\n float roundMultiplier = 1.0f / snapTo;\n float newTimeSnapped = Math.round(newTime * roundMultiplier) / roundMultiplier;\n\n ProjectManager.getCurrentClientLevelData().setTimelinePosSeconds(newTimeSnapped);\n\n } else {\n float currentSpeed = ProjectManager.getCurrentClientLevelData().getPlaybackSpeed();\n\n if (currentSpeed < -1) ProjectManager.getCurrentClientLevelData().setPlaybackSpeed(currentSpeed * 0.5f);\n else if (currentSpeed > 0) ProjectManager.getCurrentClientLevelData().setPlaybackSpeed(currentSpeed * 2.0f);\n else if (currentSpeed == 0) ProjectManager.getCurrentClientLevelData().setPlaybackSpeed(1.0f);\n else if (currentSpeed < 0) ProjectManager.getCurrentClientLevelData().setPlaybackSpeed(0.0f);\n }\n\n } else {\n super.onKeyDown(key, keyChar);\n }\n\n } else if (key == Keyboard.KEY_X) { //X Axis\n ProjectManager.getCurrentProject().modeDirection = new PosXYZ(1, 0, 0);\n modeCursor.setColor(UIColor.matRed());\n } else if (key == Keyboard.KEY_Y) { //Y Axis\n ProjectManager.getCurrentProject().modeDirection = new PosXYZ(0, 1, 0);\n modeCursor.setColor(UIColor.matGreen());\n } else if (key == Keyboard.KEY_Z) { //Z Axis\n ProjectManager.getCurrentProject().modeDirection = new PosXYZ(0, 0, 1);\n modeCursor.setColor(UIColor.matBlue());\n } else if (key == Keyboard.KEY_U) { //XYZ (Uniform)\n ProjectManager.getCurrentProject().modeDirection = new PosXYZ(1, 1, 1);\n modeCursor.setColor(UIColor.matWhite());\n\n } else if (key == Keyboard.KEY_ESCAPE) {\n discardModeAction();\n } else if (key == Keyboard.KEY_RETURN) {\n confirmModeAction();\n\n } else {\n super.onKeyDown(key, keyChar);\n }\n } else {\n super.onKeyDown(key, keyChar);\n }\n }\n } else {\n super.onKeyDown(key, keyChar);\n\n if (key == Keyboard.KEY_ESCAPE) { //Deselect text fields on escape\n for (TextField textField : textFields) {\n textField.setSelected(false);\n }\n }\n }\n }\n\n }\n\n @Override\n public void onKeyReleased(int key, char keyChar) {\n inputOverlay.onKeyReleasedManual(key, keyChar);\n\n super.onKeyReleased(key, keyChar);\n }\n\n private void confirmModeAction() {\n ProjectManager.getCurrentProject().mode = EnumActionMode.NONE;\n assert ProjectManager.getCurrentClientLevelData() != null;\n commitBufferedKeyframes();\n updatePropertiesPlaceablesPanel();\n deltaX = 0; //Reset deltaX when no ProjectManager.getCurrentProject().mode is active\n }\n\n private void discardModeAction() {\n ProjectManager.getCurrentProject().mode = EnumActionMode.NONE;\n undo();\n discardBufferedKeyframes();\n deltaX = 0; //Reset deltaX when no ProjectManager.getCurrentProject().mode is active\n }\n\n public void sendNotif(String message) {\n sendNotif(message, UIColor.matGrey900());\n }\n\n public void sendNotif(String message, UIColor color) {\n for (Map.Entry<String, Component> entry : notifPanel.childComponents.entrySet()) {\n assert entry.getValue().plugins.get(1) instanceof NotificationPlugin;\n ((NotificationPlugin) entry.getValue().plugins.get(1)).time = 1.5;\n }\n\n final Panel panel = new Panel();\n panel.setOnInitAction(() -> {\n panel.setTopLeftPos(260, -80 - TIMELINE_HEIGHT);\n panel.setBottomRightPos(-260, -56 - TIMELINE_HEIGHT);\n panel.setTopLeftAnchor(0, 1.2);\n panel.setBottomRightAnchor(1, 1.2);\n panel.setBackgroundColor(color.alpha(0.75));\n });\n PluginSmoothAnimateAnchor animateAnchor = new PluginSmoothAnimateAnchor();\n panel.addPlugin(animateAnchor);\n panel.addPlugin(new NotificationPlugin(animateAnchor));\n notifPanel.addChildComponent(\"notificationPanel\" + String.valueOf(notificationID), panel);\n\n final Label label = new Label();\n label.setOnInitAction(() -> {\n label.setTopLeftPos(4, 0);\n label.setBottomRightPos(-4, 0);\n label.setTopLeftAnchor(0, 0);\n label.setBottomRightAnchor(1, 1);\n label.setText(message);\n });\n panel.addChildComponent(\"label\", label);\n\n notificationID++;\n }\n\n private void addPlaceable(Placeable placeable) {\n if (ProjectManager.getCurrentClientLevelData() != null) {\n String name = ProjectManager.getCurrentLevelData().addPlaceable(placeable);\n ProjectManager.getCurrentClientLevelData().clearSelectedPlaceables();\n ProjectManager.getCurrentClientLevelData().addSelectedPlaceable(name);\n\n addUndoCommand(new UndoAddPlaceable(ProjectManager.getCurrentClientLevelData(), this, Collections.singletonList(name), Collections.singletonList(placeable)));\n\n synchronized (outlinerPlaceablesListBoxLock) {\n outlinerPlaceablesListBox.addChildComponent(getOutlinerPlaceableComponent(name));\n }\n\n updateOutlinerPlaceablesPanel();\n } else {\n sendNotif(LangManager.getItem(\"noLevelLoaded\"), UIColor.matRed());\n }\n }\n\n private void removePlaceable(String name) {\n if (ProjectManager.getCurrentClientLevelData() != null) {\n\n addUndoCommand(new UndoRemovePlaceable(ProjectManager.getCurrentClientLevelData(), this, Collections.singletonList(name), Collections.singletonList(ProjectManager.getCurrentLevelData().getPlaceable(name))));\n\n ProjectManager.getCurrentClientLevelData().removeSelectedPlaceable(name);\n ProjectManager.getCurrentLevelData().removePlaceable(name);\n\n synchronized (outlinerPlaceablesListBoxLock) {\n outlinerPlaceablesListBox.removeChildComponent(name + \"OutlinerPlaceable\");\n }\n } else {\n sendNotif(LangManager.getItem(\"noLevelLoaded\"), UIColor.matRed());\n }\n }\n\n private void removePlaceables(List<String> names) {\n if (ProjectManager.getCurrentClientLevelData() != null) {\n\n List<Placeable> placeables = new ArrayList<>();\n for (String name : names) {\n placeables.add(ProjectManager.getCurrentLevelData().getPlaceable(name));\n }\n\n assert ProjectManager.getCurrentClientLevelData() != null;\n addUndoCommand(new UndoRemovePlaceable(ProjectManager.getCurrentClientLevelData(), this, names, placeables));\n\n for (String name : names) {\n ProjectManager.getCurrentClientLevelData().removeSelectedPlaceable(name);\n ProjectManager.getCurrentLevelData().removePlaceable(name);\n\n synchronized (outlinerPlaceablesListBoxLock) {\n outlinerPlaceablesListBox.removeChildComponent(name + \"OutlinerPlaceable\");\n }\n }\n } else {\n sendNotif(LangManager.getItem(\"noLevelLoaded\"), UIColor.matRed());\n }\n }\n\n private void newLevelData(Set<ExternalModel> externalModels, boolean replace) throws IOException {\n synchronized (renderingLock) {\n try {\n preventRendering = true;\n\n Window.drawable.makeCurrent();\n\n GL11.glFinish();\n\n if (!replace) {\n //Clear outliner list box\n synchronized (outlinerPlaceablesListBoxLock) {\n outlinerPlaceablesListBox.clearChildComponents();\n }\n\n //Reset undo history\n undoCommandList.clear();\n redoCommandList.clear();\n }\n\n if (ProjectManager.getCurrentClientLevelData() != null) {\n //Unload textures and VBOs\n ProjectManager.getCurrentLevelData().unloadAllModels();\n }\n\n if (!replace) {\n ProjectManager.getCurrentProject().clientLevelData = new ClientLevelData();\n ProjectManager.getCurrentClientLevelData().setOnSelectedPlaceablesChanged(this::onSelectedPlaceablesChanged);\n ProjectManager.getCurrentClientLevelData().setOnSelectedObjectsChanged(this::onSelectedObjectsChanged);\n ProjectManager.getCurrentClientLevelData().setOnSelectedExternalBackgroundObjectsChanged(this::onSelectedExternalBackgroundObjectsChanged);\n ProjectManager.getCurrentClientLevelData().setOnTimelinePosChanged(this::onTimelinePosChanged);\n }\n\n ProjectManager.getCurrentLevelData().clearModelObjSources();\n\n for (ExternalModel extModel : externalModels) {\n ResourceModel model = OBJLoader.loadModel(extModel.file.getPath());\n ProjectManager.getCurrentLevelData().addModel(model);\n ProjectManager.getCurrentLevelData().addModelObjSource(extModel.file);\n }\n\n synchronized (ProjectManager.getCurrentLevelData().getPlacedObjects()) {\n\n Placeable startPosPlaceable;\n String startPosPlaceableName = null;\n Placeable falloutYPlaceable;\n String falloutYPlaceableName = null;\n if (!replace) {\n startPosPlaceable = new Placeable(new AssetStartPos());\n startPosPlaceable.setPosition(new PosXYZ(0, 1, 0));\n startPosPlaceableName = ProjectManager.getCurrentLevelData().addPlaceable(\n LangManager.getItem(\"assetStartPos\"), startPosPlaceable, \"STAGE_RESERVED\");\n\n if (objectMode == EnumObjectMode.PLACEABLE_EDIT) {\n ProjectManager.getCurrentClientLevelData().addSelectedPlaceable(startPosPlaceableName);\n }\n\n falloutYPlaceable = new Placeable(new AssetFalloutY());\n falloutYPlaceable.setPosition(new PosXYZ(0, -10, 0));\n falloutYPlaceableName = ProjectManager.getCurrentLevelData().addPlaceable(\n LangManager.getItem(\"assetFalloutY\"), falloutYPlaceable, \"STAGE_RESERVED\");\n\n }\n\n Window.drawable.makeCurrent();\n\n if (!replace) {\n synchronized (outlinerPlaceablesListBoxLock) {\n outlinerPlaceablesListBox.addChildComponent(getOutlinerPlaceableComponent(startPosPlaceableName));\n outlinerPlaceablesListBox.addChildComponent(getOutlinerPlaceableComponent(falloutYPlaceableName));\n }\n\n updateOutlinerPlaceablesPanel();\n }\n\n }\n\n if (replace) {\n //Remove selected objects if they no longer exist in the new OBJ\n for (String name : ProjectManager.getCurrentClientLevelData().getSelectedObjects()) {\n for (ResourceModel model : ProjectManager.getCurrentLevelData().getModels()) {\n if (!model.hasObject(name)) {\n ProjectManager.getCurrentClientLevelData().removeSelectedObject(name);\n }\n }\n }\n\n //Remove objects if they no longer exist in the new OBJ\n Set<String> allObjectNames = new HashSet<>();\n for (Map.Entry<String, WSItemGroup> entry : ProjectManager.getCurrentLevelData().getItemGroupMap().entrySet()) {\n allObjectNames.addAll(entry.getValue().getObjectNames());\n }\n for (ResourceModel model : ProjectManager.getCurrentLevelData().getModels()) {\n for (OBJObject object : model.scene.getObjectList()) {\n if (!allObjectNames.contains(object.name)) {\n ProjectManager.getCurrentLevelData().removeObject(name);\n }\n }\n }\n\n } else {\n ProjectManager.getCurrentClientLevelData().clearSelectedObjects();\n //TODO: Update timeline\n// timeline.setObjectAnimDataMap(ProjectManager.getCurrentLevelData().getObjectAnimDataMap());\n }\n\n if (!OBJLoader.isLastObjTriangulated) {\n setOverlayUiScreen(new DialogOverlayUIScreen(LangManager.getItem(\"warning\"), LangManager.getItem(\"notTriangulated\")));\n }\n\n synchronized (outlinerObjectsListBoxLock) {\n outlinerObjectsListBox.clearChildComponents();\n\n ProjectManager.getCurrentClientLevelData().clearHiddenObjects(); //Unhide all objects\n\n for (ResourceModel model : ProjectManager.getCurrentLevelData().getModels()) {\n for (OBJObject object : model.scene.getObjectList()) {\n outlinerObjectsListBox.addChildComponent(getOutlinerObjectComponent(object.name));\n }\n }\n }\n\n if (replace) {\n //Replace all external background objects in the objects outliner that were removed\n for (String name : ProjectManager.getCurrentLevelData().getBackgroundExternalObjects()) {\n outlinerObjectsListBox.addChildComponent(getOutlinerExternalBackgroundObjectComponent(name));\n }\n\n //Delete all specified level models that no longer exist, and add new level models to the first item group\n Set<String> existingModels = new HashSet<>();\n for (Map.Entry<String, WSItemGroup> entry : ProjectManager.getCurrentLevelData().getItemGroupMap().entrySet()) {\n WSItemGroup itemGroup = entry.getValue();\n\n Set<String> removedObjects = new HashSet<>();\n for (ResourceModel model : ProjectManager.getCurrentLevelData().getModels()) {\n for (String name : itemGroup.getObjectNames())\n if (!model.hasObject(name)) {\n removedObjects.add(name);\n }\n }\n itemGroup.removeObjects(removedObjects);\n\n existingModels.addAll(itemGroup.getObjectNames());\n }\n existingModels.addAll(ProjectManager.getCurrentLevelData().getBackgroundObjects());\n\n //Fetch a list of all new models\n Set<String> newModels = new HashSet<>();\n for (ResourceModel model : ProjectManager.getCurrentLevelData().getModels()) {\n for (OBJObject obj : model.scene.getObjectList()) {\n if (!existingModels.contains(obj.name)) {\n //It's new\n newModels.add(obj.name);\n }\n }\n }\n\n //Add the new models to the first item group\n ProjectManager.getCurrentLevelData().getFirstItemGroup().addObjects(newModels);\n } else {\n //Not replacing - Add everything to the first item group\n for (ResourceModel model : ProjectManager.getCurrentLevelData().getModels()) {\n for (OBJObject obj : model.scene.getObjectList()) {\n ProjectManager.getCurrentLevelData().getFirstItemGroup().addObject(obj.name);\n }\n }\n }\n\n //Update the timeline\n timeline.updatePercent(ProjectManager.getCurrentClientLevelData().getTimelinePos());\n timeline.updateMaxAndLeadInTime(ProjectManager.getCurrentLevelData().getMaxTime(),\n ProjectManager.getCurrentLevelData().getLeadInTime());\n\n GL11.glFlush();\n\n Window.drawable.releaseContext();\n } catch (LWJGLException e) {\n LogHelper.error(getClass(), e);\n }\n\n preventRendering = false;\n }\n }\n\n public void addUndoCommand(UndoCommand undoCommand) {\n undoCommandList.add(undoCommand);\n redoCommandList.clear();\n }\n\n private void undo() {\n if (undoCommandList.size() > 0) {\n redoCommandList.add(undoCommandList.get(undoCommandList.size() - 1).getRedoCommand());\n undoCommandList.get(undoCommandList.size() - 1).undo();\n sendNotif(undoCommandList.get(undoCommandList.size() - 1).getUndoMessage());\n undoCommandList.remove(undoCommandList.size() - 1);\n\n updatePropertiesPlaceablesPanel();\n updatePropertiesObjectsPanel();\n updateOutlinerPlaceablesPanel();\n updateOutlinerObjectsPanel();\n }\n\n }\n\n private void redo() {\n if (redoCommandList.size() > 0) {\n undoCommandList.add(redoCommandList.get(redoCommandList.size() - 1).getRedoCommand());\n redoCommandList.get(redoCommandList.size() - 1).undo();\n sendNotif(redoCommandList.get(redoCommandList.size() - 1).getRedoMessage());\n redoCommandList.remove(redoCommandList.size() - 1);\n\n updatePropertiesPlaceablesPanel();\n updatePropertiesObjectsPanel();\n updateOutlinerPlaceablesPanel();\n updateOutlinerObjectsPanel();\n }\n }\n\n public Component getOutlinerPlaceableComponent(String name) {\n final ItemButton placeableButton = new ItemButton();\n placeableButton.setOnInitAction(() -> {\n placeableButton.setTopLeftPos(0, 0);\n placeableButton.setBottomRightPos(0, 18);\n placeableButton.setId(name);\n placeableButton.setItemGroupCol(ProjectManager.getCurrentLevelData().getPlaceableItemGroup(name).getColor());\n });\n placeableButton.setOnLMBAction(() -> {\n assert ProjectManager.getCurrentClientLevelData() != null;\n\n if (Window.isShiftDown()) { //Toggle selection on shift\n ProjectManager.getCurrentClientLevelData().toggleSelectedPlaceable(name);\n } else {\n ProjectManager.getCurrentClientLevelData().clearSelectedExternalBackgroundObjects();\n ProjectManager.getCurrentClientLevelData().clearSelectedPlaceables();\n ProjectManager.getCurrentClientLevelData().addSelectedPlaceable(name);\n }\n });\n placeableButton.setName(name + \"OutlinerPlaceable\");\n\n return placeableButton;\n }\n\n public Component getOutlinerObjectComponent(String name) {\n final OutlinerObject outlinerObject = new OutlinerObject(name);\n outlinerObject.setOnInitAction(() -> {\n outlinerObject.setTopLeftPos(0, 0);\n outlinerObject.setBottomRightPos(0, 18);\n });\n\n return outlinerObject;\n }\n\n public Component getOutlinerExternalBackgroundObjectComponent(String name) {\n final TextButton objectButton = new TextButton();\n objectButton.setOnInitAction(() -> {\n objectButton.setTopLeftPos(0, 0);\n objectButton.setBottomRightPos(0, 18);\n objectButton.setText(name);\n objectButton.setBackgroundIdleColor(UIColor.matPink());\n });\n objectButton.setOnLMBAction(() -> {\n assert ProjectManager.getCurrentClientLevelData() != null;\n\n if (Window.isShiftDown()) { //Toggle selection on shift\n ProjectManager.getCurrentClientLevelData().toggleSelectedExternalBackgroundObject(name);\n } else {\n ProjectManager.getCurrentClientLevelData().clearSelectedExternalBackgroundObjects();\n ProjectManager.getCurrentClientLevelData().clearSelectedObjects();\n ProjectManager.getCurrentClientLevelData().addSelectedExternalBackgroundObject(name);\n }\n });\n objectButton.setName(name + \"OutlinerObject\");\n\n return objectButton;\n }\n\n private void importObj() {\n if (!isLoadingProject) {\n new Thread(() -> {\n isLoadingProject = true;\n importObjButton.setEnabled(false);\n importConfigButton.setEnabled(false);\n exportButton.setEnabled(false);\n settingsButton.setEnabled(false);\n projectSettingsButton.setEnabled(false);\n FileDialog fd = new FileDialog((Frame) null);\n fd.setMode(FileDialog.LOAD);\n fd.setFilenameFilter((dir, filename) -> filename.toUpperCase().endsWith(\".OBJ\"));\n fd.setVisible(true);\n\n File[] files = fd.getFiles();\n if (files != null && files.length > 0) {\n File file = files[0];\n LogHelper.info(getClass(), \"Opening file: \" + file.getAbsolutePath());\n\n try {\n if (ProjectManager.getCurrentClientLevelData() != null) {\n AskReplaceObjOverlayUIScreen dialog = new AskReplaceObjOverlayUIScreen();\n setOverlayUiScreen(dialog);\n boolean shouldRepalce = dialog.waitForShouldReplaceResponse();\n newLevelData(Collections.singleton(new ExternalModel(file, ModelType.OBJ)), shouldRepalce);\n } else {\n newLevelData(Collections.singleton(new ExternalModel(file, ModelType.OBJ)), false);\n }\n\n updateOutlinerObjectsPanel();\n } catch (IOException e) {\n LogHelper.error(getClass(), \"Failed to open file\");\n LogHelper.error(getClass(), e);\n }\n }\n projectSettingsButton.setEnabled(true);\n settingsButton.setEnabled(true);\n exportButton.setEnabled(true);\n importConfigButton.setEnabled(true);\n importObjButton.setEnabled(true);\n isLoadingProject = false;\n }, \"ObjFileOpenThread\").start();\n } else {\n LogHelper.warn(getClass(), \"Tried importing OBJ when already importing OBJ\");\n }\n }\n\n private void export() {\n if (!isLoadingProject) {\n if (ProjectManager.getCurrentClientLevelData() != null) {\n setOverlayUiScreen(new ExportOverlayUIScreen());\n } else {\n sendNotif(LangManager.getItem(\"noLevelLoaded\"), UIColor.matRed());\n }\n }\n }\n\n private void onSelectedPlaceablesChanged() {\n updatePropertiesPlaceablesPanel();\n updateOutlinerPlaceablesPanel();\n }\n\n public void updatePropertiesPlaceablesPanel() {\n double posAvgX = 0;\n boolean canGrabX = false;\n double posAvgY = 0;\n boolean canGrabY = false;\n double posAvgZ = 0;\n boolean canGrabZ = false;\n\n double rotAvgX = 0;\n double rotAvgY = 0;\n double rotAvgZ = 0;\n boolean canRotate = false;\n\n double sclAvgX = 0;\n double sclAvgY = 0;\n double sclAvgZ = 0;\n boolean canScale = false;\n\n assert ProjectManager.getCurrentClientLevelData() != null;\n\n Class<?> selectedIAsset;\n if (ProjectManager.getCurrentClientLevelData().getSelectedPlaceables().size() > 0) {\n selectedIAsset = ProjectManager.getCurrentLevelData().getPlaceable(ProjectManager.getCurrentClientLevelData().getSelectedPlaceables().iterator().next()).getAsset().getClass();\n } else {\n selectedIAsset = null;\n }\n\n for (String name : ProjectManager.getCurrentClientLevelData().getSelectedPlaceables()) {\n Placeable placeable = ProjectManager.getCurrentLevelData().getPlaceable(name);\n\n if (placeable.getAsset().canGrabX()) {\n canGrabX = true;\n posAvgX += placeable.getPosition().x;\n }\n if (placeable.getAsset().canGrabY()) {\n canGrabY = true;\n posAvgY += placeable.getPosition().y;\n }\n if (placeable.getAsset().canGrabZ()) {\n canGrabZ = true;\n posAvgZ += placeable.getPosition().z;\n }\n\n if (placeable.getAsset().canRotate()) {\n canRotate = true;\n\n rotAvgX += placeable.getRotation().x;\n rotAvgY += placeable.getRotation().y;\n rotAvgZ += placeable.getRotation().z;\n }\n\n if (placeable.getAsset().canScale()) {\n canScale = true;\n\n sclAvgX += placeable.getScale().x;\n sclAvgY += placeable.getScale().y;\n sclAvgZ += placeable.getScale().z;\n } else {\n sclAvgX += 1;\n sclAvgY += 1;\n sclAvgZ += 1;\n }\n\n if (selectedIAsset != null && !placeable.getAsset().getClass().isAssignableFrom(selectedIAsset)) {\n selectedIAsset = null;\n }\n }\n\n int selectedCount = ProjectManager.getCurrentClientLevelData().getSelectedPlaceables().size();\n\n if (selectedCount != 0) {\n posAvgX = posAvgX / (double) selectedCount;\n posAvgY = posAvgY / (double) selectedCount;\n posAvgZ = posAvgZ / (double) selectedCount;\n\n if (canGrabX) {\n placeablePositionTextFields.setXEnabled(true);\n } else {\n placeablePositionTextFields.setXEnabled(false);\n placeablePositionTextFields.setXValue(0);\n }\n if (canGrabY) {\n placeablePositionTextFields.setYEnabled(true);\n } else {\n placeablePositionTextFields.setYEnabled(false);\n placeablePositionTextFields.setYValue(0);\n }\n if (canGrabZ) {\n placeablePositionTextFields.setZEnabled(true);\n } else {\n placeablePositionTextFields.setZEnabled(false);\n placeablePositionTextFields.setZValue(0);\n }\n\n placeablePositionTextFields.setXValue(posAvgX);\n placeablePositionTextFields.setYValue(posAvgY);\n placeablePositionTextFields.setZValue(posAvgZ);\n } else {\n placeablePositionTextFields.setXEnabled(false);\n placeablePositionTextFields.setYEnabled(false);\n placeablePositionTextFields.setZEnabled(false);\n\n placeablePositionTextFields.setXValue(0);\n placeablePositionTextFields.setYValue(0);\n placeablePositionTextFields.setZValue(0);\n }\n\n if (selectedCount != 0 && canRotate) {\n rotAvgX = rotAvgX / (double) selectedCount;\n rotAvgY = rotAvgY / (double) selectedCount;\n rotAvgZ = rotAvgZ / (double) selectedCount;\n\n placeableRotationTextFields.setXEnabled(true);\n placeableRotationTextFields.setYEnabled(true);\n placeableRotationTextFields.setZEnabled(true);\n\n placeableRotationTextFields.setXValue(rotAvgX);\n placeableRotationTextFields.setYValue(rotAvgY);\n placeableRotationTextFields.setZValue(rotAvgZ);\n } else {\n placeableRotationTextFields.setXEnabled(false);\n placeableRotationTextFields.setYEnabled(false);\n placeableRotationTextFields.setZEnabled(false);\n\n placeableRotationTextFields.setXValue(0);\n placeableRotationTextFields.setYValue(0);\n placeableRotationTextFields.setZValue(0);\n }\n\n if (selectedCount != 0 && canScale) {\n sclAvgX = sclAvgX / (double) selectedCount;\n sclAvgY = sclAvgY / (double) selectedCount;\n sclAvgZ = sclAvgZ / (double) selectedCount;\n\n placeableScaleTextFields.setXEnabled(true);\n placeableScaleTextFields.setYEnabled(true);\n placeableScaleTextFields.setZEnabled(true);\n\n placeableScaleTextFields.setXValue(sclAvgX);\n placeableScaleTextFields.setYValue(sclAvgY);\n placeableScaleTextFields.setZValue(sclAvgZ);\n } else {\n placeableScaleTextFields.setXEnabled(false);\n placeableScaleTextFields.setYEnabled(false);\n placeableScaleTextFields.setZEnabled(false);\n\n placeableScaleTextFields.setXValue(1);\n placeableScaleTextFields.setYValue(1);\n placeableScaleTextFields.setZValue(1);\n }\n\n if (selectedCount > 0) {\n boolean stageReservedOnly = true;\n for (String name : ProjectManager.getCurrentClientLevelData().getSelectedPlaceables()) {\n String igName = ProjectManager.getCurrentLevelData().getPlaceableItemGroupName(name);\n if (!Objects.equals(igName, \"STAGE_RESERVED\")) {\n stageReservedOnly = false;\n break;\n }\n }\n\n placeableItemGroupButton.setEnabled(!stageReservedOnly);\n\n String commonItemGroup = null; //The name of an item group if all selected placeables have belong to the same item group, or null if the don't\n\n for (String name : ProjectManager.getCurrentClientLevelData().getSelectedPlaceables()) {\n String igName = ProjectManager.getCurrentLevelData().getPlaceableItemGroupName(name);\n if (commonItemGroup == null) {\n commonItemGroup = igName;\n }\n\n if (!Objects.equals(commonItemGroup, igName)) {\n commonItemGroup = null;\n break;\n }\n }\n\n if (commonItemGroup != null) {\n placeableItemGroupButton.setText(commonItemGroup);\n } else {\n placeableItemGroupButton.setText(\"...\");\n }\n } else {\n placeableItemGroupButton.setEnabled(false);\n placeableItemGroupButton.setText(LangManager.getItem(\"nothingSelected\"));\n }\n\n if (selectedIAsset != null) {\n String[] types = ProjectManager.getCurrentLevelData().getPlaceable(ProjectManager.getCurrentClientLevelData().getSelectedPlaceables().iterator().next()).getAsset().getValidTypes();\n\n if (types != null) {\n typeList = Arrays.asList(types);\n typeButton.setText(LangManager.getItem(ProjectManager.getCurrentLevelData().getPlaceable(ProjectManager.getCurrentClientLevelData().getSelectedPlaceables().iterator().next()).getAsset().getType()));\n typeButton.setEnabled(true);\n } else {\n typeList = null;\n typeButton.setText(LangManager.getItem(\"noTypes\"));\n typeButton.setEnabled(false);\n }\n } else {\n typeList = null;\n typeButton.setText(LangManager.getItem(\"noTypes\"));\n typeButton.setEnabled(false);\n }\n\n }\n\n private void onSelectedObjectsChanged() {\n updatePropertiesObjectsPanel();\n updateOutlinerObjectsPanel();\n timeline.setSelectedObjects(ProjectManager.getCurrentClientLevelData().getSelectedObjects());\n }\n\n public void updatePropertiesObjectsPanel() {\n int selectedCount = ProjectManager.getCurrentClientLevelData().getSelectedObjects().size();\n if (selectedCount > 0) {\n boolean stageReservedOnly = true;\n for (String name : ProjectManager.getCurrentClientLevelData().getSelectedObjects()) {\n String igName = ProjectManager.getCurrentLevelData().getObjectItemGroupName(name);\n if (!Objects.equals(igName, \"STAGE_RESERVED\")) {\n stageReservedOnly = false;\n break;\n }\n }\n\n objectItemGroupButton.setEnabled(!stageReservedOnly);\n\n String commonItemGroup = null; //The name of an item group if all selected objects have belong to the same item group, or null if the don't\n\n for (String name : ProjectManager.getCurrentClientLevelData().getSelectedObjects()) {\n String igName = ProjectManager.getCurrentLevelData().getObjectItemGroupName(name);\n if (commonItemGroup == null) {\n commonItemGroup = igName;\n }\n\n if (!Objects.equals(commonItemGroup, igName)) {\n commonItemGroup = null;\n break;\n }\n }\n\n if (commonItemGroup != null) {\n objectItemGroupButton.setText(commonItemGroup);\n } else {\n objectItemGroupButton.setText(\"...\");\n }\n } else {\n objectItemGroupButton.setEnabled(false);\n objectItemGroupButton.setText(LangManager.getItem(\"nothingSelected\"));\n }\n }\n\n private void updateOutlinerPlaceablesPanel() {\n if (ProjectManager.getCurrentClientLevelData() != null) {\n //<editor-fold desc=\"Darken selected placeables in the outliner\">\n synchronized (outlinerPlaceablesListBoxLock) {\n for (Map.Entry<String, Component> entry : outlinerPlaceablesListBox.childComponents.entrySet()) {\n ItemButton button = (ItemButton) entry.getValue();\n\n button.setItemGroupCol(ProjectManager.getCurrentLevelData().getPlaceableItemGroup(button.getId()).getColor());\n\n if (ProjectManager.getCurrentClientLevelData().isPlaceableSelected(button.getId())) {\n// button.setBackgroundIdleColor(UIColor.matBlue900());\n button.setSelected(true);\n } else {\n// button.setBackgroundIdleColor(UIColor.matBlue());\n button.setSelected(false);\n }\n }\n }\n //</editor-fold>\n }\n }\n\n private void updateOutlinerObjectsPanel() {\n //<editor-fold desc=\"Darken selected object in the outliner\">\n synchronized (outlinerObjectsListBoxLock) {\n for (Map.Entry<String, Component> entry : outlinerObjectsListBox.childComponents.entrySet()) {\n assert entry.getValue() instanceof OutlinerObject;\n OutlinerObject outlinerObject = (OutlinerObject) entry.getValue();\n\n outlinerObject.setButtonColor(getOutlinerObjectColor(outlinerObject.getObjectName()));\n }\n }\n //</editor-fold>\n }\n\n private void onSelectedExternalBackgroundObjectsChanged() {\n updatePropertiesObjectsPanel();\n updateOutlinerObjectsPanel();\n }\n\n @Deprecated\n private UIColor getOutlinerObjectColor(String name) {\n if (ProjectManager.getCurrentClientLevelData().isObjectSelected(name)) {\n return UIColor.matBlue900();\n } else {\n return UIColor.matBlue();\n }\n// if (ProjectManager.getCurrentLevelData().isObjectBackground(name)) {\n// if (ProjectManager.getCurrentClientLevelData().isObjectSelected(name)) {\n// return UIColor.matPurple900();\n// } else {\n// return UIColor.matPurple();\n// }\n// } else if (ProjectManager.getCurrentLevelData().isObjectBackgroundExternal(name)) {\n// if (ProjectManager.getCurrentClientLevelData().isExternalBackgroundObjectSelected(name)) {\n// return UIColor.matPink900();\n// } else {\n// return UIColor.matPink();\n// }\n// } else if (ProjectManager.getCurrentLevelData().doesObjectHaveAnimData(name)) {\n// if (ProjectManager.getCurrentClientLevelData().isObjectSelected(name)) {\n// return UIColor.matGreen900();\n// } else {\n// return UIColor.matGreen();\n// }\n// } else {\n// if (ProjectManager.getCurrentClientLevelData().isObjectSelected(name)) {\n// return UIColor.matBlue900();\n// } else {\n// return UIColor.matBlue();\n// }\n//\n }\n\n private IUIScreen getTypeSelectorOverlayScreen(double mouseY) {\n final double mousePercentY = mouseY / Display.getHeight();\n\n return new TypeSelectorOverlayScreen(mousePercentY, typeList);\n }\n\n private IUIScreen getItemGroupSelectorOverlayScreen(double mouseX, double mouseY) {\n final double mousePercentY = mouseY / Display.getHeight();\n\n return new ItemGroupSelectorOverlayScreen(mousePercentY, ProjectManager.getCurrentLevelData().getItemGroupMap());\n }\n\n public void setTypeForSelectedPlaceables(String type) {\n boolean changed = false;\n\n assert ProjectManager.getCurrentClientLevelData() != null;\n for (String name : ProjectManager.getCurrentClientLevelData().getSelectedPlaceables()) {\n Placeable placeable = ProjectManager.getCurrentLevelData().getPlaceable(name);\n\n if (!Objects.equals(placeable.getAsset().getType(), type)) {\n changed = true;\n }\n }\n\n if (changed) {\n addUndoCommand(new UndoAssetTypeChange(ProjectManager.getCurrentClientLevelData(), ProjectManager.getCurrentClientLevelData().getSelectedPlaceables()));\n }\n\n for (String name : ProjectManager.getCurrentClientLevelData().getSelectedPlaceables()) {\n Placeable placeable = ProjectManager.getCurrentLevelData().getPlaceable(name);\n\n placeable.getAsset().setType(type);\n }\n\n updatePropertiesPlaceablesPanel();\n }\n\n public void setItemGroupForSelectedPlaceables(String itemGroup) {\n boolean changed = false;\n\n assert ProjectManager.getCurrentClientLevelData() != null;\n for (String name : ProjectManager.getCurrentClientLevelData().getSelectedPlaceables()) {\n if (!Objects.equals(ProjectManager.getCurrentLevelData().getPlaceableItemGroupName(name), itemGroup)) {\n changed = true;\n }\n }\n\n if (changed) {\n addUndoCommand(new UndoPlaceableItemGroupChange(ProjectManager.getCurrentClientLevelData(), ProjectManager.getCurrentClientLevelData().getSelectedPlaceables()));\n }\n\n for (String name : ProjectManager.getCurrentClientLevelData().getSelectedPlaceables()) {\n Placeable placeable = ProjectManager.getCurrentLevelData().getPlaceable(name);\n\n if (placeable.getAsset() instanceof AssetStartPos || placeable.getAsset() instanceof AssetFalloutY) continue; //Start pos and fallout Y cannot change item groups\n\n ProjectManager.getCurrentLevelData().changePlaceableItemGroup(name, itemGroup);\n }\n\n updateOutlinerPlaceablesPanel();\n updatePropertiesPlaceablesPanel();\n }\n\n public void setItemGroupForSelectedObjects(String itemGroup) {\n boolean changed = false;\n\n assert ProjectManager.getCurrentClientLevelData() != null;\n for (String name : ProjectManager.getCurrentClientLevelData().getSelectedObjects()) {\n if (!Objects.equals(ProjectManager.getCurrentLevelData().getObjectItemGroupName(name), itemGroup)) {\n changed = true;\n }\n }\n\n if (changed) {\n addUndoCommand(new UndoObjectItemGroupChange(ProjectManager.getCurrentClientLevelData(), ProjectManager.getCurrentClientLevelData().getSelectedObjects()));\n }\n\n for (String name : ProjectManager.getCurrentClientLevelData().getSelectedObjects()) {\n ProjectManager.getCurrentLevelData().changeObjectItemGroup(name, itemGroup);\n }\n\n updateOutlinerObjectsPanel();\n updatePropertiesObjectsPanel();\n }\n\n private void showSettings() {\n setOverlayUiScreen(new SettingsOverlayUIScreen());\n }\n\n private void showProjectSettings() {\n if (ProjectManager.getCurrentProject() != null && ProjectManager.getCurrentClientLevelData() != null) {\n setOverlayUiScreen(new ProjectSettingsOverlayUIScreen());\n } else {\n sendNotif(LangManager.getItem(\"noLevelLoaded\"), UIColor.matRed());\n }\n }\n\n private ResourceShaderProgram getCurrentShader() {\n if (SMBLWSettings.showTextures) {\n if (SMBLWSettings.isUnlit) {\n return ResourceManager.getShaderProgram(\"texUnlitShaderProgram\");\n } else {\n return ResourceManager.getShaderProgram(\"texShaderProgram\");\n }\n } else {\n if (SMBLWSettings.isUnlit) {\n return ResourceManager.getShaderProgram(\"colUnlitShaderProgram\");\n } else {\n return ResourceManager.getShaderProgram(\"colShaderProgram\");\n }\n }\n }\n\n private boolean isCurrentShaderTextured() {\n return SMBLWSettings.showTextures;\n }\n\n private double getDistance(PosXYZ p1, PosXYZ p2) {\n return Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2) + Math.pow(p2.z - p1.z, 2));\n }\n\n private void importConfig() {\n boolean xmlOnly;\n\n //Only allow XML configs when no OBJ loaded\n if (ProjectManager.getCurrentProject() != null && ProjectManager.getCurrentClientLevelData() != null) {\n xmlOnly = false;\n } else {\n xmlOnly = true;\n// sendNotif(LangManager.getItem(\"noLevelLoaded\"), UIColor.matRed());\n }\n\n if (!isLoadingProject) {\n new Thread(() -> {\n isLoadingProject = true;\n importObjButton.setEnabled(false);\n importConfigButton.setEnabled(false);\n exportButton.setEnabled(false);\n settingsButton.setEnabled(false);\n projectSettingsButton.setEnabled(false);\n FileDialog fd = new FileDialog((Frame) null);\n fd.setMode(FileDialog.LOAD);\n if (xmlOnly) {\n fd.setFilenameFilter((dir, filename) -> filename.toUpperCase().endsWith(\".XML\"));\n } else {\n fd.setFilenameFilter((dir, filename) -> filename.toUpperCase().endsWith(\".TXT\") || filename.toUpperCase().endsWith(\".XML\"));\n }\n fd.setVisible(true);\n\n File[] files = fd.getFiles();\n if (files != null && files.length > 0) {\n File file = files[0];\n LogHelper.info(getClass(), \"Opening file: \" + file.getAbsolutePath());\n\n try {\n ConfigData configData = new ConfigData();\n if (file.getName().toUpperCase().endsWith(\".XML\")) {\n //Assume XML config file\n XMLConfigParser.parseConfig(configData, file);\n\n if (ProjectManager.getCurrentClientLevelData() != null) {\n newLevelData(configData.models, true);\n } else {\n newLevelData(configData.models, false); //No client level data - Don't replace as there's nothing to replace\n }\n\n\n } else {\n //Assume smbcnv config file\n SMBCnvConfigParser.parseConfig(configData, file);\n }\n\n ClientLevelData cld = ProjectManager.getCurrentClientLevelData();\n LevelData ld = cld.getLevelData();\n\n synchronized (ProjectManager.getCurrentLevelData().getPlacedObjects()) {\n\n //TODO: Replace with clear item groups instead\n\n cld.clearSelectedPlaceables();\n ld.clearPlacedObjects();\n ld.clearBackgroundObjects();\n outlinerPlaceablesListBox.clearChildComponents();\n\n cld.clearSelectedKeyframes();\n\n //Add start pos\n if (configData.startList.size() > 0) {\n Start start = configData.startList.entrySet().iterator().next().getValue();\n Placeable startPlaceable = new Placeable(new AssetStartPos());\n startPlaceable.setPosition(new PosXYZ(start.pos.x, start.pos.y, start.pos.z));\n startPlaceable.setRotation(new PosXYZ(start.rot.x, start.rot.y, start.rot.z));\n String name = ld.addPlaceable(LangManager.getItem(\"assetStartPos\"), startPlaceable, \"STAGE_RESERVED\");\n outlinerPlaceablesListBox.addChildComponent(getOutlinerPlaceableComponent(name));\n } else {\n //No start found - use default start\n Placeable startPlaceable = new Placeable(new AssetStartPos());\n startPlaceable.setPosition(new PosXYZ(0, 1, 0));\n String name = ld.addPlaceable(LangManager.getItem(\"assetStartPos\"), startPlaceable, \"STAGE_RESERVED\");\n outlinerPlaceablesListBox.addChildComponent(getOutlinerPlaceableComponent(name));\n }\n\n //Add fallout y\n Placeable falloutPlaceable = new Placeable(new AssetFalloutY());\n falloutPlaceable.setPosition(new PosXYZ(0, configData.falloutPlane, 0));\n String falloutName = ld.addPlaceable(LangManager.getItem(\"assetFalloutY\"), falloutPlaceable, \"STAGE_RESERVED\");\n outlinerPlaceablesListBox.addChildComponent(getOutlinerPlaceableComponent(falloutName));\n\n //Add goals\n for (Map.Entry<String, Goal> entry : configData.getFirstItemGroup().goalList.entrySet()) { //TODO: Forced to use static item group\n Goal goal = entry.getValue();\n Placeable goalPlaceable = new Placeable(new AssetGoal());\n goalPlaceable.setPosition(new PosXYZ(goal.pos));\n goalPlaceable.setRotation(new PosXYZ(goal.rot));\n\n String type = \"blueGoal\";\n //Type 0 = blueGoal\n if (goal.type == Goal.EnumGoalType.GREEN) {\n type = \"greenGoal\";\n } else if (goal.type == Goal.EnumGoalType.RED) {\n type = \"redGoal\";\n }\n\n goalPlaceable.getAsset().setType(type);\n String name = ld.addPlaceable(entry.getKey(), goalPlaceable);\n outlinerPlaceablesListBox.addChildComponent(getOutlinerPlaceableComponent(name));\n }\n\n //Add bumpers\n for (Map.Entry<String, Bumper> entry : configData.getFirstItemGroup().bumperList.entrySet()) { //TODO: Forced to use static item group\n Bumper bumper = entry.getValue();\n Placeable bumperPlaceable = new Placeable(new AssetBumper());\n bumperPlaceable.setPosition(new PosXYZ(bumper.pos));\n bumperPlaceable.setRotation(new PosXYZ(bumper.rot));\n bumperPlaceable.setScale(new PosXYZ(bumper.scl));\n\n String name = ld.addPlaceable(entry.getKey(), bumperPlaceable);\n outlinerPlaceablesListBox.addChildComponent(getOutlinerPlaceableComponent(name));\n }\n\n //Add jamabars\n for (Map.Entry<String, Jamabar> entry : configData.getFirstItemGroup().jamabarList.entrySet()) { //TODO: Forced to use static item group\n Jamabar jamabar = entry.getValue();\n Placeable jamabarPlaceable = new Placeable(new AssetJamabar());\n jamabarPlaceable.setPosition(new PosXYZ(jamabar.pos));\n jamabarPlaceable.setRotation(new PosXYZ(jamabar.rot));\n jamabarPlaceable.setScale(new PosXYZ(jamabar.scl));\n\n String name = ld.addPlaceable(entry.getKey(), jamabarPlaceable);\n outlinerPlaceablesListBox.addChildComponent(getOutlinerPlaceableComponent(name));\n }\n\n //Add bananas\n for (Map.Entry<String, Banana> entry : configData.getFirstItemGroup().bananaList.entrySet()) { //TODO: Forced to use static item group\n Banana banana = entry.getValue();\n Placeable bananaPlaceable = new Placeable(new AssetBanana());\n bananaPlaceable.setPosition(new PosXYZ(banana.pos));\n\n String type = \"singleBanana\";\n //Type 0 = singleBanana\n if (banana.type == Banana.EnumBananaType.BUNCH) {\n type = \"bunchBanana\";\n }\n\n bananaPlaceable.getAsset().setType(type);\n String name = ld.addPlaceable(entry.getKey(), bananaPlaceable);\n outlinerPlaceablesListBox.addChildComponent(getOutlinerPlaceableComponent(name));\n }\n\n //TODO: Add wormholes and fallout volumes\n\n //Mark background objects\n for (String name : configData.backgroundList) {\n for (ResourceModel model : ld.getModels()) {\n if (model.hasObject(name)) {\n ld.changeObjectItemGroup(name, \"BACKGROUND_RESERVED\");\n }\n }\n }\n\n //Set max time\n ld.setMaxTime(configData.maxTime);\n ld.setLeadInTime(configData.leadInTime);\n\n //Add anim data //TODO: Revamp for item groups\n// for (Map.Entry<String, ConfigAnimData> entry : configData.animDataMap.entrySet()) {\n// if (ld.getModel().hasObject(entry.getValue().getObjectName())) {\n// ld.setAnimData(entry.getValue().getObjectName(), new AnimData(entry.getValue()));\n// }\n// }\n\n }\n\n updateOutlinerPlaceablesPanel();\n updateOutlinerObjectsPanel();\n } catch (IOException e) {\n LogHelper.error(getClass(), \"Failed to open file\");\n LogHelper.error(getClass(), e);\n } catch (SAXException | ParserConfigurationException e) {\n LogHelper.error(getClass(), \"Failed to parse XML file\");\n LogHelper.error(getClass(), e);\n }\n }\n projectSettingsButton.setEnabled(true);\n settingsButton.setEnabled(true);\n exportButton.setEnabled(true);\n importConfigButton.setEnabled(true);\n importObjButton.setEnabled(true);\n isLoadingProject = false;\n }, \"ConfigFileOpenThread\").start();\n } else {\n LogHelper.warn(getClass(), \"Tried importing OBJ when already importing OBJ\");\n }\n }\n\n private void onTimelinePosChanged(Float percent) {\n timeline.updatePercent(percent);\n// if (SMBLWSettings.autoUpdateProperties) {\n// assert ProjectManager.getCurrentClientLevelData() != null;\n// if (ProjectManager.getCurrentClientLevelData().getTimelinePos() != percent) {\n// ProjectManager.getCurrentClientLevelData().clearCurrentFrameObjectAnimData();\n// }\n//\n// updatePropertiesObjectsPanel();\n// } else {\n// for (Map.Entry<String, AnimData> entry : ProjectManager.getCurrentClientLevelData().getCurrentFrameObjectAnimDataMap().entrySet()) {\n// entry.getValue().moveFirstFrame(percent);\n// }\n// }\n }\n\n public void addTextField(TextField textField) {\n if (textFields == null) {\n textFields = new HashSet<>();\n }\n\n textFields.add(textField);\n }\n\n private void transformObjectAtTime(String name, float time) {\n //TODO\n// ITransformable transform = ProjectManager.getCurrentClientLevelData().getObjectNamedTransform(name, time);\n// PosXYZ translate = transform.getPosition();\n// PosXYZ rotate = transform.getRotation();\n// GL11.glTranslated(translate.x, translate.y, translate.z);\n// GL11.glRotated(rotate.z, 0, 0, 1);\n// GL11.glRotated(rotate.y, 0, 1, 0);\n// GL11.glRotated(rotate.x, 1, 0, 0);\n }\n\n private void transformObjectAtTime(String name) {\n transformObjectAtTime(name, ProjectManager.getCurrentClientLevelData().getTimelinePos());\n }\n\n private void addNextFrameAction(UIAction action) {\n nextFrameActions.add(action);\n }\n\n @Deprecated\n private void moveSelectedKeyframesToBuffer(boolean makeCopy) {\n }\n\n @Deprecated\n private void commitBufferedKeyframes() {\n }\n\n @Deprecated\n private void discardBufferedKeyframes() {\n\n }\n\n}",
"public class UndoAssetTransform extends UndoCommand {\n\n @NotNull private Map<String, Placeable> placedObjectsSnapshot = new HashMap<>();\n\n public UndoAssetTransform(@NotNull ClientLevelData clientLevelData, @NotNull Set<String> selectedPlaceables) {\n super(clientLevelData);\n\n for (String name : selectedPlaceables) {\n placedObjectsSnapshot.put(name, clientLevelData.getLevelData().getPlaceable(name).getCopy());\n }\n }\n\n @Override\n public void undo() {\n for (Map.Entry<String, Placeable> entry : placedObjectsSnapshot.entrySet()) {\n clientLevelData.getLevelData().replacePlaceable(entry.getKey(), entry.getValue().getCopy());\n }\n }\n\n @Override\n public UndoCommand getRedoCommand() {\n return new UndoAssetTransform(clientLevelData, clientLevelData.getSelectedPlaceables());\n }\n\n @Nullable\n @Override\n public String getUndoMessage() {\n return LangManager.getItem(\"undoTransform\");\n }\n\n @Nullable\n @Override\n public String getRedoMessage() {\n return LangManager.getItem(\"redoTransform\");\n }\n\n}",
"public interface ITransformable {\n\n default void setPosition(PosXYZ position) { throw new UnsupportedOperationException(); }\n default PosXYZ getPosition() { throw new UnsupportedOperationException(); }\n\n default boolean canMoveX() { return true; }\n default boolean canMoveY() { return true; }\n default boolean canMoveZ() { return true; }\n\n default void setRotation(PosXYZ rotation) { throw new UnsupportedOperationException(); }\n default PosXYZ getRotation() { throw new UnsupportedOperationException(); }\n\n default boolean canRotate() { return true; }\n\n default void setScale(PosXYZ scale) { throw new UnsupportedOperationException(); }\n default PosXYZ getScale() { throw new UnsupportedOperationException(); }\n\n default boolean canScale() { return true; }\n\n}"
] | import craftedcart.smblevelworkshop.asset.Placeable;
import craftedcart.smblevelworkshop.project.ProjectManager;
import craftedcart.smblevelworkshop.resource.LangManager;
import craftedcart.smblevelworkshop.ui.MainScreen;
import craftedcart.smblevelworkshop.undo.UndoAssetTransform;
import craftedcart.smblevelworkshop.util.ITransformable;
import io.github.craftedcart.fluidui.component.TextField;
import io.github.craftedcart.fluidui.util.UIColor;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List; | package craftedcart.smblevelworkshop.ui.component.transform;
/**
* @author CraftedCart
* Created on 30/10/2016 (DD/MM/YYYY)
*/
public class PlaceableScaleTextFields extends ScaleTextFields {
public PlaceableScaleTextFields(@NotNull MainScreen mainScreen, @Nullable TextField nextTextField) {
super(mainScreen, nextTextField);
}
@Nullable
@Override
protected Double valueConfirmedParseNumber(String value, List<ITransformable> transformablesToPopulate) {
double newValue;
try {
newValue = Double.parseDouble(value);
assert ProjectManager.getCurrentClientLevelData() != null;
mainScreen.addUndoCommand(new UndoAssetTransform(ProjectManager.getCurrentClientLevelData(),
ProjectManager.getCurrentClientLevelData().getSelectedPlaceables()));
for (String name : ProjectManager.getCurrentClientLevelData().getSelectedPlaceables()) { | Placeable placeable = ProjectManager.getCurrentLevelData().getPlaceable(name); | 0 |
wxiaoqi/ace-cache | src/main/java/com/ace/cache/parser/impl/DefaultKeyGenerator.java | [
"public class RedisConfig {\n private RedisPoolConfig pool = new RedisPoolConfig();\n private String host;\n private String password;\n private String timeout;\n private String database;\n private String port;\n private String enable;\n private String sysName;\n private String userKey;\n private Long refreshTimeout;\n\n\n @PostConstruct\n public void init() {\n PropertiesLoaderUtils prop = new PropertiesLoaderUtils(\"application.properties\");\n if (!StringUtils.isBlank(prop.getProperty(\"redis.host\"))) {\n host = prop.getProperty(\"redis.host\");\n pool.setMaxActive(prop.getProperty(\"redis.pool.maxActive\"));\n pool.setMaxIdle(prop.getProperty(\"redis.pool.maxIdle\"));\n pool.setMaxWait(prop.getProperty(\"redis.pool.maxWait\"));\n password = prop.getProperty(\"redis.password\");\n timeout = prop.getProperty(\"redis.timeout\");\n database = prop.getProperty(\"redis.database\");\n port = prop.getProperty(\"redis.port\");\n sysName = prop.getProperty(\"redis.sysName\");\n enable = prop.getProperty(\"redis.enable\");\n String refreshTimeoutStr = prop.getProperty(\"redis.cache.refreshTimeout\");\n if (StringUtils.isNotBlank(refreshTimeoutStr)) {\n refreshTimeout = Long.parseLong(refreshTimeoutStr.trim());\n } else {\n refreshTimeout = 0L;\n }\n userKey = prop.getProperty(\"redis.userkey\");\n\n }\n }\n\n public String addSys(String key) {\n String result = key;\n String sys = this.getSysName();\n if (key.startsWith(sys))\n result = key;\n else\n result = sys + \":\" + key;\n return result;\n }\n\n\n public RedisPoolConfig getPool() {\n return pool;\n }\n\n public void setPool(RedisPoolConfig pool) {\n this.pool = pool;\n }\n\n public void setRefreshTimeout(Long refreshTimeout) {\n this.refreshTimeout = refreshTimeout;\n }\n\n public String getHost() {\n return host;\n }\n\n public void setHost(String host) {\n this.host = host;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n public String getTimeout() {\n return timeout;\n }\n\n public void setTimeout(String timeout) {\n this.timeout = timeout;\n }\n\n public String getDatabase() {\n return database;\n }\n\n public void setDatabase(String database) {\n this.database = database;\n }\n\n public String getSysName() {\n return sysName;\n }\n\n public void setSysName(String sysName) {\n this.sysName = sysName;\n }\n\n public String getEnable() {\n return enable;\n }\n\n public void setEnable(String enable) {\n this.enable = enable;\n }\n\n public String getPort() {\n return port;\n }\n\n public void setPort(String port) {\n this.port = port;\n }\n\n public String getUserKey() {\n return userKey;\n }\n\n public void setUserKey(String userKey) {\n this.userKey = userKey;\n }\n\n public Long getRefreshTimeout() {\n return this.refreshTimeout;\n }\n}",
"public interface IUserKeyGenerator {\n public String getCurrentUserAccount();\n}",
"@SuppressWarnings(\"rawtypes\")\npublic class ReflectionUtils {\n\n private static final String SETTER_PREFIX = \"set\";\n\n private static final String GETTER_PREFIX = \"get\";\n\n private static final String CGLIB_CLASS_SEPARATOR = \"$$\";\n\n private static Logger logger = LoggerFactory.getLogger(ReflectionUtils.class);\n\n /**\n * 调用Getter方法.\n * 支持多级,如:对象名.对象名.方法\n */\n public static Object invokeGetter(Object obj, String propertyName) {\n Object object = obj;\n for (String name : StringUtils.split(propertyName, \".\")) {\n String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(name);\n object = invokeMethod(object, getterMethodName, new Class[]{}, new Object[]{});\n }\n return object;\n }\n\n /**\n * 调用Setter方法, 仅匹配方法名。\n * 支持多级,如:对象名.对象名.方法\n */\n public static void invokeSetter(Object obj, String propertyName, Object value) {\n Object object = obj;\n String[] names = StringUtils.split(propertyName, \".\");\n for (int i = 0; i < names.length; i++) {\n if (i < names.length - 1) {\n String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(names[i]);\n object = invokeMethod(object, getterMethodName, new Class[]{}, new Object[]{});\n } else {\n String setterMethodName = SETTER_PREFIX + StringUtils.capitalize(names[i]);\n invokeMethodByName(object, setterMethodName, new Object[]{value});\n }\n }\n }\n\n /**\n * 直接读取对象属性值, 无视private/protected修饰符, 不经过getter函数.\n */\n public static Object getFieldValue(final Object obj, final String fieldName) {\n Field field = getAccessibleField(obj, fieldName);\n\n if (field == null) {\n throw new IllegalArgumentException(\"Could not find field [\" + fieldName + \"] on target [\" + obj + \"]\");\n }\n\n Object result = null;\n try {\n result = field.get(obj);\n } catch (IllegalAccessException e) {\n logger.error(\"不可能抛出的异常{}\", e.getMessage());\n }\n return result;\n }\n\n /**\n * 直接设置对象属性值, 无视private/protected修饰符, 不经过setter函数.\n */\n public static void setFieldValue(final Object obj, final String fieldName, final Object value) {\n Field field = getAccessibleField(obj, fieldName);\n\n if (field == null) {\n logger.error(\"Could not find field [\" + fieldName + \"] on target [\" + obj + \"]\");\n return;\n //throw new IllegalArgumentException(\"Could not find field [\" + fieldName + \"] on target [\" + obj + \"]\");\n }\n try {\n field.set(obj, convert(value, field.getType()));\n } catch (IllegalAccessException e) {\n logger.error(\"不可能抛出的异常:{}\", e.getMessage());\n }\n }\n\n public static Object convert(Object object, Class<?> type) {\n if (object instanceof Number) {\n Number number = (Number) object;\n if (type.equals(byte.class) || type.equals(Byte.class)) {\n return number.byteValue();\n }\n if (type.equals(short.class) || type.equals(Short.class)) {\n return number.shortValue();\n }\n if (type.equals(int.class) || type.equals(Integer.class)) {\n return number.intValue();\n }\n if (type.equals(long.class) || type.equals(Long.class)) {\n return number.longValue();\n }\n if (type.equals(float.class) || type.equals(Float.class)) {\n return number.floatValue();\n }\n if (type.equals(double.class) || type.equals(Double.class)) {\n return number.doubleValue();\n }\n }\n if (type.equals(String.class)) {\n return (object == null) ? \"\" : object.toString();\n }\n return object;\n }\n\n /**\n * 直接调用对象方法, 无视private/protected修饰符.\n * 用于一次性调用的情况,否则应使用getAccessibleMethod()函数获得Method后反复调用.\n * 同时匹配方法名+参数类型,\n */\n public static Object invokeMethod(final Object obj, final String methodName, final Class<?>[] parameterTypes,\n final Object[] args) {\n Method method = getAccessibleMethod(obj, methodName, parameterTypes);\n if (method == null) {\n throw new IllegalArgumentException(\"Could not find method [\" + methodName + \"] on target [\" + obj + \"]\");\n }\n\n try {\n return method.invoke(obj, args);\n } catch (Exception e) {\n throw convertReflectionExceptionToUnchecked(e);\n }\n }\n\n /**\n * 直接调用对象方法, 无视private/protected修饰符,\n * 用于一次性调用的情况,否则应使用getAccessibleMethodByName()函数获得Method后反复调用.\n * 只匹配函数名,如果有多个同名函数调用第一个。\n */\n public static Object invokeMethodByName(final Object obj, final String methodName, final Object[] args) {\n Method method = getAccessibleMethodByName(obj, methodName);\n if (method == null) {\n throw new IllegalArgumentException(\"Could not find method [\" + methodName + \"] on target [\" + obj + \"]\");\n }\n\n try {\n return method.invoke(obj, args);\n } catch (Exception e) {\n throw convertReflectionExceptionToUnchecked(e);\n }\n }\n\n /**\n * 循环向上转型, 获取对象的DeclaredField, 并强制设置为可访问.\n * <p/>\n * 如向上转型到Object仍无法找到, 返回null.\n */\n public static Field getAccessibleField(final Object obj, final String fieldName) {\n Validate.notNull(obj, \"object can't be null\");\n Validate.notBlank(fieldName, \"fieldName can't be blank\");\n for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) {\n try {\n Field field = superClass.getDeclaredField(fieldName);\n makeAccessible(field);\n return field;\n } catch (NoSuchFieldException e) {//NOSONAR\n // Field不在当前类定义,继续向上转型\n continue;// new add\n }\n }\n return null;\n }\n\n /**\n * 循环向上转型, 获取对象的DeclaredMethod,并强制设置为可访问.\n * 如向上转型到Object仍无法找到, 返回null.\n * 匹配函数名+参数类型。\n * <p/>\n * 用于方法需要被多次调用的情况. 先使用本函数先取得Method,然后调用Method.invoke(Object obj, Object... args)\n */\n public static Method getAccessibleMethod(final Object obj, final String methodName,\n final Class<?>... parameterTypes) {\n Validate.notNull(obj, \"object can't be null\");\n Validate.notBlank(methodName, \"methodName can't be blank\");\n\n for (Class<?> searchType = obj.getClass(); searchType != Object.class; searchType = searchType.getSuperclass()) {\n try {\n Method method = searchType.getDeclaredMethod(methodName, parameterTypes);\n makeAccessible(method);\n return method;\n } catch (NoSuchMethodException e) {\n // Method不在当前类定义,继续向上转型\n continue;// new add\n }\n }\n return null;\n }\n\n /**\n * 循环向上转型, 获取对象的DeclaredMethod,并强制设置为可访问.\n * 如向上转型到Object仍无法找到, 返回null.\n * 只匹配函数名。\n * <p/>\n * 用于方法需要被多次调用的情况. 先使用本函数先取得Method,然后调用Method.invoke(Object obj, Object... args)\n */\n public static Method getAccessibleMethodByName(final Object obj, final String methodName) {\n Validate.notNull(obj, \"object can't be null\");\n Validate.notBlank(methodName, \"methodName can't be blank\");\n\n for (Class<?> searchType = obj.getClass(); searchType != Object.class; searchType = searchType.getSuperclass()) {\n Method[] methods = searchType.getDeclaredMethods();\n for (Method method : methods) {\n if (method.getName().equals(methodName)) {\n makeAccessible(method);\n return method;\n }\n }\n }\n return null;\n }\n\n /**\n * 改变private/protected的方法为public,尽量不调用实际改动的语句,避免JDK的SecurityManager抱怨。\n */\n public static void makeAccessible(Method method) {\n if ((!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers()))\n && !method.isAccessible()) {\n method.setAccessible(true);\n }\n }\n\n /**\n * 改变private/protected的成员变量为public,尽量不调用实际改动的语句,避免JDK的SecurityManager抱怨。\n */\n public static void makeAccessible(Field field) {\n if ((!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers()) || Modifier\n .isFinal(field.getModifiers())) && !field.isAccessible()) {\n field.setAccessible(true);\n }\n }\n\n /**\n * 通过反射, 获得Class定义中声明的泛型参数的类型, 注意泛型必须定义在父类处\n * 如无法找到, 返回Object.class.\n * eg.\n * public UserDao extends HibernateDao<User>\n *\n * @param clazz The class to introspect\n * @return the first generic declaration, or Object.class if cannot be determined\n */\n @SuppressWarnings(\"unchecked\")\n public static <T> Class<T> getClassGenricType(final Class clazz) {\n return getClassGenricType(clazz, 0);\n }\n\n /**\n * 通过反射, 获得Class定义中声明的父类的泛型参数的类型.\n * 如无法找到, 返回Object.class.\n * <p/>\n * 如public UserDao extends HibernateDao<User,Long>\n *\n * @param clazz clazz The class to introspect\n * @param index the Index of the generic ddeclaration,start from 0.\n * @return the index generic declaration, or Object.class if cannot be determined\n */\n public static Class getClassGenricType(final Class clazz, final int index) {\n\n Type genType = clazz.getGenericSuperclass();\n\n if (!(genType instanceof ParameterizedType)) {\n logger.warn(clazz.getSimpleName() + \"'s superclass not ParameterizedType\");\n return Object.class;\n }\n\n Type[] params = ((ParameterizedType) genType).getActualTypeArguments();\n\n if (index >= params.length || index < 0) {\n logger.warn(\"Index: \" + index + \", Size of \" + clazz.getSimpleName() + \"'s Parameterized Type: \"\n + params.length);\n return Object.class;\n }\n if (!(params[index] instanceof Class)) {\n logger.warn(clazz.getSimpleName() + \" not set the actual class on superclass generic parameter\");\n return Object.class;\n }\n\n return (Class) params[index];\n }\n\n public static Class<?> getUserClass(Object instance) {\n Assert.notNull(instance, \"Instance must not be null\");\n Class clazz = instance.getClass();\n if (clazz != null && clazz.getName().contains(CGLIB_CLASS_SEPARATOR)) {\n Class<?> superClass = clazz.getSuperclass();\n if (superClass != null && !Object.class.equals(superClass)) {\n return superClass;\n }\n }\n return clazz;\n\n }\n\n /**\n * 将反射时的checked exception转换为unchecked exception.\n */\n public static RuntimeException convertReflectionExceptionToUnchecked(Exception e) {\n if (e instanceof IllegalAccessException || e instanceof IllegalArgumentException\n || e instanceof NoSuchMethodException) {\n return new IllegalArgumentException(e);\n } else if (e instanceof InvocationTargetException) {\n return new RuntimeException(((InvocationTargetException) e).getTargetException());\n } else if (e instanceof RuntimeException) {\n return (RuntimeException) e;\n }\n return new RuntimeException(\"Unexpected Checked Exception.\", e);\n }\n\n /**\n * 判断某个对象是否拥有某个属性\n *\n * @param obj 对象\n * @param fieldName 属性名\n * @return 有属性返回true\n * 无属性返回false\n */\n public static boolean hasField(final Object obj, final String fieldName) {\n Field field = getAccessibleField(obj, fieldName);\n if (field == null) {\n return false;\n }\n return true;\n\n }\n}",
"public enum CacheScope {\n user, application\n}",
"public class WebUtil {\n public static String getCookieValue(HttpServletRequest request, String cookieName) {\n Cookie[] cookies = request.getCookies();\n if (cookies != null && cookies.length > 0) {\n Cookie[] var3 = cookies;\n int var4 = cookies.length;\n\n for(int var5 = 0; var5 < var4; ++var5) {\n Cookie cookie = var3[var5];\n if (cookie.getName().equals(cookieName)) {\n return cookie.getValue();\n }\n }\n }\n\n return null;\n }\n}",
"public abstract class IKeyGenerator {\n public static final String LINK = \"_\";\n\n /**\n * 获取动态key\n *\n * @param key\n * @param scope\n * @param parameterTypes\n * @param arguments\n * @return\n */\n public String getKey(String key, CacheScope scope,\n Class<?>[] parameterTypes, Object[] arguments) {\n StringBuffer sb = new StringBuffer(\"\");\n key = buildKey(key, scope, parameterTypes, arguments);\n sb.append(key);\n if (CacheScope.user.equals(scope)) {\n if (getUserKeyGenerator() != null)\n sb.append(LINK)\n .append(getUserKeyGenerator().getCurrentUserAccount());\n }\n return sb.toString();\n }\n\n /**\n * 当前登陆人key\n *\n * @param userKeyGenerator\n */\n public abstract IUserKeyGenerator getUserKeyGenerator();\n\n /**\n * 生成动态key\n *\n * @param key\n * @param scope\n * @param parameterTypes\n * @param arguments\n * @return\n */\n public abstract String buildKey(String key, CacheScope scope,\n Class<?>[] parameterTypes, Object[] arguments);\n}"
] | import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.ace.cache.config.RedisConfig;
import com.ace.cache.parser.IUserKeyGenerator;
import com.ace.cache.utils.ReflectionUtils;
import com.ace.cache.constants.CacheScope;
import com.ace.cache.utils.WebUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ace.cache.parser.IKeyGenerator;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest; | package com.ace.cache.parser.impl;
@Service
public class DefaultKeyGenerator extends IKeyGenerator {
@Autowired
RedisConfig redisConfig;
@Autowired(required = false) | private IUserKeyGenerator userKeyGenerator; | 1 |
openintents/filemanager | FileManager/src/main/java/org/openintents/filemanager/FileManagerActivity.java | [
"public class BookmarkListActivity extends FragmentActivity {\n public static final String KEY_RESULT_PATH = \"path\";\n private static final String FRAGMENT_TAG = \"Fragment\";\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n UIUtils.setThemeFor(this);\n super.onCreate(savedInstanceState);\n\n HomeIconHelper.activity_actionbar_setDisplayHomeAsUpEnabled(this);\n\n if (getSupportFragmentManager().findFragmentByTag(FRAGMENT_TAG) == null) {\n getSupportFragmentManager().beginTransaction()\n .add(android.R.id.content, new BookmarkListFragment(), FRAGMENT_TAG)\n .commit();\n }\n }\n\n public void onListItemClick(String path) {\n setResult(RESULT_OK, new Intent().putExtra(KEY_RESULT_PATH, path));\n finish();\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n switch (item.getItemId()) {\n case android.R.id.home:\n HomeIconHelper.showHome(this);\n break;\n }\n return super.onOptionsItemSelected(item);\n }\n}",
"public class FileHolder implements Parcelable, Comparable<FileHolder> {\n public static final Parcelable.Creator<FileHolder> CREATOR = new Parcelable.Creator<FileHolder>() {\n public FileHolder createFromParcel(Parcel in) {\n return new FileHolder(in);\n }\n\n public FileHolder[] newArray(int size) {\n return new FileHolder[size];\n }\n };\n private File mFile;\n private Drawable mIcon;\n private String mMimeType = \"\";\n private String mExtension;\n private Boolean mIsDirectory;\n\n public FileHolder(File f) {\n mFile = f;\n mExtension = parseExtension();\n mMimeType = MimeTypes.getInstance().getMimeType(f.getName());\n }\n\n public FileHolder(File f, boolean isDirectory) {\n mFile = f;\n mExtension = parseExtension();\n mMimeType = MimeTypes.getInstance().getMimeType(f.getName());\n mIsDirectory = isDirectory;\n }\n\n /**\n * Fastest constructor as it takes everything ready.\n */\n public FileHolder(File f, String m, Drawable i, boolean isDirectory) {\n mFile = f;\n mIcon = i;\n mExtension = parseExtension();\n mMimeType = m;\n mIsDirectory = isDirectory;\n }\n\n public FileHolder(Parcel in) {\n mFile = new File(in.readString());\n mMimeType = in.readString();\n mExtension = in.readString();\n byte directoryFlag = in.readByte();\n if (directoryFlag == -1) {\n mIsDirectory = null;\n } else {\n mIsDirectory = (directoryFlag == 1);\n }\n }\n\n public File getFile() {\n return mFile;\n }\n\n /**\n * Gets the icon representation of this file. In case of loss through parcel-unparcel.\n *\n * @return The icon.\n */\n public Drawable getIcon() {\n return mIcon;\n }\n\n public void setIcon(Drawable icon) {\n mIcon = icon;\n }\n\n /**\n * Shorthand for getFile().getName().\n *\n * @return This file's name.\n */\n public String getName() {\n return mFile.getName();\n }\n\n /**\n * Get the contained file's extension.\n */\n public String getExtension() {\n return mExtension;\n }\n\n /**\n * @return The held item's mime type.\n */\n public String getMimeType() {\n return mMimeType;\n }\n\n public String getFormattedModificationDate(Context c) {\n DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(c);\n DateFormat timeFormat = android.text.format.DateFormat.getTimeFormat(c);\n Date date = new Date(mFile.lastModified());\n return dateFormat.format(date) + \" \" + timeFormat.format(date);\n }\n\n /**\n * @param recursive Whether to return size of the whole tree below this file (Directories only).\n */\n public String getFormattedSize(Context c, boolean recursive) {\n return Formatter.formatFileSize(c, getSizeInBytes(recursive));\n }\n\n private long getSizeInBytes(boolean recursive) {\n if (recursive && mFile.isDirectory())\n return FileUtils.folderSize(mFile);\n else\n return mFile.length();\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n dest.writeString(mFile.getAbsolutePath());\n dest.writeString(mMimeType);\n dest.writeString(mExtension);\n dest.writeByte((byte) (mIsDirectory == null ? -1 : (mIsDirectory ? 1 : 0)));\n }\n\n @Override\n public int compareTo(FileHolder another) {\n return mFile.compareTo(another.getFile());\n }\n\n /**\n * Parse the extension from the filename of the mFile member.\n */\n private String parseExtension() {\n return FileUtils.getExtension(mFile.getName()).toLowerCase(Locale.ROOT);\n }\n\n @Override\n public String toString() {\n return super.toString() + \"-\" + getName();\n }\n\n public Boolean isDirectory() {\n return mIsDirectory;\n }\n}",
"public class SimpleFileListFragment extends FileListFragment {\n protected static final int REQUEST_CODE_MULTISELECT = 2;\n private static final String INSTANCE_STATE_PATHBAR_MODE = \"pathbar_mode\";\n private PathBar mPathBar;\n private boolean mActionsEnabled = true;\n\n private int mSingleSelectionMenu = R.menu.context;\n private int mMultiSelectionMenu = R.menu.multiselect;\n private TextView mMessageView;\n\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {\n return inflater.inflate(R.layout.filelist_browse, null);\n }\n\n @Override\n public void onViewCreated(View view, Bundle savedInstanceState) {\n super.onViewCreated(view, savedInstanceState);\n\n // Pathbar init.\n mPathBar = view.findViewById(R.id.pathbar);\n mMessageView = view.findViewById(R.id.message);\n mMessageView.setText(getString(R.string.error_generic) + \"no access\");\n // Handle mPath differently if we restore state or just initially create the view.\n if (savedInstanceState == null)\n mPathBar.setInitialDirectory(getPath());\n else\n mPathBar.cd(getPath());\n mPathBar.setOnDirectoryChangedListener(new OnDirectoryChangedListener() {\n\n @Override\n public void directoryChanged(File newCurrentDir) {\n Context activity = getActivity();\n if (activity == null) {\n return;\n }\n open(new FileHolder(newCurrentDir, true));\n }\n });\n if (savedInstanceState != null && savedInstanceState.getBoolean(INSTANCE_STATE_PATHBAR_MODE))\n mPathBar.switchToManualInput();\n // Removed else clause as the other mode is the default. It seems faster this way on Nexus S.\n\n initContextualActions();\n }\n\n /**\n * Override this to handle initialization of list item long clicks.\n */\n void initContextualActions() {\n if (mActionsEnabled) {\n FileMultiChoiceModeHelper multiChoiceModeHelper = new FileMultiChoiceModeHelper(mSingleSelectionMenu, mMultiSelectionMenu);\n multiChoiceModeHelper.setListView(getListView());\n multiChoiceModeHelper.setPathBar(mPathBar);\n multiChoiceModeHelper.setContext(this);\n getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);\n setHasOptionsMenu(true);\n }\n }\n\n @Override\n public void onCreateContextMenu(ContextMenu menu, View view,\n ContextMenuInfo menuInfo) {\n MenuInflater inflater = new MenuInflater(getActivity());\n\n // Obtain context menu info\n AdapterView.AdapterContextMenuInfo info;\n try {\n info = (AdapterView.AdapterContextMenuInfo) menuInfo;\n } catch (ClassCastException e) {\n e.printStackTrace();\n return;\n }\n\n MenuUtils.fillContextMenu((FileHolder) mAdapter.getItem(info.position), menu, mSingleSelectionMenu, inflater, getActivity());\n }\n\n @Override\n public boolean onContextItemSelected(MenuItem item) {\n FileHolder fh = (FileHolder) mAdapter.getItem(((AdapterContextMenuInfo) item.getMenuInfo()).position);\n return MenuUtils.handleSingleSelectionAction(this, item, fh, getActivity());\n }\n\n @Override\n public void onListItemClick(ListView l, View v, int position, long id) {\n FileHolder item = (FileHolder) mAdapter.getItem(position);\n\n openInformingPathBar(item);\n }\n\n @Override\n protected void updateNoAccessMessage(boolean showMessage) {\n mMessageView.setVisibility(showMessage ? View.VISIBLE : View.GONE);\n }\n\n /**\n * Use this to open files and folders using this fragment. Appropriately handles pathbar updates.\n *\n * @param item The dir/file to open.\n */\n public void openInformingPathBar(FileHolder item) {\n if (mPathBar == null)\n open(item);\n else\n mPathBar.cd(item.getFile());\n }\n\n /**\n * Point this Fragment to show the contents of the passed file.\n *\n * @param f If same as current, does nothing.\n */\n private void open(FileHolder f) {\n if (!f.getFile().exists())\n return;\n\n if (f.getFile().isDirectory()) {\n openDir(f);\n } else if (f.getFile().isFile()) {\n openFile(f);\n }\n }\n\n private void openFile(FileHolder fileholder) {\n FileUtils.openFile(fileholder, getActivity());\n }\n\n /**\n * Attempts to open a directory for browsing.\n * Override this to handle folder click behavior.\n *\n * @param fileholder The holder of the directory to open.\n */\n protected void openDir(FileHolder fileholder) {\n // Avoid unnecessary attempts to load.\n if (fileholder.getFile().getAbsolutePath().equals(getPath()))\n return;\n\n setPath(fileholder.getFile());\n refresh();\n }\n\n protected void setLongClickMenus(int singleSelectionResource, int multiSelectionResource) {\n mSingleSelectionMenu = singleSelectionResource;\n mMultiSelectionMenu = multiSelectionResource;\n }\n\n @Override\n public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {\n inflater.inflate(R.menu.simple_file_list, menu);\n }\n\n @Override\n public void onPrepareOptionsMenu(Menu menu) {\n // We only know about \".nomedia\" once scanning is finished.\n boolean showMediaScanMenuItem = PreferenceFragment.getMediaScanFromPreference(getActivity());\n if (!mScanner.isRunning() && showMediaScanMenuItem) {\n menu.findItem(R.id.menu_media_scan_include).setVisible(mScanner.getNoMedia());\n menu.findItem(R.id.menu_media_scan_exclude).setVisible(!mScanner.getNoMedia());\n } else {\n menu.findItem(R.id.menu_media_scan_include).setVisible(false);\n menu.findItem(R.id.menu_media_scan_exclude).setVisible(false);\n }\n\n if (((FileManagerApplication) getActivity().getApplication()).getCopyHelper().canPaste()) {\n menu.findItem(R.id.menu_paste).setVisible(true);\n } else {\n menu.findItem(R.id.menu_paste).setVisible(false);\n }\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n switch (item.getItemId()) {\n\n case R.id.menu_create_folder:\n CreateDirectoryDialog dialog = new CreateDirectoryDialog();\n dialog.setTargetFragment(this, 0);\n Bundle args = new Bundle();\n args.putString(FileManagerIntents.EXTRA_DIR_PATH, getPath());\n dialog.setArguments(args);\n dialog.show(getActivity().getSupportFragmentManager(), CreateDirectoryDialog.class.getName());\n return true;\n\n case R.id.menu_media_scan_include:\n includeInMediaScan();\n return true;\n\n case R.id.menu_media_scan_exclude:\n excludeFromMediaScan();\n return true;\n case R.id.menu_paste:\n if (((FileManagerApplication) getActivity().getApplication()).getCopyHelper().canPaste())\n ((FileManagerApplication) getActivity().getApplication()).getCopyHelper().paste(new File(getPath()), new CopyHelper.OnOperationFinishedListener() {\n @Override\n public void operationFinished(boolean success) {\n refresh();\n\n // Refresh options menu\n getActivity().supportInvalidateOptionsMenu();\n }\n });\n else\n Toast.makeText(getActivity(), R.string.nothing_to_paste, Toast.LENGTH_LONG).show();\n return true;\n\n case R.id.menu_multiselect:\n Intent intent = new Intent(FileManagerIntents.ACTION_MULTI_SELECT);\n intent.putExtra(FileManagerIntents.EXTRA_DIR_PATH, getPath());\n startActivityForResult(intent, REQUEST_CODE_MULTISELECT);\n return true;\n\n default:\n return false;\n }\n }\n\n @Override\n public void onActivityResult(int requestCode, int resultCode, Intent data) {\n // Automatically refresh to display possible changes done through the multiselect fragment.\n if (requestCode == REQUEST_CODE_MULTISELECT)\n refresh();\n super.onActivityResult(requestCode, resultCode, data);\n }\n\n private void includeInMediaScan() {\n // Delete the .nomedia file.\n File file = FileUtils.getFile(mPathBar.getCurrentDirectory(),\n FileUtils.NOMEDIA_FILE_NAME);\n if (file.delete()) {\n Toast.makeText(getActivity(),\n getString(R.string.media_scan_included), Toast.LENGTH_LONG)\n .show();\n } else {\n // That didn't work.\n Toast.makeText(getActivity(), getString(R.string.error_generic),\n Toast.LENGTH_LONG).show();\n }\n refresh();\n }\n\n private void excludeFromMediaScan() {\n // Create the .nomedia file.\n File file = FileUtils.getFile(mPathBar.getCurrentDirectory(),\n FileUtils.NOMEDIA_FILE_NAME);\n try {\n if (file.createNewFile()) {\n Toast.makeText(getActivity(),\n getString(R.string.media_scan_excluded),\n Toast.LENGTH_LONG).show();\n } else {\n Toast.makeText(getActivity(),\n getString(R.string.error_media_scan), Toast.LENGTH_LONG)\n .show();\n }\n } catch (IOException e) {\n // That didn't work.\n Toast.makeText(getActivity(),\n getString(R.string.error_generic) + e.getMessage(), Toast.LENGTH_LONG).show();\n }\n refresh();\n }\n\n public void browseToHome() {\n mPathBar.cd(mPathBar.getInitialDirectory());\n }\n\n public boolean pressBack() {\n return mPathBar.pressBack();\n }\n\n /**\n * Set whether to show menu and selection actions. Must be set before OnViewCreated is called.\n *\n * @param enabled\n */\n public void setActionsEnabled(boolean enabled) {\n mActionsEnabled = enabled;\n }\n\n @Override\n public void onSaveInstanceState(Bundle outState) {\n super.onSaveInstanceState(outState);\n\n outState.putBoolean(INSTANCE_STATE_PATHBAR_MODE, mPathBar.getMode() == Mode.MANUAL_INPUT);\n }\n}",
"public class FileUtils {\r\n\r\n public static final String NOMEDIA_FILE_NAME = \".nomedia\";\r\n /**\r\n * TAG for log messages.\r\n */\r\n static final String TAG = \"FileUtils\";\r\n\r\n private FileUtils() {\r\n }\r\n\r\n /**\r\n * Gets the extension of a file name, like \".png\" or \".jpg\".\r\n *\r\n * @param uri\r\n * @return Extension including the dot(\".\"); \"\" if there is no extension;\r\n * null if uri was null.\r\n */\r\n public static String getExtension(String uri) {\r\n if (uri == null) {\r\n return null;\r\n }\r\n\r\n int dot = uri.lastIndexOf(\".\");\r\n if (dot >= 0) {\r\n return uri.substring(dot);\r\n } else {\r\n // No extension.\r\n return \"\";\r\n }\r\n }\r\n\r\n /**\r\n * Convert File into Uri.\r\n *\r\n * @param file\r\n * @return uri\r\n */\r\n public static Uri getUri(File file) {\r\n if (file != null) {\r\n return Uri.fromFile(file);\r\n }\r\n return null;\r\n }\r\n\r\n /**\r\n * Convert Uri into File.\r\n *\r\n * @param uri\r\n * @return file\r\n */\r\n public static File getFile(Uri uri) {\r\n if (uri != null) {\r\n String filepath = uri.getPath();\r\n if (filepath != null) {\r\n return new File(filepath);\r\n }\r\n }\r\n return null;\r\n }\r\n\r\n /**\r\n * Returns the path only (without file name).\r\n *\r\n * @param file\r\n * @return\r\n */\r\n public static File getPathWithoutFilename(File file) {\r\n if (file != null) {\r\n if (file.isDirectory()) {\r\n // no file to be split off. Return everything\r\n return file;\r\n } else {\r\n String filename = file.getName();\r\n String filepath = file.getAbsolutePath();\r\n\r\n // Construct path without file name.\r\n String pathwithoutname = filepath.substring(0, filepath.length() - filename.length());\r\n if (pathwithoutname.endsWith(\"/\")) {\r\n pathwithoutname = pathwithoutname.substring(0, pathwithoutname.length() - 1);\r\n }\r\n return new File(pathwithoutname);\r\n }\r\n }\r\n return null;\r\n }\r\n\r\n /**\r\n * Constructs a file from a path and file name.\r\n *\r\n * @param curdir\r\n * @param file\r\n * @return\r\n */\r\n public static File getFile(String curdir, String file) {\r\n String separator = \"/\";\r\n if (curdir.endsWith(\"/\")) {\r\n separator = \"\";\r\n }\r\n return new File(curdir + separator + file);\r\n }\r\n\r\n public static File getFile(File curdir, String file) {\r\n return getFile(curdir.getAbsolutePath(), file);\r\n }\r\n\r\n public static long folderSize(File directory) {\r\n long length = 0;\r\n File[] files = directory.listFiles();\r\n if (files != null)\r\n for (File file : files)\r\n if (file.isFile())\r\n length += file.length();\r\n else\r\n length += folderSize(file);\r\n return length;\r\n }\r\n\r\n public static int getFileCount(File file) {\r\n return calculateFileCount(file, 0);\r\n }\r\n\r\n /**\r\n * @param f - file which need be checked\r\n * @return if is archive - returns true otherwise\r\n */\r\n public static boolean checkIfZipArchive(File f) {\r\n int l = f.getName().length();\r\n // TODO test\r\n if (f.isFile() && FileUtils.getExtension(f.getAbsolutePath()).equalsIgnoreCase(\".zip\"))\r\n return true;\r\n return false;\r\n\r\n // Old way. REALLY slow. Too slow for realtime action loading.\r\n// try {\r\n// new ZipFile(f);\r\n// return true;\r\n// } catch (Exception e){\r\n// return false;\r\n// }\r\n }\r\n\r\n /**\r\n * Recursively count all files in the <code>file</code>'s subtree.\r\n *\r\n * @param countSoFar file count of previous counting\r\n * @param file The root of the tree to count.\r\n */\r\n private static int calculateFileCount(File file, int countSoFar) {\r\n if (!file.isDirectory()) {\r\n countSoFar++;\r\n return countSoFar;\r\n }\r\n if (file.list() == null) {\r\n return countSoFar;\r\n }\r\n for (String fileName : file.list()) {\r\n File f = new File(file.getAbsolutePath() + File.separator + fileName);\r\n countSoFar += calculateFileCount(f, 0);\r\n }\r\n return countSoFar;\r\n }\r\n\r\n /**\r\n * Native helper method, returns whether the current process has execute privilages.\r\n *\r\n * @param file File\r\n * @return returns TRUE if the current process has execute privilages.\r\n */\r\n public static boolean canExecute(File file) {\r\n return file.canExecute();\r\n }\r\n\r\n /**\r\n * @param path The path that the file is supposed to be in.\r\n * @param fileName Desired file name. This name will be modified to create a unique file if necessary.\r\n * @return A file name that is guaranteed to not exist yet. MAY RETURN NULL!\r\n */\r\n public static File createUniqueCopyName(Context context, File path, String fileName) {\r\n // Does that file exist?\r\n File file = FileUtils.getFile(path, fileName);\r\n\r\n if (!file.exists()) {\r\n // Nope - we can take that.\r\n return file;\r\n }\r\n\r\n // Split file's name and extension to fix internationalization issue #307\r\n int fromIndex = fileName.lastIndexOf('.');\r\n String extension = \"\";\r\n if (fromIndex > 0) {\r\n extension = fileName.substring(fromIndex);\r\n fileName = fileName.substring(0, fromIndex);\r\n }\r\n\r\n // Try a simple \"copy of\".\r\n file = FileUtils.getFile(path, context.getString(R.string.copied_file_name, fileName).concat(extension));\r\n\r\n if (!file.exists()) {\r\n // Nope - we can take that.\r\n return file;\r\n }\r\n\r\n int copyIndex = 2;\r\n\r\n // Well, we gotta find a unique name at some point.\r\n while (copyIndex < 500) {\r\n file = FileUtils.getFile(path, context.getString(R.string.copied_file_name_2, copyIndex, fileName).concat(extension));\r\n\r\n if (!file.exists()) {\r\n // Nope - we can take that.\r\n return file;\r\n }\r\n\r\n copyIndex++;\r\n }\r\n\r\n // I GIVE UP.\r\n return null;\r\n }\r\n\r\n /**\r\n * Attempts to open a file for viewing.\r\n *\r\n * @param fileholder The holder of the file to open.\r\n */\r\n public static void openFile(FileHolder fileholder, Context c) {\r\n Intent intent = new Intent(android.content.Intent.ACTION_VIEW);\r\n\r\n Uri data = FileManagerProvider.getUriForFile(fileholder.getFile().getAbsolutePath());\r\n String type = fileholder.getMimeType();\r\n\r\n if (\"*/*\".equals(type)) {\r\n intent.setData(data);\r\n intent.putExtra(FileManagerIntents.EXTRA_FROM_OI_FILEMANAGER, true);\r\n } else {\r\n intent.setDataAndType(data, type);\r\n }\r\n\r\n intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);\r\n try {\r\n List<ResolveInfo> activities = c.getPackageManager().queryIntentActivities(intent, 0);\r\n if (activities.isEmpty() || (activities.size() == 1 && c.getApplicationInfo().packageName.equals(activities.get(0).activityInfo.packageName))) {\r\n Toast.makeText(c, R.string.application_not_available, Toast.LENGTH_SHORT).show();\r\n return;\r\n } else {\r\n c.startActivity(intent);\r\n }\r\n } catch (ActivityNotFoundException | SecurityException e) {\r\n Toast.makeText(c.getApplicationContext(), R.string.application_not_available, Toast.LENGTH_SHORT).show();\r\n } catch (RuntimeException e) {\r\n Log.d(TAG, \"Couldn't open file\", e);\r\n Toast.makeText(c, \"Couldn't open file \" + e, Toast.LENGTH_SHORT).show();\r\n }\r\n }\r\n\r\n public static String getNameWithoutExtension(File f) {\r\n return f.getName().substring(0, f.getName().length() - getExtension(getUri(f).toString()).length());\r\n }\r\n\r\n /**\r\n * Given any file/folder inside an sd card, this will return the path of the sd card\r\n */\r\n public static String getRootOfInnerSdCardFolder(File file) {\r\n if (file == null)\r\n return null;\r\n final long totalSpace = file.getTotalSpace();\r\n while (true) {\r\n final File parentFile = file.getParentFile();\r\n if (parentFile == null || parentFile.getTotalSpace() != totalSpace) {\r\n return file.getAbsolutePath();\r\n }\r\n file = parentFile;\r\n }\r\n }\r\n}\r",
"public final class FileManagerIntents {\r\n\r\n /**\r\n * Activity Action: Pick a file through the file manager, or let user\r\n * specify a custom file name.\r\n * Data is the current file name or file name suggestion.\r\n * Returns a new file name as file URI in data.\r\n * <p>\r\n * <p>Constant Value: \"org.openintents.action.PICK_FILE\"</p>\r\n */\r\n public static final String ACTION_PICK_FILE = \"org.openintents.action.PICK_FILE\";\r\n\r\n /**\r\n * Activity Action: Pick a directory through the file manager, or let user\r\n * specify a custom file name.\r\n * Data is the current directory name or directory name suggestion.\r\n * Returns a new directory name as file URI in data.\r\n * <p>\r\n * <p>Constant Value: \"org.openintents.action.PICK_DIRECTORY\"</p>\r\n */\r\n public static final String ACTION_PICK_DIRECTORY = \"org.openintents.action.PICK_DIRECTORY\";\r\n\r\n /**\r\n * Activity Action: Move, copy or delete after select entries.\r\n * Data is the current directory name or directory name suggestion.\r\n * <p>\r\n * <p>Constant Value: \"org.openintents.action.MULTI_SELECT\"</p>\r\n */\r\n public static final String ACTION_MULTI_SELECT = \"org.openintents.action.MULTI_SELECT\";\r\n\r\n public static final String ACTION_SEARCH_STARTED = \"org.openintents.action.SEARCH_STARTED\";\r\n\r\n public static final String ACTION_SEARCH_FINISHED = \"org.openintens.action.SEARCH_FINISHED\";\r\n\r\n /**\r\n * The title to display.\r\n * <p>\r\n * <p>This is shown in the title bar of the file manager.</p>\r\n * <p>\r\n * <p>Constant Value: \"org.openintents.extra.TITLE\"</p>\r\n */\r\n public static final String EXTRA_TITLE = \"org.openintents.extra.TITLE\";\r\n\r\n /**\r\n * The text on the button to display.\r\n * <p>\r\n * <p>Depending on the use, it makes sense to set this to \"Open\" or \"Save\".</p>\r\n * <p>\r\n * <p>Constant Value: \"org.openintents.extra.BUTTON_TEXT\"</p>\r\n */\r\n public static final String EXTRA_BUTTON_TEXT = \"org.openintents.extra.BUTTON_TEXT\";\r\n\r\n /**\r\n * Flag indicating to show only writeable files and folders.\r\n * <p>\r\n * <p>Constant Value: \"org.openintents.extra.WRITEABLE_ONLY\"</p>\r\n */\r\n public static final String EXTRA_WRITEABLE_ONLY = \"org.openintents.extra.WRITEABLE_ONLY\";\r\n\r\n /**\r\n * The path to prioritize in search. Usually denotes the path the user was on when the search was initiated.\r\n * <p>\r\n * <p>Constant Value: \"org.openintents.extra.SEARCH_INIT_PATH\"</p>\r\n */\r\n public static final String EXTRA_SEARCH_INIT_PATH = \"org.openintents.extra.SEARCH_INIT_PATH\";\r\n\r\n /**\r\n * The search query as sent to SearchService.\r\n * <p>\r\n * <p>Constant Value: \"org.openintents.extra.SEARCH_QUERY\"</p>\r\n */\r\n public static final String EXTRA_SEARCH_QUERY = \"org.openintents.extra.SEARCH_QUERY\";\r\n\r\n /**\r\n * <p>Constant Value: \"org.openintents.extra.DIR_PATH\"</p>\r\n */\r\n public static final String EXTRA_DIR_PATH = \"org.openintents.extra.DIR_PATH\";\r\n\r\n /**\r\n * <p>Constant Value: \"org.openintents.extra.ABSOLUTE_PATH\"</p>\r\n */\r\n public static final String EXTRA_ABSOLUTE_PATH = \"org.openintents.extra.ABSOLUTE_PATH\";\r\n /**\r\n * Extension by which to filter.\r\n * <p>\r\n * <p>Constant Value: \"org.openintents.extra.FILTER_FILETYPE\"</p>\r\n */\r\n public static final String EXTRA_FILTER_FILETYPE = \"org.openintents.extra.FILTER_FILETYPE\";\r\n\r\n /**\r\n * Mimetype by which to filter.\r\n * <p>\r\n * <p>Constant Value: \"org.openintents.extra.FILTER_MIMETYPE\"</p>\r\n */\r\n public static final String EXTRA_FILTER_MIMETYPE = \"org.openintents.extra.FILTER_MIMETYPE\";\r\n\r\n /**\r\n * Only show directories.\r\n * <p>\r\n * <p>Constant Value: \"org.openintents.extra.DIRECTORIES_ONLY\"</p>\r\n */\r\n public static final String EXTRA_DIRECTORIES_ONLY = \"org.openintents.extra.DIRECTORIES_ONLY\";\r\n\r\n public static final String EXTRA_DIALOG_FILE_HOLDER = \"org.openintents.extra.DIALOG_FILE\";\r\n\r\n public static final String EXTRA_IS_GET_CONTENT_INITIATED = \"org.openintents.extra.ENABLE_ACTIONS\";\r\n\r\n public static final String EXTRA_FILENAME = \"org.openintents.extra.FILENAME\";\r\n\r\n public static final String EXTRA_FROM_OI_FILEMANAGER = \"org.openintents.extra.FROM_OI_FILEMANAGER\";\r\n\r\n private FileManagerIntents() {\r\n }\r\n}\r",
"public class MenuIntentOptionsWithIcons {\r\n\r\n Context mContext;\r\n Menu mMenu;\r\n\r\n public MenuIntentOptionsWithIcons(Context context, Menu menu) {\r\n mContext = context;\r\n mMenu = menu;\r\n }\r\n\r\n public int addIntentOptions(int group, int id, int categoryOrder,\r\n ComponentName caller, Intent[] specifics, Intent intent, int flags,\r\n MenuItem[] outSpecificItems) {\r\n PackageManager pm = mContext.getPackageManager();\r\n final List<ResolveInfo> lri = pm.queryIntentActivityOptions(caller,\r\n specifics, intent, 0);\r\n final int N = lri != null ? lri.size() : 0;\r\n if ((flags & Menu.FLAG_APPEND_TO_GROUP) == 0) {\r\n mMenu.removeGroup(group);\r\n }\r\n for (int i = 0; i < N; i++) {\r\n final ResolveInfo ri = lri.get(i);\r\n Intent rintent = new Intent(ri.specificIndex < 0 ? intent\r\n : specifics[ri.specificIndex]);\r\n rintent.setComponent(new ComponentName(\r\n ri.activityInfo.applicationInfo.packageName,\r\n ri.activityInfo.name));\r\n final MenuItem item = mMenu.add(group, id, categoryOrder,\r\n ri.loadLabel(pm)).setIcon(ri.loadIcon(pm)).setIntent(\r\n rintent);\r\n if (outSpecificItems != null && ri.specificIndex >= 0) {\r\n outSpecificItems[ri.specificIndex] = item;\r\n }\r\n }\r\n return N;\r\n }\r\n}\r"
] | import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import androidx.annotation.VisibleForTesting;
import androidx.appcompat.widget.Toolbar;
import org.openintents.distribution.DistributionLibrary;
import org.openintents.distribution.DistributionLibraryActivity;
import org.openintents.filemanager.bookmarks.BookmarkListActivity;
import org.openintents.filemanager.files.FileHolder;
import org.openintents.filemanager.lists.SimpleFileListFragment;
import org.openintents.filemanager.util.FileUtils;
import org.openintents.intents.FileManagerIntents;
import org.openintents.util.MenuIntentOptionsWithIcons;
import java.io.File; | /*
* Copyright (C) 2008 OpenIntents.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openintents.filemanager;
public class FileManagerActivity extends DistributionLibraryActivity {
@VisibleForTesting
public static final String FRAGMENT_TAG = "ListFragment";
protected static final int REQUEST_CODE_BOOKMARKS = 1;
private SimpleFileListFragment mFragment;
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if (intent.getData() != null) | mFragment.openInformingPathBar(new FileHolder(FileUtils.getFile(intent.getData()))); | 1 |
thomasjungblut/tjungblut-graph | test/de/jungblut/graph/bsp/SSSPTest.java | [
"public interface Graph<VERTEX_ID, VERTEX_VALUE, EDGE_VALUE> {\n\n /**\n * Adds a vertex with a single adjacent to it.\n */\n void addVertex(Vertex<VERTEX_ID, VERTEX_VALUE> vertex,\n Edge<VERTEX_ID, EDGE_VALUE> adjacent);\n\n /**\n * Adds a vertex with a no adjacents to it.\n */\n void addVertex(Vertex<VERTEX_ID, VERTEX_VALUE> vertex);\n\n /**\n * Adds a vertex with a list of adjacents to it.\n */\n void addVertex(Vertex<VERTEX_ID, VERTEX_VALUE> vertex,\n @SuppressWarnings(\"unchecked\") Edge<VERTEX_ID, EDGE_VALUE>... adjacents);\n\n /**\n * Gets a set of adjacent vertices from a given vertex id.\n */\n Set<Vertex<VERTEX_ID, VERTEX_VALUE>> getAdjacentVertices(VERTEX_ID vertexId);\n\n /**\n * Get the vertex by its id.\n */\n Vertex<VERTEX_ID, VERTEX_VALUE> getVertex(VERTEX_ID vertexId);\n\n /**\n * Gets a set of adjacent vertices from a given vertex.\n */\n Set<Vertex<VERTEX_ID, VERTEX_VALUE>> getAdjacentVertices(Vertex<VERTEX_ID, VERTEX_VALUE> vertex);\n\n /**\n * Gets all vertices associated with this graph.\n */\n Set<Vertex<VERTEX_ID, VERTEX_VALUE>> getVertexSet();\n\n /**\n * Gets all verte IDs associated with this graph.\n */\n Set<VERTEX_ID> getVertexIDSet();\n\n /**\n * Adds an edge to a vertex.\n */\n void addEdge(VERTEX_ID vertexId, Edge<VERTEX_ID, EDGE_VALUE> edge);\n\n /**\n * Get's a set of edges outbound from the given vertex id.\n *\n * @param vertexId the id of the vertex to get out edges.\n * @return a set of edges.\n */\n Set<Edge<VERTEX_ID, EDGE_VALUE>> getEdges(VERTEX_ID vertexId);\n\n\n /**\n * Finds an edge between the source and destination vertex.\n *\n * @return null if nothing found, else the edge between those twos.\n */\n Edge<VERTEX_ID, EDGE_VALUE> getEdge(VERTEX_ID source, VERTEX_ID dest);\n\n /**\n * @return how many vertices are present in this graph.\n */\n int getNumVertices();\n\n /**\n * @return how many edges are present in this graph.\n */\n int getNumEdges();\n\n /**\n * @return the transpose of this graph, meaning that it will reverse all edges.\n * So if there was an edge from A->B, the returned graph will contain one for B->A instead.\n */\n Graph<VERTEX_ID, VERTEX_VALUE, EDGE_VALUE> transpose();\n\n}",
"public class TestGraphProvider {\n\n /**\n * from {@link https://de.wikipedia.org/wiki/Dijkstra-Algorithmus#Beispiel}\n */\n @SuppressWarnings({\"unchecked\"})\n public static Graph<Integer, String, Integer> getWikipediaExampleGraph() {\n Graph<Integer, String, Integer> graph = new AdjacencyList<>();\n\n ArrayList<VertexImpl<Integer, String>> cities = new ArrayList<>();\n\n cities.add(new VertexImpl<>(0, \"Frankfurt\"));\n cities.add(new VertexImpl<>(1, \"Mannheim\"));\n cities.add(new VertexImpl<>(2, \"Wuerzburg\"));\n cities.add(new VertexImpl<>(3, \"Stuttgart\"));\n cities.add(new VertexImpl<>(4, \"Kassel\"));\n cities.add(new VertexImpl<>(5, \"Karlsruhe\"));\n cities.add(new VertexImpl<>(6, \"Erfurt\"));\n cities.add(new VertexImpl<>(7, \"Nuernberg\"));\n cities.add(new VertexImpl<>(8, \"Augsburg\"));\n cities.add(new VertexImpl<>(9, \"Muenchen\"));\n\n // frankfurt -> mannheim, kassel, wuerzburg\n graph.addVertex(cities.get(0),\n new Edge<>(cities.get(1).getVertexId(), 85),\n new Edge<>(cities.get(4).getVertexId(), 173),\n new Edge<>(cities.get(2).getVertexId(), 217));\n\n // mannheim -> frankfurt, karlsruhe\n graph.addVertex(cities.get(1),\n new Edge<>(cities.get(0).getVertexId(), 85),\n new Edge<>(cities.get(5).getVertexId(), 80));\n\n // wuerzburg -> frankfurt, erfurt, nuernberg\n graph.addVertex(cities.get(2),\n new Edge<>(cities.get(0).getVertexId(), 217),\n new Edge<>(cities.get(6).getVertexId(), 186),\n new Edge<>(cities.get(7).getVertexId(), 103));\n\n // stuttgart -> nuernberg\n graph.addVertex(cities.get(3), new Edge<>(cities.get(7).getVertexId(), 183));\n\n // kassel -> muenchen, frankfurt\n graph.addVertex(cities.get(4),\n new Edge<>(cities.get(9).getVertexId(), 502),\n new Edge<>(cities.get(0).getVertexId(), 173));\n\n // karlsruhe -> mannheim, augsburg\n graph.addVertex(cities.get(5),\n new Edge<>(cities.get(1).getVertexId(), 80),\n new Edge<>(cities.get(8).getVertexId(), 250));\n\n // erfurt -> wuerzburg\n graph.addVertex(cities.get(6), new Edge<>(cities.get(2).getVertexId(), 186));\n\n // nuernberg -> stuttgart, muenchen, wuerzburg\n graph.addVertex(cities.get(7),\n new Edge<>(cities.get(3).getVertexId(), 183),\n new Edge<>(cities.get(9).getVertexId(), 167),\n new Edge<>(cities.get(2).getVertexId(), 103));\n\n // augsburg -> karlsruhe, muenchen\n graph.addVertex(cities.get(8),\n new Edge<>(cities.get(5).getVertexId(), 250),\n new Edge<>(cities.get(9).getVertexId(), 84));\n\n // muenchen -> nuernberg, kassel, augsburg\n graph.addVertex(cities.get(9),\n new Edge<>(cities.get(7).getVertexId(), 167),\n new Edge<>(cities.get(4).getVertexId(), 502),\n new Edge<>(cities.get(8).getVertexId(), 84));\n\n return graph;\n }\n\n /**\n * from {@link https://en.wikipedia.org/wiki/Topological_sorting}\n */\n @SuppressWarnings(\"unchecked\")\n public static Graph<Integer, String, Integer> getTopologicalSortWikipediaExampleGraph() {\n Graph<Integer, String, Integer> graph = new AdjacencyList<>();\n\n ArrayList<VertexImpl<Integer, String>> cities = new ArrayList<>();\n\n // 7, 5, 3, 11, 8, 2, 9, 10\n cities.add(new VertexImpl<>(7, \"\")); // 0\n cities.add(new VertexImpl<>(5, \"\")); // 1\n cities.add(new VertexImpl<>(3, \"\")); // 2\n cities.add(new VertexImpl<>(11, \"\")); // 3\n cities.add(new VertexImpl<>(8, \"\")); // 4\n cities.add(new VertexImpl<>(2, \"\")); // 5\n cities.add(new VertexImpl<>(9, \"\")); // 6\n cities.add(new VertexImpl<>(10, \"\")); // 7\n\n // 7 -> 11, 8\n graph.addVertex(cities.get(0),\n new Edge<>(cities.get(3).getVertexId(), null),\n new Edge<>(cities.get(4).getVertexId(), null));\n // 5 -> 11\n graph.addVertex(cities.get(1), new Edge<>(cities.get(3).getVertexId(), null));\n // 3 -> 8,10\n graph.addVertex(cities.get(2),\n new Edge<>(cities.get(4).getVertexId(), null),\n new Edge<>(cities.get(7).getVertexId(), null));\n // 11 -> 2,9,10\n graph.addVertex(cities.get(3),\n new Edge<>(cities.get(2).getVertexId(), null),\n new Edge<>(cities.get(6).getVertexId(), null),\n new Edge<>(cities.get(7).getVertexId(), null));\n // 8 -> 9\n graph.addVertex(cities.get(4), new Edge<>(cities.get(6).getVertexId(), null));\n // 2 -> nowhere\n graph.addVertex(cities.get(5));\n // 9 -> nowhere\n graph.addVertex(cities.get(6));\n // 10 -> nowhere\n graph.addVertex(cities.get(7));\n\n return graph;\n }\n\n}",
"public static class IntIntPairWritable implements Writable {\n\n public int id;\n public int distance;\n\n public IntIntPairWritable() {\n }\n\n public IntIntPairWritable(int id, int distance) {\n super();\n this.id = id;\n this.distance = distance;\n }\n\n public int getId() {\n return id;\n }\n\n public int getDistance() {\n return distance;\n }\n\n @Override\n public void readFields(DataInput in) throws IOException {\n id = WritableUtils.readVInt(in);\n distance = WritableUtils.readVInt(in);\n }\n\n @Override\n public void write(DataOutput out) throws IOException {\n WritableUtils.writeVInt(out, id);\n WritableUtils.writeVInt(out, distance);\n }\n\n @Override\n public String toString() {\n return id + \"\\t\" + distance;\n }\n\n}",
"public static class SSSPTextReader\n extends\n VertexInputReader<LongWritable, Text, IntWritable, IntWritable, IntIntPairWritable> {\n\n /**\n * The text file essentially should look like: <br/>\n * VERTEX_ID\\t(n-tab separated VERTEX_ID:VERTEX_VALUE pairs)<br/>\n * E.G:<br/>\n * 1\\t2:25\\t3:32\\t4:21<br/>\n * 2\\t3:222\\t1:922<br/>\n * etc.\n */\n @Override\n public boolean parseVertex(LongWritable key, Text value,\n Vertex<IntWritable, IntWritable, IntIntPairWritable> vertex) {\n String[] split = value.toString().split(\"\\t\");\n for (int i = 0; i < split.length; i++) {\n if (i == 0) {\n vertex.setVertexID(new IntWritable(Integer.parseInt(split[i])));\n } else {\n String[] split2 = split[i].split(\":\");\n vertex.addEdge(new Edge<>(\n new IntWritable(Integer.parseInt(split2[0])), new IntWritable(\n Integer.parseInt(split2[1]))));\n }\n }\n return true;\n }\n\n}",
"public static class ShortestPathVertex extends\n Vertex<IntWritable, IntWritable, IntIntPairWritable> {\n\n @Override\n public void setup(HamaConfiguration conf) {\n this.setValue(new IntIntPairWritable(this.getVertexID().get(),\n Integer.MAX_VALUE));\n }\n\n public boolean isStartVertex() {\n int startVertex = getConf().getInt(START_VERTEX, -1);\n return (this.getVertexID().get() == startVertex);\n }\n\n @Override\n public void compute(Iterable<IntIntPairWritable> messages)\n throws IOException {\n int minDist = isStartVertex() ? 0 : Integer.MAX_VALUE;\n int minPredecessor = getVertexID().get();\n for (IntIntPairWritable msg : messages) {\n if (msg.getDistance() < minDist) {\n minDist = msg.getDistance();\n minPredecessor = msg.getId();\n }\n }\n\n if (minDist < this.getValue().getDistance()) {\n this.setValue(new IntIntPairWritable(minPredecessor, minDist));\n for (Edge<IntWritable, IntWritable> e : this.getEdges()) {\n sendMessage(e, new IntIntPairWritable(this.getVertexID().get(),\n minDist + e.getValue().get()));\n }\n } else {\n voteToHalt();\n }\n }\n}",
"public final class Edge<VERTEX_ID, EDGE_VALUE> {\n\n private final VERTEX_ID destinationVertexID;\n private final EDGE_VALUE cost;\n\n public Edge(VERTEX_ID destinationVertexID, EDGE_VALUE cost) {\n this.destinationVertexID = destinationVertexID;\n this.cost = cost;\n }\n\n public VERTEX_ID getDestinationVertexID() {\n return destinationVertexID;\n }\n\n public EDGE_VALUE getValue() {\n return cost;\n }\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime\n * result\n + ((this.destinationVertexID == null) ? 0 : this.destinationVertexID\n .hashCode());\n return result;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj)\n return true;\n if (obj == null)\n return false;\n if (getClass() != obj.getClass())\n return false;\n @SuppressWarnings(\"rawtypes\")\n Edge other = (Edge) obj;\n if (this.destinationVertexID == null) {\n if (other.destinationVertexID != null)\n return false;\n } else if (!this.destinationVertexID.equals(other.destinationVertexID))\n return false;\n return true;\n }\n\n @Override\n public String toString() {\n return this.destinationVertexID + \":\" + this.getValue();\n }\n\n}",
"public interface Vertex<VERTEX_ID, VERTEX_VALUE> {\n\n /**\n * @return the id of this vertex.\n */\n VERTEX_ID getVertexId();\n\n /**\n * @return the value of this vertex.\n */\n VERTEX_VALUE getVertexValue();\n\n}"
] | import de.jungblut.graph.Graph;
import de.jungblut.graph.TestGraphProvider;
import de.jungblut.graph.bsp.SSSP.IntIntPairWritable;
import de.jungblut.graph.bsp.SSSP.SSSPTextReader;
import de.jungblut.graph.bsp.SSSP.ShortestPathVertex;
import de.jungblut.graph.model.Edge;
import de.jungblut.graph.model.Vertex;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hama.HamaConfiguration;
import org.apache.hama.bsp.HashPartitioner;
import org.apache.hama.bsp.TextInputFormat;
import org.apache.hama.bsp.TextOutputFormat;
import org.apache.hama.graph.GraphJob;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import java.io.*;
import java.util.EnumSet;
import java.util.Set; | package de.jungblut.graph.bsp;
public final class SSSPTest {
@Test
@Ignore("BSP partitioning job fails without proper reason")
public void testSSSP() throws Exception {
// Graph job configuration
HamaConfiguration conf = new HamaConfiguration();
conf.set("bsp.local.tasks.maximum", "2");
GraphJob ssspJob = new GraphJob(conf, SSSP.class);
// Set the job name
ssspJob.setJobName("Single Source Shortest Path");
FileContext fs = FileContext.getFileContext(conf);
Path in = new Path(TestHelpers.getTempDir() + "/sssp/input.txt");
createInput(fs, in);
Path out = new Path(TestHelpers.getTempDir() + "/sssp/out/");
if (fs.util().exists(out)) {
fs.delete(out, true);
}
conf.set(SSSP.START_VERTEX, "0");
ssspJob.setNumBspTask(2);
ssspJob.setInputPath(in);
ssspJob.setOutputPath(out);
ssspJob.setVertexClass(ShortestPathVertex.class);
ssspJob.setInputFormat(TextInputFormat.class);
ssspJob.setInputKeyClass(LongWritable.class);
ssspJob.setInputValueClass(Text.class);
ssspJob.setPartitioner(HashPartitioner.class);
ssspJob.setOutputFormat(TextOutputFormat.class);
ssspJob.setVertexInputReaderClass(SSSPTextReader.class);
ssspJob.setOutputKeyClass(IntWritable.class);
ssspJob.setOutputValueClass(IntIntPairWritable.class);
// Iterate until all the nodes have been reached.
ssspJob.setMaxIteration(Integer.MAX_VALUE);
ssspJob.setVertexIDClass(IntWritable.class);
ssspJob.setVertexValueClass(IntIntPairWritable.class);
ssspJob.setEdgeValueClass(IntWritable.class);
long startTime = System.currentTimeMillis();
if (ssspJob.waitForCompletion(true)) {
System.out.println("Job Finished in "
+ (System.currentTimeMillis() - startTime) / 1000.0 + " seconds");
verifyOutput(fs, out);
}
}
private void createInput(FileContext fs, Path in) throws IOException {
if (fs.util().exists(in)) {
fs.delete(in, true);
} else {
fs.mkdir(in.getParent(), FsPermission.getDefault(), true);
}
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
fs.create(in, EnumSet.of(CreateFlag.CREATE, CreateFlag.OVERWRITE))))) {
Graph<Integer, String, Integer> wikipediaExampleGraph = TestGraphProvider
.getWikipediaExampleGraph();
for (Vertex<Integer, String> v : wikipediaExampleGraph.getVertexSet()) { | Set<Edge<Integer, Integer>> adjacentVertices = wikipediaExampleGraph | 5 |
hnakagawa/proton | Proton/src/instrumentTest/java/proton/inject/state/StateRecoveryTest.java | [
"public class DefaultModule extends AbstractModule {\n @SuppressWarnings(\"rawtypes\")\n private static final Class mAccountManagerClass = loadClass(\"android.accounts.AccountManager\");\n\n private static Class<?> loadClass(String className) {\n try {\n return Class.forName(className);\n } catch (Throwable t) {\n return null;\n }\n }\n\n @SuppressWarnings(\"unchecked\")\n protected void configure() {\n bind(Application.class).toProvider(ApplicationProvider.class).in(ApplicationScoped.class);\n bind(Context.class).toProvider(ContextProvider.class);\n bind(Handler.class).toProvider(HandlerProvider.class).in(ApplicationScoped.class);\n\n bind(ActivityManager.class).toProvider(new SystemServiceProvider<ActivityManager>(Context.ACTIVITY_SERVICE));\n bind(AlarmManager.class).toProvider(new SystemServiceProvider<AlarmManager>(Context.ALARM_SERVICE));\n bind(AudioManager.class).toProvider(new SystemServiceProvider<AudioManager>(Context.AUDIO_SERVICE));\n bind(ConnectivityManager.class).toProvider(\n new SystemServiceProvider<ConnectivityManager>(Context.CONNECTIVITY_SERVICE));\n bind(InputMethodManager.class).toProvider(\n new SystemServiceProvider<InputMethodManager>(Context.INPUT_METHOD_SERVICE));\n bind(KeyguardManager.class).toProvider(new SystemServiceProvider<KeyguardManager>(Context.KEYGUARD_SERVICE));\n\n bind(LocationManager.class).toProvider(new SystemServiceProvider<LocationManager>(Context.LOCATION_SERVICE));\n bind(NotificationManager.class).toProvider(\n new SystemServiceProvider<NotificationManager>(Context.NOTIFICATION_SERVICE));\n bind(PowerManager.class).toProvider(new SystemServiceProvider<PowerManager>(Context.POWER_SERVICE));\n bind(SensorManager.class).toProvider(new SystemServiceProvider<SensorManager>(Context.SENSOR_SERVICE));\n bind(TelephonyManager.class).toProvider(new SystemServiceProvider<TelephonyManager>(Context.TELEPHONY_SERVICE));\n bind(Vibrator.class).toProvider(new SystemServiceProvider<Vibrator>(Context.VIBRATOR_SERVICE));\n bind(WifiManager.class).toProvider(new SystemServiceProvider<WifiManager>(Context.WIFI_SERVICE));\n bind(WindowManager.class).toProvider(new SystemServiceProvider<WindowManager>(Context.WINDOW_SERVICE));\n\n bind(mAccountManagerClass).toProvider(AccountManagerProvider.class);\n\n bind(ObserverManager.class);\n bindProviderListener(new ObserverRegister());\n\n bind(StateManager.class).in(ApplicationScoped.class);\n bind(StateEventObserver.class);\n bindFieldListener(RetainState.class, new RetainStateListener());\n }\n}",
"public class MockContext extends android.test.mock.MockContext {\n\tprivate Application mApplication;\n\n\tpublic MockContext(Application application) {\n\t\tmApplication = application;\n\t}\n\n\t@Override\n\tpublic Context getApplicationContext() {\n\t\treturn mApplication;\n\t}\n}",
"public final class Proton {\n private static Map<Context, InjectorImpl> sInjectors;\n private static Bindings sBindings;\n private static ProviderListeners sProviderListeners;\n private static FieldListeners sFieldListeners;\n\n private Proton() {\n }\n\n public static void initialize(Application app) {\n initialize(app, new DefaultModule());\n }\n\n public static void initialize(Application app, Module... modules) {\n synchronized (Proton.class) {\n checkState(sInjectors == null, \"Already initialized Proton\");\n sInjectors = new WeakHashMap<Context, InjectorImpl>();\n sBindings = new Bindings();\n sProviderListeners = new ProviderListeners();\n sFieldListeners = new FieldListeners();\n\n for (Module module : modules)\n module.configure(sBindings, sProviderListeners, sFieldListeners);\n\n InjectorImpl injector = new InjectorImpl(app, sBindings, sProviderListeners, sFieldListeners, null);\n sInjectors.put(app, injector);\n }\n }\n\n public static Injector getInjector(Context context) {\n synchronized (Proton.class) {\n checkInitialize();\n InjectorImpl injector = sInjectors.get(context);\n if (injector == null) {\n InjectorImpl parent = sInjectors.get(context.getApplicationContext());\n injector = new InjectorImpl(context, sBindings, sProviderListeners, sFieldListeners, parent);\n sInjectors.put(context, injector);\n }\n return injector;\n }\n }\n\n public static void destroy() {\n synchronized (Proton.class) {\n checkInitialize();\n sProviderListeners = null;\n sBindings = null;\n sInjectors = null;\n }\n }\n\n public static void destroyInjector(Context context) {\n synchronized (Proton.class) {\n checkInitialize();\n sInjectors.remove(context);\n }\n }\n\n private static void checkInitialize() {\n checkNotNull(sInjectors, \"Proton is not initialized yet\");\n }\n}",
"public class ObserverManager {\n private SparseClassArray<List<Observer>> mObservers = new SparseClassArray<List<Observer>>();\n\n public void registerIfObserver(Object obj) {\n for (Class<?> clazz = obj.getClass(); clazz != Object.class; clazz = clazz.getSuperclass()) {\n for (Method method : clazz.getDeclaredMethods()) {\n Class<?> eventClass = findObserveEvent(method);\n if (eventClass != null)\n register(eventClass, new Observer(obj, method));\n }\n }\n }\n\n private void register(Class<?> eventClass, Observer observer) {\n synchronized (this) {\n List<Observer> list = mObservers.get(eventClass);\n if (list == null) {\n list = new ArrayList<Observer>();\n mObservers.put(eventClass, list);\n }\n list.add(observer);\n }\n }\n\n public void fire(Object event) {\n synchronized (this) {\n List<Observer> list = mObservers.get(event.getClass());\n if (list == null)\n return;\n\n for (Observer observer : list) {\n try {\n observer.method.invoke(observer.receiver, event);\n } catch (IllegalArgumentException exp) {\n throw new InvocationException(exp);\n } catch (IllegalAccessException exp) {\n throw new InvocationException(exp);\n } catch (InvocationTargetException exp) {\n throw new InvocationException(exp);\n }\n }\n }\n }\n\n public void destroy() {\n synchronized (this) {\n mObservers.clear();\n }\n }\n\n private Class<?> findObserveEvent(Method method) {\n Annotation[][] parameterAnnotations = method.getParameterAnnotations();\n for (int i = 0; i < parameterAnnotations.length; ++i) {\n Annotation[] annotations = parameterAnnotations[i];\n Class<?> type = method.getParameterTypes()[i];\n for (Annotation ann : annotations) {\n if (ann.annotationType() == Observes.class)\n return type;\n }\n }\n return null;\n }\n\n private static class Observer {\n private Object receiver;\n private Method method;\n\n private Observer(Object receiver, Method method) {\n this.receiver = receiver;\n this.method = method;\n }\n }\n}",
"public class OnCreateEvent {\n private final Bundle mSavedInstanceState;\n\n public OnCreateEvent(Bundle savedInstanceState) {\n mSavedInstanceState = savedInstanceState;\n }\n\n public Bundle getSavedInstanceState() {\n return mSavedInstanceState;\n }\n}",
"public class OnDestroyEvent {\n}",
"public class OnSaveInstanceStateEvent {\n private final Bundle mOutState;\n\n public OnSaveInstanceStateEvent(Bundle outState) {\n mOutState = outState;\n }\n\n public Bundle getOutState() {\n return mOutState;\n }\n}"
] | import java.util.ArrayList;
import proton.inject.DefaultModule;
import proton.inject.Injector;
import proton.inject.MockContext;
import proton.inject.Proton;
import proton.inject.observer.ObserverManager;
import proton.inject.observer.event.OnCreateEvent;
import proton.inject.observer.event.OnDestroyEvent;
import proton.inject.observer.event.OnSaveInstanceStateEvent;
import android.app.Application;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.test.AndroidTestCase;
import android.test.mock.MockApplication; | package proton.inject.state;
public class StateRecoveryTest extends AndroidTestCase {
private Application mMockApplication;
private Injector mInjector;
private ObserverManager mObserverManager;
@SuppressWarnings("unused")
private StateEventObserver mStateEventObserver;
@Override
protected void setUp() throws Exception {
super.setUp();
mMockApplication = new MockApplication();
Proton.initialize(mMockApplication, new DefaultModule() {
@Override
protected void configure() {
super.configure();
bind(Aaa.class);
}
});
mInjector = Proton.getInjector(new MockContext(mMockApplication));
mObserverManager = mInjector.getInstance(ObserverManager.class);
mStateEventObserver = mInjector.getInstance(StateEventObserver.class);
}
@Override
protected void tearDown() throws Exception {
Proton.destroy();
super.tearDown();
}
public void testRecovery() { | mObserverManager.fire(new OnCreateEvent(null)); | 4 |
Kestutis-Z/World-Weather | WorldWeather/app/src/main/java/com/haringeymobile/ukweather/database/GeneralDatabaseService.java | [
"public class CityManagementActivity extends ThemedActivity implements\n CityListFragmentWithUtilityButtons.OnUtilityButtonClickedListener,\n CityUtilitiesCursorAdapter.Listener,\n DeleteCityDialog.OnDialogButtonClickedListener {\n\n public static final String CITY_ID = \"city id\";\n public static final String CITY_NEW_NAME = \"city new name\";\n public static final String CITY_ORDER_FROM = \"city order x\";\n public static final String CITY_ORDER_TO = \"city order y\";\n static final String CITY_DELETE_DIALOG_FRAGMENT_TAG = \"delete city dialog\";\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n setTheme(R.style.AppTheme);\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_city_management);\n Toolbar toolbar = (Toolbar) findViewById(R.id.general_toolbar);\n setSupportActionBar(toolbar);\n ActionBar actionBar = getSupportActionBar();\n if (actionBar != null) {\n actionBar.setDisplayHomeAsUpEnabled(true);\n }\n toolbar.setNavigationIcon(R.drawable.ic_action_arrow_left);\n }\n\n @Override\n public void onCityNameChangeRequested(final int cityId, final String originalName) {\n AlertDialog.Builder cityNameChangeDialog = new AlertDialog.Builder(this);\n\n String dialogTitle = getDialogTitle(originalName);\n cityNameChangeDialog.setTitle(dialogTitle);\n\n final EditText cityNameEditText = getNewCityNameEditText();\n cityNameChangeDialog.setView(cityNameEditText);\n\n DialogInterface.OnClickListener dialogOnClickListener = getDialogOnClickListener(\n cityId, originalName, cityNameEditText);\n cityNameChangeDialog.setPositiveButton(android.R.string.ok, dialogOnClickListener);\n\n cityNameChangeDialog.show();\n }\n\n /**\n * Creates the dialog's title.\n *\n * @param originalName current city name\n * @return the dialog title, asking to enter a new name for the city\n */\n private String getDialogTitle(final String originalName) {\n Resources res = getResources();\n return String.format(res.getString(R.string.dialog_title_rename_city), originalName);\n }\n\n /**\n * Obtains an editable view were the new city name should be typed in.\n *\n * @return an editable view for the new city name\n */\n private EditText getNewCityNameEditText() {\n final EditText cityNameEditText = new EditText(this);\n LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(\n LinearLayout.LayoutParams.WRAP_CONTENT,\n LinearLayout.LayoutParams.WRAP_CONTENT);\n cityNameEditText.setLayoutParams(lp);\n return cityNameEditText;\n }\n\n /**\n * Obtain a listener for dialog button clicks.\n *\n * @param cityId OpenWeatherMap city ID\n * @param originalName current city name\n * @param cityNameEditText an editable view for the new city name\n * @return a dialog button clicks listener\n */\n private DialogInterface.OnClickListener getDialogOnClickListener(\n final int cityId, final String originalName,\n final EditText cityNameEditText) {\n DialogInterface.OnClickListener dialogOnClickListener = new DialogInterface.OnClickListener() {\n\n @Override\n public void onClick(DialogInterface dialog, int whichButton) {\n String newName = cityNameEditText.getText().toString();\n if (newName.length() == 0) {\n showEmptyNameErrorMessage();\n } else {\n boolean userNameHasBeenChanged = !newName.equals(originalName);\n if (userNameHasBeenChanged) {\n renameCity(cityId, newName);\n }\n }\n }\n };\n return dialogOnClickListener;\n }\n\n /**\n * Displays a message informing that the new name cannot be an empty string.\n */\n private void showEmptyNameErrorMessage() {\n Toast.makeText(this, R.string.message_enter_city_name, Toast.LENGTH_SHORT).show();\n }\n\n /**\n * Renames the specified city.\n *\n * @param cityId OpenWeatherMap city ID\n * @param newName a new name for the city\n */\n private void renameCity(int cityId, String newName) {\n Intent intent = new Intent(this, GeneralDatabaseService.class);\n intent.setAction(GeneralDatabaseService.ACTION_RENAME_CITY);\n intent.putExtra(CITY_ID, cityId);\n intent.putExtra(CITY_NEW_NAME, newName);\n startService(intent);\n }\n\n @Override\n public void onCityRecordDeletionRequested(int cityId, String cityName) {\n FragmentManager fragmentManager = getSupportFragmentManager();\n DeleteCityDialog dialogFragment = (DeleteCityDialog) fragmentManager\n .findFragmentByTag(CITY_DELETE_DIALOG_FRAGMENT_TAG);\n if (dialogFragment == null) {\n dialogFragment = DeleteCityDialog.newInstance(cityId, cityName);\n dialogFragment.show(fragmentManager, CITY_DELETE_DIALOG_FRAGMENT_TAG);\n }\n }\n\n @Override\n public void onCityRecordDeletionConfirmed(int cityId) {\n removeCityById(cityId);\n }\n\n @Override\n public void removeCityById(int cityId) {\n updateLastRequestedCityInfo(cityId);\n Intent intent = new Intent(this, GeneralDatabaseService.class);\n intent.setAction(GeneralDatabaseService.ACTION_DELETE_CITY_RECORDS);\n intent.putExtra(CITY_ID, cityId);\n startService(intent);\n }\n\n /**\n * Makes note in the SharedPreferences if the city to be deleted is also the\n * last city to be queried for weather information (so the next time an\n * automatic weather information request is made, it won't be necessary to\n * go to the database to check if the city still exists).\n *\n * @param cityId OpenWeatherMap city ID\n */\n private void updateLastRequestedCityInfo(int cityId) {\n int lastCityId = SharedPrefsHelper.getCityIdFromSharedPrefs(this);\n if (cityId == lastCityId) {\n SharedPrefsHelper.putCityIdIntoSharedPrefs(this, CityTable.CITY_ID_DOES_NOT_EXIST,\n false);\n }\n }\n\n @Override\n public void dragCity(int cityOrderFrom, int cityOrderTo) {\n Intent intent = new Intent(this, GeneralDatabaseService.class);\n intent.setAction(GeneralDatabaseService.ACTION_DRAG_CITY);\n intent.putExtra(CITY_ORDER_FROM, cityOrderFrom);\n intent.putExtra(CITY_ORDER_TO, cityOrderTo);\n startService(intent);\n }\n\n}",
"public class MainActivity extends RefreshingActivity implements\n CityListFragmentWithWeatherButtons.OnWeatherInfoButtonClickedListener,\n GetAvailableCitiesTask.OnCitySearchResponseRetrievedListener,\n CitySearchResultsDialog.OnCityNamesListItemClickedListener,\n AddCityFragment.OnNewCityQueryTextListener,\n FindCitiesQueryProcessor.InvalidQueryListener,\n SharedPreferences.OnSharedPreferenceChangeListener {\n\n public static final String CITY_ID = \"city id\";\n public static final String CITY_NAME = \"city name\";\n public static final String LIST_FRAGMENT_TAG = \"list fragment\";\n public static final String WORKER_FRAGMENT_TAG = \"worker fragment\";\n private static final String ADD_CITY_FRAGMENT_TAG = \"add city dialog\";\n private static final String QUERY_STRING_TOO_SHORT_ALERT_DIALOG_FRAGMENT_TAG =\n \"short query fragment\";\n\n private SearchResponseForFindQuery searchResponseForFindQuery;\n private boolean isDualPane;\n\n private SearchView searchView;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n Toolbar toolbar = (Toolbar) findViewById(R.id.general_toolbar);\n setSupportActionBar(toolbar);\n\n isDualPane = findViewById(R.id.weather_info_container) != null;\n\n FragmentManager fragmentManager = getSupportFragmentManager();\n FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();\n workerFragment = (WorkerFragmentToRetrieveJsonString) fragmentManager\n .findFragmentByTag(WORKER_FRAGMENT_TAG);\n if (workerFragment == null) {\n workerFragment = new WorkerFragmentToRetrieveJsonString();\n fragmentTransaction.add(workerFragment, WORKER_FRAGMENT_TAG);\n }\n Fragment cityListFragment = fragmentManager.findFragmentByTag(LIST_FRAGMENT_TAG);\n if (cityListFragment == null) {\n cityListFragment = new CityListFragmentWithWeatherButtons();\n fragmentTransaction.add(R.id.city_list_container, cityListFragment,\n LIST_FRAGMENT_TAG);\n }\n fragmentTransaction.commit();\n\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);\n prefs.registerOnSharedPreferenceChangeListener(this);\n\n if (searchView != null) {\n handleIntent(getIntent());\n }\n }\n\n /**\n * Handles the intent that was provided to custom search suggestions, as described in\n * http://developer.android.com/guide/topics/search/adding-custom-suggestions.html#HandlingIntent\n *\n * @param intent the intent that started this activity. Since this activity is searchable and\n * \"single top\", a new intent will replace the old one each time the user\n * performs a search\n */\n private void handleIntent(Intent intent) {\n final SqlOperation sqlOperation = new SqlOperation(this);\n boolean collapseSearchViewAfterHandlingIntent = true;\n\n if (Intent.ACTION_SEARCH.equals(intent.getAction())) {\n // Handle the search request\n CursorAdapter cursorAdapter = searchView.getSuggestionsAdapter();\n if (cursorAdapter != null) {\n int cityCount = cursorAdapter.getCount();\n if (cityCount == 0) {\n collapseSearchViewAfterHandlingIntent = false;\n showAlertDialog(R.string.dialog_title_no_cities_found);\n } else {\n final long[] rowIds = new long[cityCount];\n for (int i = 0; i < cityCount; i++) {\n rowIds[i] = cursorAdapter.getItemId(i);\n }\n\n new Thread(new Runnable() {\n\n @Override\n public void run() {\n sqlOperation.setLastOverallQueryTimeToCurrentTime(rowIds);\n }\n }).start();\n }\n }\n } else if (Intent.ACTION_VIEW.equals(intent.getAction())) {\n // Handle a suggestions click\n final Uri data = intent.getData();\n final long rowId = Long.valueOf(data.getLastPathSegment());\n\n new Thread(new Runnable() {\n\n @Override\n public void run() {\n sqlOperation.setLastOverallQueryTimeToCurrentTime(rowId);\n }\n }).start();\n }\n\n if (collapseSearchViewAfterHandlingIntent) {\n if (searchView != null) {\n searchView.onActionViewCollapsed();\n }\n }\n }\n\n @Override\n protected void onNewIntent(Intent intent) {\n super.onNewIntent(intent);\n // important - we set a new intent as a default intent, so the search suggestions can\n // be handled properly\n setIntent(intent);\n handleIntent(getIntent());\n }\n\n @Override\n protected void onRestoreInstanceState(Bundle savedInstanceState) {\n super.onRestoreInstanceState(savedInstanceState);\n String jsonString = savedInstanceState.getString(WEATHER_INFO_JSON_STRING);\n if (jsonString != null) {\n searchResponseForFindQuery = new Gson().fromJson(jsonString,\n SearchResponseForFindQuery.class);\n }\n }\n\n @Override\n protected void onStart() {\n super.onStart();\n if (isDualPane) {\n workerFragment.retrieveLastRequestedWeatherInfo();\n }\n }\n\n @Override\n protected void onSaveInstanceState(Bundle outState) {\n super.onSaveInstanceState(outState);\n if (searchResponseForFindQuery != null) {\n outState.putString(WEATHER_INFO_JSON_STRING,\n new Gson().toJson(searchResponseForFindQuery));\n }\n }\n\n @Override\n public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {\n if (PREF_APP_THEME.equals(key)) {\n recreate();\n } else if (PREF_APP_LANGUAGE.equals(key)) {\n SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);\n String appLocaleCode = preferences.getString(PREF_APP_LANGUAGE, LANGUAGE_DEFAULT);\n\n String newAppLocaleCode;\n if (appLocaleCode.equals(LANGUAGE_DEFAULT)) {\n newAppLocaleCode = WorldWeatherApplication.systemLocaleCode;\n } else {\n newAppLocaleCode = appLocaleCode;\n }\n MiscMethods.updateLocale(newAppLocaleCode, getResources());\n\n recreate();\n resetActionBarTitle();\n }\n }\n\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n getMenuInflater().inflate(R.menu.main, menu);\n setCitySearching(menu);\n return true;\n }\n\n /**\n * Locates the search view in the action bar, and prepares it for city searching.\n *\n * @param menu options menu containing the city search view\n */\n private void setCitySearching(Menu menu) {\n MenuItem searchItem = menu.findItem(R.id.mi_search_cities);\n searchView = (SearchView) MenuItemCompat.getActionView(searchItem);\n\n SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);\n searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));\n searchView.setSubmitButtonEnabled(true);\n searchView.setQueryHint(getResources().getString(R.string.city_searchable_hint));\n }\n\n @Override\n public void showAlertDialog(final int stringResourceId) {\n GeneralDialogFragment.newInstance(getResources().getString(stringResourceId), null).\n show(getSupportFragmentManager(), QUERY_STRING_TOO_SHORT_ALERT_DIALOG_FRAGMENT_TAG);\n }\n\n /**\n * If there is a network connection, and the user query is valid, starts the task to search the\n * cities satisfying the provided query.\n *\n * @param query a location search text provided by the user\n */\n @Override\n public void onQueryTextSubmit(String query) {\n if (MiscMethods.isUserOnline(MainActivity.this)) {\n FindCitiesQueryProcessor findCitiesQueryProcessor =\n new FindCitiesQueryProcessor(this, query);\n URL url = findCitiesQueryProcessor.getUrlForFindCitiesQuery(this);\n if (url != null) {\n new GetAvailableCitiesTask(MainActivity.this).execute(url);\n }\n } else {\n Toast.makeText(MainActivity.this, R.string.error_message_no_connection,\n Toast.LENGTH_SHORT).show();\n }\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n int id = item.getItemId();\n if (id == R.id.mi_add_city) {\n showAddCityDialog();\n } else if (id == R.id.mi_city_management) {\n Intent cityManagementIntent = new Intent(this, CityManagementActivity.class);\n startActivityWithTransitionAnimation(cityManagementIntent);\n } else if (id == R.id.mi_settings) {\n Intent settingsIntent = new Intent(this, SettingsActivity.class);\n startActivityWithTransitionAnimation(settingsIntent);\n } else if (id == R.id.mi_rate_application) {\n goToPlayStore();\n } else if (id == R.id.mi_about) {\n Intent aboutIntent = new Intent(this, AboutActivity.class);\n startActivityWithTransitionAnimation(aboutIntent);\n }\n return super.onOptionsItemSelected(item);\n }\n\n /**\n * Displays a dialog allowing user to search new cities.\n */\n private void showAddCityDialog() {\n FragmentManager fragmentManager = getSupportFragmentManager();\n AddCityFragment addCityFragment = (AddCityFragment) fragmentManager\n .findFragmentByTag(ADD_CITY_FRAGMENT_TAG);\n if (addCityFragment == null) {\n addCityFragment = new AddCityFragment();\n addCityFragment.show(fragmentManager, ADD_CITY_FRAGMENT_TAG);\n }\n }\n\n /**\n * Attempts to visit the app's page in the Play Store via the Play Store app. If this fails\n * (the Play Store app not installed on the user's device), the second try is to do so via\n * the browser.\n */\n private void goToPlayStore() {\n final String appPackageName = getPackageName();\n try {\n startActivityWithTransitionAnimation(new Intent(Intent.ACTION_VIEW,\n Uri.parse(\"market://details?id=\" + appPackageName)));\n } catch (android.content.ActivityNotFoundException e) {\n startActivityWithTransitionAnimation(new Intent(Intent.ACTION_VIEW,\n Uri.parse(\"http://play.google.com/store/apps/details?id=\"\n + appPackageName)));\n }\n }\n\n @Override\n public void onSearchResponseForFindQueryRetrieved(\n SearchResponseForFindQuery searchResponseForFindQuery) {\n this.searchResponseForFindQuery = searchResponseForFindQuery;\n }\n\n @Override\n public void onFoundCityNamesItemClicked(int position) {\n AddCityFragment addCityFragment = (AddCityFragment) getSupportFragmentManager()\n .findFragmentByTag(ADD_CITY_FRAGMENT_TAG);\n if (addCityFragment != null) {\n addCityFragment.dismiss();\n }\n\n if (searchView != null) {\n searchView.onActionViewCollapsed();\n }\n\n if (searchResponseForFindQuery != null) {\n CityCurrentWeather selectedCityWeather = searchResponseForFindQuery\n .getCities().get(position);\n String currentWeatherJsonString = new Gson().toJson(selectedCityWeather);\n\n if (isDualPane) {\n displayRetrievedDataInThisActivity(currentWeatherJsonString,\n WeatherInfoType.CURRENT_WEATHER);\n }\n\n // Since the Open Weather Map search response for the 'find cities' query contains the\n // current weather information for each found city, we can cache this weather\n // information for the selected city in the database, just in case the user requests it\n // shortly (quite likely, given that s/he had just selected the city).\n insertNewRecordOrUpdateCity(selectedCityWeather.getCityId(),\n selectedCityWeather.getCityName(), currentWeatherJsonString);\n saveWeatherInfoRequest(selectedCityWeather.getCityId(),\n WeatherInfoType.CURRENT_WEATHER);\n }\n }\n\n /**\n * Updates the current weather record for the city if it already exists in the database,\n * otherwise inserts a new record.\n *\n * @param cityId Open Weather Map ID for the city\n * @param cityName the name as provided by the Open Weather Map\n * @param currentWeatherJsonString JSON current weather data\n */\n private void insertNewRecordOrUpdateCity(int cityId, String cityName,\n String currentWeatherJsonString) {\n Intent intent = new Intent(this, GeneralDatabaseService.class);\n intent.setAction(GeneralDatabaseService.ACTION_INSERT_OR_UPDATE_CITY_RECORD);\n intent.putExtra(CITY_ID, cityId);\n intent.putExtra(CITY_NAME, cityName);\n intent.putExtra(WEATHER_INFO_JSON_STRING, currentWeatherJsonString);\n startService(intent);\n }\n\n /**\n * Saves the requested city and weather information type in the SharedPreferences, so they can\n * be retrieved later and a new request formed automatically.\n *\n * @param cityId Open Weather Map ID for the requested city\n * @param weatherInfoType requested weather information type\n */\n private void saveWeatherInfoRequest(int cityId, WeatherInfoType weatherInfoType) {\n SharedPrefsHelper.putCityIdIntoSharedPrefs(this, cityId, false);\n SharedPrefsHelper.putLastWeatherInfoTypeIntoSharedPrefs(this, weatherInfoType);\n }\n\n @Override\n public void onCityWeatherInfoRequested(int cityId, WeatherInfoType weatherInfoType) {\n workerFragment.retrieveWeatherInfoJsonString(cityId, weatherInfoType);\n saveWeatherInfoRequest(cityId, weatherInfoType);\n }\n\n @Override\n public void displayRetrievedData(String jsonString, WeatherInfoType weatherInfoType) {\n if (isDualPane) {\n displayRetrievedDataInThisActivity(jsonString, weatherInfoType);\n } else {\n displayRetrievedDataInNewActivity(jsonString, weatherInfoType);\n }\n }\n\n /**\n * Creates and embeds a new fragment of the correct type to display the obtained weather data\n * in the second pane of this activity.\n *\n * @param jsonString JSON weather information data in textual form\n * @param weatherInfoType a type of the retrieved weather data\n */\n private void displayRetrievedDataInThisActivity(String jsonString,\n WeatherInfoType weatherInfoType) {\n Fragment fragment;\n if (weatherInfoType == WeatherInfoType.CURRENT_WEATHER) {\n fragment = WeatherInfoFragment.newInstance(weatherInfoType, null, jsonString);\n } else {\n fragment = WeatherForecastParentFragment.newInstance(weatherInfoType, jsonString);\n }\n getSupportFragmentManager().beginTransaction()\n .replace(R.id.weather_info_container, fragment).commit();\n }\n\n /**\n * Starts a new activity to display the obtained weather data.\n *\n * @param jsonString JSON weather information data in textual form\n * @param weatherInfoType a type of the retrieved weather data\n */\n private void displayRetrievedDataInNewActivity(String jsonString,\n WeatherInfoType weatherInfoType) {\n Intent intent = new Intent(this, WeatherInfoActivity.class);\n intent.putExtra(WEATHER_INFORMATION_TYPE, (Parcelable) weatherInfoType);\n intent.putExtra(WEATHER_INFO_JSON_STRING, jsonString);\n startActivityWithTransitionAnimation(intent);\n }\n\n private void startActivityWithTransitionAnimation(Intent intent) {\n startActivity(intent);\n overridePendingTransition(R.anim.abc_slide_in_bottom, R.anim.abc_slide_out_top);\n }\n\n}",
"public abstract class RefreshingActivity extends ThemedActivity implements\n WorkerFragmentToRetrieveJsonString.OnJsonStringRetrievedListener,\n WeatherInfoFragment.IconCacheRequestListener,\n WeatherThreeHourlyForecastChildListFragment.IconCacheRequestListener {\n\n public static final String WEATHER_INFORMATION_TYPE = \"weather info type\";\n public static final String WEATHER_INFO_JSON_STRING = \"json string\";\n\n protected WorkerFragmentToRetrieveJsonString workerFragment;\n /**\n * LruCache storing icons illustrating weather conditions. The key is the OWM icon code name:\n * https://openweathermap.org/weather-conditions\n */\n protected LruCache<String, Bitmap> iconCache;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setIconMemoryCache();\n }\n\n /**\n * Obtains or creates a new memory cache to store the weather icons.\n */\n private void setIconMemoryCache() {\n IconCacheRetainFragment retainFragment =\n IconCacheRetainFragment.findOrCreateRetainFragment(getSupportFragmentManager());\n iconCache = retainFragment.iconCache;\n if (iconCache == null) {\n // maximum available VM memory, stored in kilobytes\n int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);\n // we use 1/8th of the available memory for this memory cache\n int cacheSize = maxMemory / 8;\n\n iconCache = new LruCache<String, Bitmap>(cacheSize) {\n\n @Override\n protected int sizeOf(String key, Bitmap bitmap) {\n // the cache size will be measured in kilobytes rather than number of items\n return bitmap.getByteCount() / 1024;\n }\n };\n\n }\n retainFragment.iconCache = iconCache;\n }\n\n @Override\n public void onRecentJsonStringRetrieved(String jsonString, WeatherInfoType weatherInfoType,\n boolean shouldSaveLocally) {\n if (shouldSaveLocally) {\n saveRetrievedData(jsonString, weatherInfoType);\n }\n displayRetrievedData(jsonString, weatherInfoType);\n }\n\n /**\n * Saves the retrieved data in the database, so that it could be reused for a short period of\n * time.\n *\n * @param jsonString Weather information data in JSON format\n * @param weatherInfoType type of the retrieved weather data\n */\n protected void saveRetrievedData(String jsonString, WeatherInfoType weatherInfoType) {\n Intent intent = new Intent(this, GeneralDatabaseService.class);\n intent.setAction(GeneralDatabaseService.ACTION_UPDATE_WEATHER_INFO);\n intent.putExtra(WEATHER_INFO_JSON_STRING, jsonString);\n intent.putExtra(WEATHER_INFORMATION_TYPE, (Parcelable) weatherInfoType);\n startService(intent);\n }\n\n /**\n * @param jsonString weather information data in JSON format\n * @param weatherInfoType type of the retrieved weather data\n */\n protected abstract void displayRetrievedData(String jsonString, WeatherInfoType\n weatherInfoType);\n\n @Override\n public void onOldJsonStringRetrieved(final String jsonString,\n final WeatherInfoType weatherInfoType, long queryTime) {\n new AlertDialog.Builder(this)\n .setTitle(R.string.dialog_title_no_network_connection)\n .setIcon(R.drawable.ic_alert_error)\n .setMessage(getAlertDialogMessage(queryTime))\n .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {\n\n @Override\n public void onClick(DialogInterface dialog, int which) {\n dialog.dismiss();\n onRecentJsonStringRetrieved(jsonString, weatherInfoType, false);\n }\n })\n .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {\n\n @Override\n public void onClick(DialogInterface dialog, int which) {\n dialog.dismiss();\n }\n })\n .create()\n .show();\n }\n\n /**\n * Parses the message to be shown to user when there is no network access, but the old weather\n * data stored locally still can be displayed.\n *\n * @param queryTime the time when the old weather data were obtained\n * @return time in millis\n */\n @NonNull\n private String getAlertDialogMessage(long queryTime) {\n long weatherDataAge = System.currentTimeMillis() - queryTime;\n int hours = (int) (weatherDataAge / (3600 * 1000));\n int days = hours / 24;\n hours %= 24;\n if (days == 0 && hours == 0) {\n hours = 1;\n }\n\n Resources res = getResources();\n String daysPlural = res.getQuantityString(R.plurals.days, days);\n String hoursPlural = res.getQuantityString(R.plurals.hours, hours);\n\n if (days > 0 && hours > 0) {\n return String.format(res.getString(R.string.old_data_message_x_days_and_y_hours_ago),\n days, daysPlural, hours, hoursPlural);\n } else {\n int number = days > 0 ? days : hours;\n String plural = days > 0 ? daysPlural : hoursPlural;\n return String.format(res.getString(R.string.old_data_message_x_days_or_hours_ago),\n number, plural);\n }\n\n }\n\n @Override\n public LruCache<String, Bitmap> getIconMemoryCache() {\n return iconCache;\n }\n\n}",
"public class SharedPrefsHelper {\n\n public static final String SHARED_PREFS_KEY =\n \"com.haringeymobile.ukweather.PREFERENCE_FILE_KEY\";\n\n private static final String LAST_SELECTED_CITY_ID = \"city id\";\n private static final String LAST_SELECTED_WEATHER_INFO_TYPE = \"weather info type\";\n private static final String PERSONAL_API_KEY = \"personal api key\";\n\n /**\n * Obtains the ID of the city that was last queried by the user.\n */\n public static int getCityIdFromSharedPrefs(Context context) {\n return getSharedPreferences(context).getInt(LAST_SELECTED_CITY_ID,\n CityTable.CITY_ID_DOES_NOT_EXIST);\n }\n\n private static SharedPreferences getSharedPreferences(Context context) {\n return context.getSharedPreferences(SHARED_PREFS_KEY, Activity.MODE_PRIVATE);\n }\n\n /**\n * Saves the specified city ID.\n *\n * @param cityId OpenWeatherMap city ID\n * @param commit commit if true, apply if false\n */\n public static void putCityIdIntoSharedPrefs(Context context, int cityId, boolean commit) {\n SharedPreferences.Editor editor = getEditor(context).putInt(LAST_SELECTED_CITY_ID, cityId);\n if (commit) {\n editor.commit();\n } else {\n editor.apply();\n }\n }\n\n private static SharedPreferences.Editor getEditor(Context context) {\n return getSharedPreferences(context).edit();\n }\n\n /**\n * Obtains the {@link WeatherInfoType} for the last user's query.\n */\n public static WeatherInfoType getLastWeatherInfoTypeFromSharedPrefs(Context context) {\n int lastSelectedWeatherInfoTypeId = getSharedPreferences(context).getInt(\n LAST_SELECTED_WEATHER_INFO_TYPE, WeatherInfoType.CURRENT_WEATHER.getId());\n return WeatherInfoType.getTypeById(lastSelectedWeatherInfoTypeId);\n }\n\n /**\n * Saves the {@link WeatherInfoType} that was last queried by the user.\n *\n * @param weatherInfoType a kind of weather information\n */\n public static void putLastWeatherInfoTypeIntoSharedPrefs(Context context,\n WeatherInfoType weatherInfoType) {\n getEditor(context).putInt(LAST_SELECTED_WEATHER_INFO_TYPE, weatherInfoType.getId()).apply();\n }\n\n public static String getPersonalApiKeyFromSharedPrefs(Context context) {\n return getSharedPreferences(context).getString(PERSONAL_API_KEY, \"\");\n }\n\n /**\n * Saves users personal API key.\n *\n * @param key OWM developer key\n */\n public static void putPersonalApiKeyIntoSharedPrefs(Context context, String key) {\n getEditor(context).putString(PERSONAL_API_KEY, key).apply();\n }\n\n /**\n * Obtains the three-hourly forecast display mode from the shared preferences.\n *\n * @return weather forecast display mode preferred by the user, such as a list, or a horizontal\n * swipe view\n */\n public static ThreeHourlyForecastDisplayMode getForecastDisplayMode(Context context) {\n String forecastDisplayModeIdString = PreferenceManager.getDefaultSharedPreferences(context)\n .getString(SettingsActivity.PREF_FORECAST_DISPLAY_MODE, context.getResources()\n .getString(R.string.pref_forecast_display_mode_id_default));\n int forecastDisplayModeId = Integer.parseInt(forecastDisplayModeIdString);\n return ThreeHourlyForecastDisplayMode.getForecastDisplayModeById(forecastDisplayModeId);\n }\n\n /**\n * Determines if cities are deleted using button.\n */\n public static boolean isRemovalModeButton(Context context) {\n SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);\n Resources res = context.getResources();\n String cityRemovalModeIdString = preferences.getString(SettingsActivity.\n PREF_CITY_REMOVAL_MODE,\n res.getString(R.string.pref_city_removal_mode_id_default));\n return cityRemovalModeIdString.equals(res.getString(\n R.string.pref_city_removal_mode_button_id));\n }\n\n}",
"public enum WeatherInfoType implements Parcelable {\n\n /**\n * Current weather conditions.\n */\n CURRENT_WEATHER(1, CityCurrentWeather.class,\n R.string.weather_info_type_label_current_weather,\n R.drawable.ic_assignment_returned),\n\n /**\n * Daily weather forecast for up to 14 days.\n */\n DAILY_WEATHER_FORECAST(2, CityDailyWeatherForecast.class,\n R.string.weather_info_type_label_daily_forecast,\n R.drawable.ic_octicon_calendar),\n\n /**\n * Three hourly weather forecast for up to 5 days.\n */\n THREE_HOURLY_WEATHER_FORECAST(3, CityThreeHourlyWeatherForecast.class,\n R.string.weather_info_type_label_three_hourly_forecast,\n R.drawable.ic_assignment);\n\n /**\n * The number of days for the daily weather forecast. Currently this is the\n * maximum number allowed by the Open Weather Map.\n */\n private static final int DEFAULT_DAYS_COUNT_FOR_DAILY_FORECAST = 16;\n\n /**\n * An internal id for convenience.\n */\n private int id;\n /**\n * A class corresponding to this weather information type.\n */\n Class<? extends WeatherInformation> clazz;\n /**\n * A resource id for this weather information type's title to be presented\n * to users.\n */\n private int labelResourceId;\n /**\n * A resource id for this weather information type's icon to be presented to\n * users.\n */\n private int iconResourceId;\n\n WeatherInfoType(int id, Class<? extends WeatherInformation> clazz, int labelResourceId,\n int iconResourceId) {\n this.id = id;\n this.clazz = clazz;\n this.labelResourceId = labelResourceId;\n this.iconResourceId = iconResourceId;\n }\n\n /**\n * Obtains the weather information type corresponding to the provided ID.\n *\n * @param id a weather information type ID\n * @return a weather information type\n */\n public static WeatherInfoType getTypeById(int id) {\n switch (id) {\n case 1:\n return CURRENT_WEATHER;\n case 2:\n return DAILY_WEATHER_FORECAST;\n case 3:\n return THREE_HOURLY_WEATHER_FORECAST;\n default:\n throw new IllegalArgumentException(\"Unsupported id: \" + id);\n }\n }\n\n /**\n * @return an internal id for this weather information type\n */\n public int getId() {\n return id;\n }\n\n /**\n * @return a resource id for this weather information type's title to be\n * presented to users\n */\n public int getLabelResourceId() {\n return labelResourceId;\n }\n\n /**\n * @return a resource id for this weather information type's icon to be\n * presented to users.\n */\n public int getIconResourceId() {\n return iconResourceId;\n }\n\n /**\n * Obtains an Open Weather Map url for this weather info type.\n *\n * @param cityId an Open Weather Map city ID\n * @return a url containing the weather information for the specified city\n */\n public URL getOpenWeatherMapUrl(Context context, int cityId) {\n OpenWeatherMapUrl openWeatherMapUrl = new OpenWeatherMapUrl(context);\n switch (this) {\n case CURRENT_WEATHER:\n return openWeatherMapUrl.generateCurrentWeatherByCityIdUrl(cityId);\n case DAILY_WEATHER_FORECAST:\n return openWeatherMapUrl.generateDailyWeatherForecastUrl(cityId,\n DEFAULT_DAYS_COUNT_FOR_DAILY_FORECAST);\n case THREE_HOURLY_WEATHER_FORECAST:\n return openWeatherMapUrl\n .generateThreeHourlyWeatherForecastUrl(cityId);\n default:\n throw new IllegalWeatherInfoTypeArgumentException(this);\n }\n }\n\n public static final Creator<WeatherInfoType> CREATOR = new Creator<WeatherInfoType>() {\n\n @Override\n public WeatherInfoType createFromParcel(Parcel in) {\n WeatherInfoType weatherInfoType;\n try {\n weatherInfoType = valueOf(in.readString());\n } catch (IllegalArgumentException ex) {\n weatherInfoType = null;\n }\n return weatherInfoType;\n }\n\n @Override\n public WeatherInfoType[] newArray(int size) {\n return new WeatherInfoType[size];\n }\n };\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n dest.writeString(this == null ? \"\" : name());\n }\n\n /**\n * An IllegalArgumentException to be throwed in switch or if/else statements\n * when a certain weather information type is not expected as an argument.\n */\n public static class IllegalWeatherInfoTypeArgumentException extends\n IllegalArgumentException {\n\n /**\n * For serialisation.\n */\n private static final long serialVersionUID = -3666143975910277111L;\n\n public IllegalWeatherInfoTypeArgumentException(\n WeatherInfoType weatherInfoType) {\n super(\"Unsupported weatherInfoType: \" + weatherInfoType);\n }\n }\n\n}"
] | import android.app.IntentService;
import android.content.Intent;
import com.haringeymobile.ukweather.CityManagementActivity;
import com.haringeymobile.ukweather.MainActivity;
import com.haringeymobile.ukweather.RefreshingActivity;
import com.haringeymobile.ukweather.utils.SharedPrefsHelper;
import com.haringeymobile.ukweather.weather.WeatherInfoType; | package com.haringeymobile.ukweather.database;
public class GeneralDatabaseService extends IntentService {
private static final String APP_PACKAGE = "com.haringeymobile.ukweather";
public static final String ACTION_INSERT_OR_UPDATE_CITY_RECORD = APP_PACKAGE
+ ".insert_or_update_city_records";
public static final String ACTION_UPDATE_WEATHER_INFO = APP_PACKAGE
+ ".update_weather_info_records";
public static final String ACTION_RENAME_CITY = APP_PACKAGE + ".rename_city";
public static final String ACTION_DELETE_CITY_RECORDS = APP_PACKAGE + ".delete_city_records";
public static final String ACTION_DRAG_CITY = APP_PACKAGE + ".drag_city";
private static final String WORKER_THREAD_NAME = "General database service thread";
public GeneralDatabaseService() {
super(WORKER_THREAD_NAME);
}
@Override
protected void onHandleIntent(Intent intent) {
String action = intent.getAction();
switch (action) {
case ACTION_INSERT_OR_UPDATE_CITY_RECORD: {
int cityId = intent.getIntExtra(MainActivity.CITY_ID, CityTable.
CITY_ID_DOES_NOT_EXIST);
String cityName = intent.getStringExtra(MainActivity.CITY_NAME);
String currentWeatherJsonString = intent.getStringExtra(RefreshingActivity.
WEATHER_INFO_JSON_STRING);
new SqlOperation(this, WeatherInfoType.CURRENT_WEATHER).
updateOrInsertCityWithCurrentWeather(cityId, cityName,
currentWeatherJsonString);
break;
}
case ACTION_UPDATE_WEATHER_INFO: { | int cityId = SharedPrefsHelper.getCityIdFromSharedPrefs(this); | 3 |
quaap/LaunchTime | app/src/main/java/com/quaap/launchtime/db/DB.java | [
"public class AppLauncher implements Comparable<AppLauncher> {\n\n\n private static final Map<ComponentName,AppLauncher> mAppLaunchers = Collections.synchronizedMap(new HashMap<ComponentName,AppLauncher>());\n private static final String LINK_SEP = \":IS_APP_LINK:\";\n public static final String ACTION_PACKAGE = \"ACTION.PACKAGE\";\n private static final String OREOSHORTCUT = \"OREOSHORTCUT:\";\n public static final String OLDSHORTCUT = \"OLDSHORTCUT:\";\n private static final int THREAD_TIMEOUT = 5;\n\n\n public static AppLauncher createAppLauncher(String activityName, String packageName, String label, String category, boolean isWidget) {\n AppLauncher app = mAppLaunchers.get(new ComponentName(packageName, activityName));\n if (app == null) {\n app = new AppLauncher(activityName, packageName, label, category, isWidget);\n mAppLaunchers.put(app.getComponentName(), app);\n }\n return app;\n }\n\n public static AppLauncher createAppLauncher(Context context, PackageManager pm, ResolveInfo ri) {\n return createAppLauncher(context, pm, ri, null, true);\n }\n\n public static AppLauncher createAppLauncher(Context context, PackageManager pm, ResolveInfo ri, String category, boolean autocat) {\n String activityName = ri.activityInfo.name;\n AppLauncher app = mAppLaunchers.get(new ComponentName(ri.activityInfo.packageName, activityName));\n if (app == null) {\n app = new AppLauncher(context, pm, ri, category, autocat);\n mAppLaunchers.put(app.getComponentName(), app);\n }\n return app;\n }\n\n public static AppLauncher createAppLauncher(AppLauncher launcher) {\n return createAppLauncher(launcher, false);\n }\n\n public static AppLauncher createAppLauncher(AppLauncher launcher, boolean copyOrig) {\n return new AppLauncher(launcher, copyOrig);\n }\n\n\n// public static AppLauncher createActionLink(String activityName, Uri linkUri, String packageName, String label, String category) {\n// activityName = makeLink(activityName, linkUri);\n// AppLauncher app = mAppLaunchers.get(new ComponentName(packageName, activityName));\n// if (app == null) {\n// app = new AppLauncher(activityName, packageName, label, category, false);\n// mAppLaunchers.put(app.getComponentName(), app);\n// }\n// return app;\n// }\n//\n// public static AppLauncher createActionLink(String actionName, Uri linkUri, String label, String category) {\n//\n// actionName = makeLink(actionName, linkUri);\n// AppLauncher app = mAppLaunchers.get(new ComponentName(ACTION_PACKAGE, actionName));\n// if (app == null) {\n// app = new AppLauncher(actionName, ACTION_PACKAGE, label, category, false);\n// mAppLaunchers.put(app.getComponentName(), app);\n// }\n// return app;\n// }\n\n public static AppLauncher createActionShortcut(Intent launchintent, String label, String category) {\n launchintent.putExtra(\"_LT__LINK_\", Math.random()); //so we can have multiple shortcuts\n String actionName = makeLink(OLDSHORTCUT, launchintent.toUri(0));\n\n AppLauncher app = mAppLaunchers.get(new ComponentName(ACTION_PACKAGE, actionName));\n if (app == null) {\n app = new AppLauncher(actionName, ACTION_PACKAGE, label, category, false);\n mAppLaunchers.put(app.getComponentName(), app);\n }\n return app;\n }\n\n\n public static AppLauncher createShortcut(Intent launchintent, String packageName, String label, String category) {\n launchintent.putExtra(\"_LT__LINK_\", Math.random()); //so we can have multiple shortcuts\n String actionName = makeLink(OLDSHORTCUT, launchintent.toUri(0));\n\n AppLauncher app = mAppLaunchers.get(new ComponentName(packageName, actionName));\n if (app == null) {\n app = new AppLauncher(actionName, packageName, label, category, false);\n mAppLaunchers.put(app.getComponentName(), app);\n }\n return app;\n }\n\n\n public static AppLauncher createOreoShortcut(String shortcutid, String packageName, String label, String category) {\n\n String actionName = makeLink(OREOSHORTCUT, shortcutid);\n AppLauncher app = mAppLaunchers.get(new ComponentName(packageName, actionName));\n if (app == null) {\n app = new AppLauncher(actionName, packageName, label, category, false);\n mAppLaunchers.put(app.getComponentName(), app);\n }\n return app;\n }\n\n public static AppLauncher getAppLauncher(ComponentName activityName) {\n return mAppLaunchers.get(activityName);\n }\n\n public static void removeAppLauncher(ComponentName activityName) {\n mAppLaunchers.remove(activityName);\n }\n\n public static void removeAppLauncher(String activityName, String packageName) {\n try {\n if (activityName==null) activityName = \"\";\n mAppLaunchers.remove(new ComponentName(packageName, activityName));\n } catch (Exception e) {\n Log.e(\"AppLauncher\", e.getMessage(), e);\n }\n }\n\n public static void clearIcons() {\n for (AppLauncher app: mAppLaunchers.values()) {\n app.clearDrawable();\n }\n mAppLaunchers.clear();\n }\n\n\n private final String mPackageName;\n private final String mActivityName;\n private String mLabel;\n\n\n private String mCategory;\n private final boolean mWidget;\n\n private volatile Drawable mIconDrawable;\n final private List<ImageView> mIconImage = new ArrayList<>(1);\n\n private AppLauncher(String activityName, String packageName, String label, String category, boolean isWidget) {\n mActivityName = activityName;\n mPackageName = packageName;\n mLabel = label;\n mCategory = category;\n mWidget = isWidget;\n// if (mCategory==null) {\n// mCategory = Categories.getCategoryForPackage(mPackageName);\n// }\n }\n\n\n private AppLauncher(AppLauncher launcher, boolean copyOrig) {\n mActivityName = copyOrig ? launcher.getLinkBaseActivityName() : launcher.getActivityName();\n mPackageName = launcher.getPackageName();\n mLabel = launcher.getLabel();\n mCategory = launcher.getCategory();\n if (!copyOrig) {\n mIconDrawable = launcher.mIconDrawable;\n }\n mWidget = launcher.mWidget;\n\n }\n\n\n private AppLauncher(Context context, PackageManager pm, ResolveInfo ri, String category, boolean autocat) {\n mActivityName = ri.activityInfo.name;\n mPackageName = ri.activityInfo.packageName;\n mLabel = ri.loadLabel(pm).toString();\n if (category!=null) {\n mCategory = category;\n //Log.d(\"LaunchTime\", mPackageName + \", \" + ri.activityInfo.name + \", \" + mLabel + \" cat \" + category);\n } else if (autocat) {\n mCategory = Categories.getCategoryForComponent(context, mActivityName, mPackageName, true, ri.activityInfo.applicationInfo);\n if (mCategory==null) {\n mCategory = Categories.getCategoryFromPiCat(ri.activityInfo.applicationInfo);\n }\n\n //Log.d(\"LaunchTime\", mPackageName + \", \" + ri.activityInfo.name + \", \" + mLabel + \" auto \" + category);\n } else {\n mCategory = Categories.CAT_OTHER;\n //Log.d(\"LaunchTime\", mPackageName + \", \" + ri.activityInfo.name + \", \" + mLabel + \" plain \" + category);\n }\n mWidget = false;\n\n\n\n loadAppIconAsync(context);\n }\n\n\n private static String makeLink(String activityName, Uri uri) {\n String uristr = \"\";\n if (uri != null) uristr = uri.toString();\n return makeLink(activityName, uristr);\n }\n\n private static String makeLink(String activityName, String uri) {\n if (!activityName.contains(LINK_SEP)) {\n return activityName + LINK_SEP + uri;\n }\n Log.e(\"Link\", \"Activity is already a link\"+ activityName, new Throwable(\"Activity is already a link\"+ activityName));\n return activityName;\n }\n\n private static final String linkuri = \"_link\";\n\n public AppLauncher makeAppLink() {\n //return AppLauncher.createActionLink(getLinkBaseActivityName(), new Uri.Builder().scheme(linkuri).path(linkuri + Math.random()).build(), getPackageName(), getLabel(), getCategory());\n Intent intent = new Intent(Intent.ACTION_MAIN);\n intent.setClassName(getPackageName(), getLinkBaseActivityName());\n intent.setPackage(getPackageName());\n\n return AppLauncher.createShortcut(intent, intent.getPackage(), getLabel(), null);\n }\n\n public boolean isAppLink() {\n String uristr = getLinkUri();\n return uristr!=null && uristr.startsWith(linkuri);\n }\n\n public ComponentName getComponentName() {\n return new ComponentName(mPackageName, mActivityName);\n }\n\n public ComponentName getBaseComponentName() {\n return new ComponentName(mPackageName, getLinkBaseActivityName());\n }\n\n public boolean isLink() {\n return mActivityName.contains(LINK_SEP);\n }\n\n public String getLinkBaseActivityName() {\n return mActivityName.split(LINK_SEP,2)[0];\n }\n\n public String getLinkUri() {\n String [] parts = mActivityName.split(LINK_SEP,2);\n if (parts.length==2) {\n return parts[1];\n }\n return null;\n }\n\n public boolean isOreoShortcut() {\n return mActivityName.contains(OREOSHORTCUT);\n }\n public boolean isShortcut() {\n return mActivityName.contains(OLDSHORTCUT);\n }\n\n public String getLabel() {\n return mLabel;\n }\n\n public void setLabel(String label) {\n mLabel = label;\n }\n\n public String getPackageName() {\n return mPackageName;\n }\n\n public String getActivityName() {\n return mActivityName;\n }\n\n public String getCategory() {\n return mCategory;\n }\n\n public void setCategory(String category) {\n mCategory = category;\n }\n\n public boolean isWidget() {\n return mWidget;\n }\n\n public boolean isActionLink() {\n return mPackageName.equals(ACTION_PACKAGE);\n }\n\n public boolean isNormalApp() {\n return !(isWidget() || isLink() || isActionLink() || isAppLink() || isShortcut() || isOreoShortcut());\n }\n\n public boolean iconLoaded() {\n return mIconDrawable != null;\n }\n\n public void addIconImage(ImageView iconImage) {\n mIconImage.add(iconImage);\n if (mIconDrawable != null) {\n //Log.d(\"icon1\", mLabel + \" \" + mIconDrawable+\"\");\n iconImage.setImageDrawable(mIconDrawable);\n }\n }\n\n public void clearImageViews() {\n mIconImage.clear();\n }\n\n public Drawable getIconDrawable() {\n return mIconDrawable;\n }\n\n public void setIconDrawable(Drawable drawable) {\n mIconDrawable = drawable;\n if (mIconImage.size()>0) {\n //Log.d(\"icon2\", mLabel + \" \" + mIconDrawable+\"\");\n for (ImageView im: mIconImage) {\n im.setImageDrawable(mIconDrawable);\n }\n }\n }\n\n public void clearDrawable() {\n mIconDrawable = null;\n mIconImage.clear();\n }\n\n @Override\n public boolean equals(Object obj) {\n if (obj instanceof AppLauncher) {\n return getComponentName().equals(((AppLauncher) obj).getComponentName());\n }\n return super.equals(obj);\n }\n\n @Override\n public int hashCode() {\n return getComponentName().hashCode();\n }\n\n @Override\n public int compareTo(@NonNull AppLauncher appLauncher) {\n return this.mLabel.toLowerCase(Locale.getDefault()).compareTo(appLauncher.mLabel.toLowerCase(Locale.getDefault()));\n }\n\n public void loadAppIcon(Context context, Handler handler) {\n if (iconLoaded()) return;\n Drawable app_icon = null;\n try {\n\n String uristr = null;\n if (isActionLink()) {\n uristr = getLinkUri();\n if (uristr == null) uristr = \"\";\n }\n\n app_icon = GlobState.getIconsHandler(context).getDrawableIconForPackage(this);\n\n if (app_icon == null) {\n app_icon = context.getPackageManager().getDefaultActivityIcon();\n }\n if (isLink()) {\n app_icon = IconsHandler.drawLinkSymbol(app_icon, context);\n }\n\n\n } catch (Exception | Error e) {\n Log.d(\"loadIcon\", e.getMessage(), e);\n }\n\n if (app_icon == null) {\n app_icon = context.getPackageManager().getDefaultActivityIcon();\n }\n\n final Drawable app_iconf = app_icon;\n\n if (handler!=null) {\n handler.post(new Runnable() {\n @Override\n public void run() {\n setIconDrawable(app_iconf);\n }\n });\n } else {\n setIconDrawable(app_iconf);\n }\n }\n\n\n private static final BlockingQueue<AppLauncher> iconQueue = new LinkedBlockingQueue<>();\n private static final Object iconLoaderSync = new Object();\n private static IconLoaderTask iconLoader;\n private static Handler handler;\n\n public void loadAppIconAsync(final Context context) {\n if (iconLoaded() || isWidget()) return;\n\n queueIconLoad(this);\n\n synchronized (iconLoaderSync) {\n if (iconLoader==null || !iconLoader.isrunning) {\n if (handler==null) handler = new Handler(Looper.getMainLooper());\n iconLoader = new IconLoaderTask(context, handler);\n try {\n //AsyncTask.THREAD_POOL_EXECUTOR.execute(iconLoader);\n GlobState.execute(context, iconLoader);\n } catch (Throwable t) {\n Log.e(\"loadAppIconAsync\", t.getMessage(), t);\n if (!iconLoader.isrunning) {\n new Thread(iconLoader).start();\n }\n\n }\n }\n }\n\n }\n\n private void queueIconLoad(AppLauncher app) {\n iconQueue.offer(app);\n }\n\n\n //We do this because we know we will process many icon loading tasks in a row (ie at startup), and\n // there's no need to restart a thread or even a runnable for each one.\n // This way we just get a thread and keep it until we're done\n private static class IconLoaderTask implements Runnable {\n\n volatile boolean isrunning = true;\n private final WeakReference<Context> mContextRef;\n private final WeakReference<Handler> mHandlerRef;\n\n private int processed=0;\n\n\n IconLoaderTask(Context context, Handler handler) {\n mContextRef = new WeakReference<>(context);\n mHandlerRef = new WeakReference<>(handler);\n }\n\n @Override\n public void run() {\n Log.d(\"IconLoaderTask\", \"Starting IconLoad task\");\n\n try {\n do {\n Context context = mContextRef.get();\n Handler handler = mHandlerRef.get();\n if (context == null || handler == null) {\n Log.d(\"IconLoaderTask\", context + \" \" + handler);\n return;\n }\n try {\n final AppLauncher inst = iconQueue.poll(THREAD_TIMEOUT, TimeUnit.SECONDS);\n if (inst == null) {\n isrunning = false;\n } else {\n inst.loadAppIcon(context, handler);\n processed++;\n }\n\n\n } catch (InterruptedException e) {\n Log.d(\"loadAppIconAsync\", e.getMessage(), e);\n isrunning = false;\n }\n } while (isrunning);\n\n } finally {\n synchronized (iconLoaderSync) {\n iconLoader = null;\n handler = null;\n isrunning = false;\n }\n Log.d(\"IconLoaderTask\", \"Completing IconLoad task. Processed \" + processed);\n\n }\n }\n\n }\n\n\n}",
"public class Categories {\n\n private static Resources resources;\n\n //Don't change these values here. Change their displays in strings.xml\n public static final String CAT_SEARCH = \"Search\";\n public static final String CAT_TALK = \"Communicate\";\n private static final String CAT_GAMES = \"Games\";\n private static final String CAT_INTERNET = \"Internet\";\n private static final String CAT_MEDIA = \"Media\";\n private static final String CAT_GRAPHICS = \"Graphics\";\n private static final String CAT_Utilities = \"Utilities\";\n public static final String CAT_OTHER = \"Other\";\n private static final String CAT_SETTINGS = \"Settings\";\n public static final String CAT_HIDDEN = \"Hidden\";\n public static final String CAT_DUMB = \"Dumb__\";\n\n //public static final String[] CAT_TINY = {CAT_OTHER, CAT_SETTINGS, CAT_HIDDEN};\n private static final String[] CAT_TINY = {CAT_HIDDEN, CAT_DUMB};\n private static final String[] CAT_HIDDENS = {CAT_HIDDEN};\n private static final String[] CAT_SPECIALS = {CAT_OTHER, CAT_TALK, CAT_HIDDEN, CAT_SEARCH};\n private static final String[] CAT_NODROP = {CAT_SEARCH};\n\n public static final String[] DefCategoryOrder = {\n CAT_TALK,\n CAT_GAMES,\n CAT_INTERNET,\n CAT_MEDIA,\n CAT_GRAPHICS,\n CAT_Utilities,\n CAT_SETTINGS,\n CAT_OTHER,\n CAT_SEARCH,\n CAT_HIDDEN\n };\n\n private static Map<String, String[]> mCategorKeywords;\n\n public static void init(Context context) {\n resources = context.getResources();\n\n mCategorKeywords = getCategoryKeywords();\n }\n\n public static String unabbreviate(String abbr) {\n if (abbr==null) return null;\n for (String cat: DefCategoryOrder) {\n if (cat.startsWith(abbr)) {\n return cat;\n }\n }\n return null;\n }\n\n public static String getCategoryForAction(Context context, String action) {\n String category = null;\n if (action.contains(\"CALL\") || action.contains(\"SEND\")\n || action.contains(\"DIAL\") || action.contains(\"CONTACT\")\n || action.contains(\"MAIL\") || action.contains(\"MESSAG\")) {\n category = CAT_TALK;\n } else if (action.contains(\"MUSIC\")) {\n category = CAT_MEDIA;\n } else if (action.contains(\"WEB\")) {\n category = CAT_INTERNET;\n }\n\n return checkCat(context, category);\n }\n\n public static String getCategoryForUri(Context context, String uri) {\n String category = null;\n if (uri.contains(\"sms\") || uri.contains(\"call\") || uri.contains(\"tel:\") || uri.contains(\"contact\")) {\n category = CAT_TALK;\n } else if (uri.contains(\"aud\") || uri.contains(\"snd\")) {\n category = CAT_MEDIA;\n } else if (uri.contains(\"http\")) {\n category = CAT_INTERNET;\n }\n\n return checkCat(context, category);\n }\n\n\n public static String getCategoryForPackage(Context context, String pkgname, boolean guess) {\n DB db = GlobState.getGlobState(context).getDB();\n\n String category = db.getCategoryForPackage(pkgname);\n if (guess && (category == null || category.equals(CAT_OTHER))) {\n category = guessCategoryForPackage(context,pkgname);\n }\n return checkCat(context, category);\n }\n\n private static String getCategoryForActivity(Context context, String actvname, boolean guess) {\n DB db = GlobState.getGlobState(context).getDB();\n\n String category = db.getCategoryForActivity(actvname);\n if (guess && (category == null || category.equals(CAT_OTHER))) {\n category = guessCategoryForPackage(context,actvname);\n }\n return checkCat(context, category);\n }\n\n public static String getCategoryForComponent(Context context, ComponentName activity, boolean guess, ApplicationInfo ai) {\n return getCategoryForComponent(context, activity.getClassName(), activity.getPackageName(), guess, ai);\n }\n\n public static String getCategoryForComponent(Context context, String actvname, String pkgname, boolean guess, ApplicationInfo ai) {\n\n String catact = getCategoryForActivity(context, actvname, false);\n String catpack = getCategoryForPackage(context, pkgname, false);\n\n String category = catact;\n if (category==null || category.equals(CAT_OTHER)) category = catpack;\n\n if (category==null || category.equals(CAT_OTHER)) {\n category = getCategoryFromPiCat(ai);\n }\n\n if (guess && (category == null || category.equals(CAT_OTHER))) {\n category = guessCategoryForPackage(context,pkgname);\n }\n\n\n return checkCat(context, category);\n\n }\n// CAT_TALK,\n// CAT_GAMES,\n// CAT_INTERNET,\n// CAT_MEDIA,\n// CAT_GRAPHICS,\n// CAT_Utilities,\n// CAT_SETTINGS,\n// CAT_OTHER,\n// CAT_HIDDEN,\n// CAT_SEARCH\n\n public static String getCategoryFromPiCat(ApplicationInfo appinfo) {\n if (appinfo==null) return null;\n String cat = null;\n if (Build.VERSION.SDK_INT >= 26) {\n int category = appinfo.category;\n switch (category) {\n\n case ApplicationInfo.CATEGORY_AUDIO:\n cat = CAT_MEDIA;\n break;\n\n case ApplicationInfo.CATEGORY_GAME:\n cat = CAT_GAMES;\n break;\n\n case ApplicationInfo.CATEGORY_IMAGE:\n cat = CAT_GRAPHICS;\n break;\n\n case ApplicationInfo.CATEGORY_MAPS:\n cat = CAT_INTERNET;\n break;\n\n case ApplicationInfo.CATEGORY_NEWS:\n cat = CAT_INTERNET;\n break;\n\n case ApplicationInfo.CATEGORY_PRODUCTIVITY:\n cat = CAT_Utilities;\n break;\n\n case ApplicationInfo.CATEGORY_SOCIAL:\n cat = CAT_TALK;\n break;\n\n case ApplicationInfo.CATEGORY_VIDEO:\n cat = CAT_GRAPHICS;\n break;\n\n case ApplicationInfo.CATEGORY_UNDEFINED:\n default:\n cat = null;\n break;\n\n }\n } else if ((appinfo.flags & ApplicationInfo.FLAG_IS_GAME) == ApplicationInfo.FLAG_IS_GAME) {\n cat = CAT_GAMES;\n }\n return cat;\n }\n\n\n private static String guessCategoryForPackage(Context context, String pkgname) {\n String category = null;\n OUTER:\n for (String cat : mCategorKeywords.keySet()) {\n for (String pkg : mCategorKeywords.get(cat)) {\n if (pkgname.contains(pkg)) {\n category = cat;\n break OUTER;\n }\n }\n }\n\n return checkCat(context, category);\n }\n\n\n\n private static String checkCat(Context context, String category) {\n if (category == null) {\n category = CAT_OTHER;\n } else if (!isSpeacialCategory(category)){\n DB db = GlobState.getGlobState(context).getDB();\n String dbcat = db.getCategoryDisplay(category);\n if (dbcat == null) {\n category = Categories.CAT_OTHER; //the user deleted the category\n }\n }\n\n return category;\n }\n\n public static boolean isTinyCategory(String category) {\n //none are tiny by default\n //return false;\n return Arrays.asList(Categories.CAT_TINY).contains(category);\n }\n\n public static boolean isHiddenCategory(String category) {\n return Arrays.asList(Categories.CAT_HIDDENS).contains(category);\n }\n\n public static boolean isSpeacialCategory(String category) {\n return Arrays.asList(Categories.CAT_SPECIALS).contains(category);\n }\n\n public static boolean isNoDropCategory(String category) {\n return Arrays.asList(Categories.CAT_NODROP).contains(category);\n }\n\n public static String getCatLabel(Context context, String category) {\n Map<String, Integer> catmap = new HashMap<>();\n catmap.put(CAT_SEARCH, R.string.category_Search);\n catmap.put(CAT_TALK, R.string.category_Talk);\n catmap.put(CAT_GAMES, R.string.category_Games);\n catmap.put(CAT_INTERNET, R.string.category_Internet);\n catmap.put(CAT_MEDIA, R.string.category_Media);\n catmap.put(CAT_GRAPHICS, R.string.category_Graphics);\n catmap.put(CAT_Utilities, R.string.category_Utilities);\n catmap.put(CAT_OTHER, R.string.category_Other);\n catmap.put(CAT_SETTINGS, R.string.category_Settings);\n catmap.put(CAT_HIDDEN, R.string.category_Hidden);\n catmap.put(CAT_DUMB, R.string.category_Dumb);\n return context.getString(catmap.get(category));\n }\n\n public static String getCatFullLabel(Context context, String category) {\n Map<String, Integer> catmap = new HashMap<>();\n catmap.put(CAT_SEARCH, R.string.category_Search_full);\n catmap.put(CAT_TALK, R.string.category_Talk_full);\n catmap.put(CAT_GAMES, R.string.category_Games_full);\n catmap.put(CAT_INTERNET, R.string.category_Internet_full);\n catmap.put(CAT_MEDIA, R.string.category_Media_full);\n catmap.put(CAT_GRAPHICS, R.string.category_Graphics_full);\n catmap.put(CAT_Utilities, R.string.category_Utilities_full);\n catmap.put(CAT_OTHER, R.string.category_Other_full);\n catmap.put(CAT_SETTINGS, R.string.category_Settings_full);\n catmap.put(CAT_HIDDEN, R.string.category_Hidden_full);\n catmap.put(CAT_DUMB, R.string.category_Dumb_full);\n return context.getString(catmap.get(category));\n }\n\n private static Map<String, String[]> getCategoryKeywords() {\n Map<String, String[]> keywordsDict = new LinkedHashMap<>();\n \n keywordsDict.put(CAT_TALK, resources.getStringArray(R.array.CAT_TALK));\n keywordsDict.put(CAT_GAMES, resources.getStringArray(R.array.CAT_GAMES));\n keywordsDict.put(CAT_INTERNET, resources.getStringArray(R.array.CAT_INTERNET));\n keywordsDict.put(CAT_MEDIA, resources.getStringArray(R.array.CAT_MEDIA));\n keywordsDict.put(CAT_GRAPHICS, resources.getStringArray(R.array.CAT_GRAPHICS));\n keywordsDict.put(CAT_Utilities, resources.getStringArray(R.array.CAT_ACCESSORIES));\n keywordsDict.put(CAT_SETTINGS, resources.getStringArray(R.array.CAT_SETTINGS));\n\n\n return keywordsDict;\n }\n\n\n}",
"public class FsTools {\n\n private final Context mContext;\n\n public FsTools(Context context) {\n mContext = context;\n }\n\n private String [] listDirsInDir(File extdir, final String matchRE, final boolean onlyDirs) {\n\n FilenameFilter filterdirs = new FilenameFilter() {\n\n @Override\n public boolean accept(File dir, String filename) {\n File sel = new File(dir, filename);\n return sel.isDirectory();\n }\n\n };\n\n List<String> dirs = new ArrayList<>(Arrays.asList(extdir.list(filterdirs)));\n\n if (extdir.getParent()!=null && !extdir.equals(Environment.getExternalStorageDirectory())) {\n dirs.add(0, \"..\");\n }\n\n Collections.sort(dirs, new Comparator<String>() {\n @Override\n public int compare(String s, String t1) {\n return s.compareToIgnoreCase(t1);\n }\n });\n\n if (!onlyDirs) {\n FilenameFilter filterfiles = new FilenameFilter() {\n\n @Override\n public boolean accept(File dir, String filename) {\n File sel = new File(dir, filename);\n return sel.isFile() && (matchRE == null || filename.matches(matchRE));\n }\n\n };\n\n List<String> files = new ArrayList<>(Arrays.asList(extdir.list(filterfiles)));\n\n Collections.sort(files, new Comparator<String>() {\n @Override\n public int compare(String s, String t1) {\n return s.compareToIgnoreCase(t1);\n }\n });\n\n dirs.addAll(files);\n }\n\n String [] fileslist = dirs.toArray(new String[0]);\n for (int i=0; i<fileslist.length; i++) {\n File sel = new File(extdir, fileslist[i]);\n if (sel.isDirectory()) fileslist[i] = fileslist[i] + \"/\";\n //Log.d(\"DD\", fileslist[i]);\n }\n return fileslist;\n\n }\n\n public void selectExternalLocation(final SelectionMadeListener listener, String title, boolean chooseDir) {\n selectExternalLocation(listener, title, null, chooseDir, null);\n }\n\n public void selectExternalLocation(final SelectionMadeListener listener, String title, boolean chooseDir, String matchRE) {\n selectExternalLocation(listener, title, null, chooseDir, matchRE);\n }\n\n\n private void selectExternalLocation(final SelectionMadeListener listener, final String title, String startdir, final boolean chooseDir, final String matchRE) {\n final File currentDir = startdir==null ? Environment.getExternalStorageDirectory() : new File(startdir);\n\n final String [] items = listDirsInDir(currentDir, matchRE, chooseDir);\n\n AlertDialog.Builder builder = new AlertDialog.Builder(mContext);\n\n builder.setTitle(title + \"\\n\" +\n currentDir.getPath().replaceFirst(Pattern.quote(Environment.getExternalStorageDirectory().getPath()) + \"/?\", \"/\"));\n\n builder.setItems(items, new DialogInterface.OnClickListener() {\n @Override\n public void onClick(DialogInterface dialogInterface, int i) {\n dialogInterface.dismiss();\n\n try {\n File selFile = new File(currentDir,items[i]).getCanonicalFile();\n if (selFile.isDirectory()) {\n selectExternalLocation(listener, title, selFile.getPath(), chooseDir, matchRE);\n } else {\n listener.selected(selFile);\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n }\n });\n if (chooseDir) {\n builder.setPositiveButton(\"Select current\", new DialogInterface.OnClickListener() {\n @Override\n public void onClick(DialogInterface dialogInterface, int i) {\n\n listener.selected(currentDir);\n }\n });\n }\n builder.setNegativeButton(R.string.cancel, null);\n\n builder.show();\n }\n\n\n public interface SelectionMadeListener {\n void selected(File selection);\n }\n\n public static File copyFileToDir(File srcFile, File destDir){\n if (!destDir.isDirectory()) throw new IllegalArgumentException(\"Destination must be a directory\");\n\n return copyFile(srcFile, new File(destDir,srcFile.getName()));\n }\n\n public static File copyFile(File srcFile, File destFile) {\n return copyFile(srcFile, destFile, false, false);\n }\n\n public static File compressFile(File srcFile, File destFile) {\n return copyFile(srcFile, destFile, true, false);\n }\n\n\n public static File decompressFile(File srcFile, File destFile) {\n return copyFile(srcFile, destFile, false, true);\n }\n\n\n\n private static File copyFile(File srcFile, File destFile, boolean compress, boolean decompress){\n if (destFile.exists() && !destFile.isFile()) throw new IllegalArgumentException(\"Destination must be a normal file\");\n try {\n\n InputStream fis = new FileInputStream(srcFile);\n\n try {\n if (decompress) {\n fis = new GZIPInputStream(fis);\n }\n\n OutputStream output = new FileOutputStream(destFile);\n\n try {\n if (compress) {\n output = new GZIPOutputStream(output);\n }\n\n // Transfer bytes from the inputfile to the outputfile\n byte[] buffer = new byte[1024];\n int length;\n while ((length = fis.read(buffer)) > 0) {\n output.write(buffer, 0, length);\n }\n\n output.flush();\n return destFile;\n } finally {\n try {output.close();} catch (Exception e) {Log.e(\"Fs\",e.getMessage(),e);}\n }\n } finally {\n try {fis.close();} catch (Exception e) {Log.e(\"Fs\",e.getMessage(),e);}\n }\n\n } catch (IOException e) {\n Log.e(\"DB\", \"Copy failed\", e);\n }\n return null;\n }\n\n\n public static File compressFiles(File destFile, File ... files) {\n\n if (files.length<1) throw new IllegalArgumentException(\"Need at least one source file and exactly one destination file.\");\n if (destFile.exists() && !destFile.isFile()) throw new IllegalArgumentException(\"Destination must be a normal file\");\n\n try {\n ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(destFile));\n try {\n\n for (File file : files) {\n InputStream fis = new FileInputStream(file);\n try {\n\n zout.putNextEntry(new ZipEntry(file.getName()));\n\n byte[] buffer = new byte[1024];\n int length;\n while ((length = fis.read(buffer)) > 0) {\n zout.write(buffer, 0, length);\n }\n\n\n zout.closeEntry();\n\n } finally {\n try {\n fis.close();\n } catch (Exception e) {\n Log.e(\"Fs\", e.getMessage(), e);\n }\n }\n\n }\n } finally {\n try {zout.close();} catch (Exception e) {Log.e(\"Fs\",e.getMessage(),e);}\n }\n\n\n } catch (IOException e) {\n Log.e(\"DB\", \"Copy failed\", e);\n }\n return destFile;\n }\n\n\n public static List<File> uncompressFiles(File srcFile, File destDir) {\n\n List<File> files = new ArrayList<>();\n\n\n try {\n ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(srcFile));\n try {\n ZipEntry zipEntry;\n while ((zipEntry = zipInputStream.getNextEntry()) !=null) {\n File destFile = new File(destDir, zipEntry.getName());\n\n if (!destFile.getParentFile().exists()) {\n if (!destFile.getParentFile().mkdirs()) continue;\n }\n if (zipEntry.isDirectory()) {\n continue;\n }\n\n files.add(destFile);\n\n OutputStream zout = new FileOutputStream(destFile);\n try {\n\n byte[] buffer = new byte[1024];\n int length;\n while ((length = zipInputStream.read(buffer)) > 0) {\n zout.write(buffer, 0, length);\n }\n\n } finally {\n try {zout.close();} catch (Exception e) {Log.e(\"Fs\",e.getMessage(),e);}\n }\n\n }\n } finally {\n try {zipInputStream.close();} catch (Exception e) {Log.e(\"Fs\",e.getMessage(),e);}\n }\n\n\n } catch (IOException e) {\n Log.e(\"DB\", \"Copy failed\", e);\n }\n return files;\n }\n\n//\n// public static File storeSharedPreferences(SharedPreferences prefs, String fname) throws IOException {\n// File outfile = new File(fname);\n// Properties props = new Properties();\n// props.putAll(prefs.getAll());\n// BufferedWriter out = new BufferedWriter(new FileWriter(outfile));\n// try {\n// props.store(out,fname);\n// } finally {\n// out.close();\n// }\n// return outfile;\n//\n// }\n//\n// public static void loadSharedPreferences(SharedPreferences prefs, File prefsFile) throws IOException {\n// Properties props = new Properties();\n// FileReader in = new FileReader(prefsFile);\n// try {\n// props.load(in);\n// } finally {\n// in.close();\n// }\n//\n// SharedPreferences.Editor editor = prefs.edit();\n// try {\n// for (Map.Entry<?, ?> ent : props.entrySet()) {\n// // props.\n// }\n// } finally {\n// editor.apply();\n// }\n// }\n\n public static File saveSharedPreferencesToFile(SharedPreferences pref, File destFile) {\n\n ObjectOutputStream output = null;\n try {\n output = new ObjectOutputStream(new FileOutputStream(destFile));\n\n output.writeObject(pref.getAll());\n\n } catch (IOException e) {\n Log.e(\"FsTools\", e.getMessage(), e);\n } finally {\n try {\n if (output != null) {\n output.flush();\n output.close();\n }\n } catch (IOException e) {\n Log.e(\"FsTools\", e.getMessage(), e);\n }\n }\n return destFile;\n }\n\n\n @SuppressWarnings({\"unchecked\"})\n public static void loadSharedPreferencesFromFile(SharedPreferences pref, File src) {\n\n ObjectInputStream input = null;\n try {\n input = new ObjectInputStream(new FileInputStream(src));\n SharedPreferences.Editor prefEdit = pref.edit();\n prefEdit.clear();\n\n Map<String, ?> entries = (Map<String, ?>) input.readObject();\n for (Map.Entry<String, ?> entry : entries.entrySet()) {\n Object v = entry.getValue();\n String key = entry.getKey();\n\n if (v instanceof Boolean) {\n prefEdit.putBoolean(key, (Boolean) v);\n } else if (v instanceof Float) {\n prefEdit.putFloat(key, (Float) v);\n } else if (v instanceof Integer) {\n prefEdit.putInt(key, (Integer) v);\n } else if (v instanceof Long) {\n prefEdit.putLong(key, (Long) v);\n } else if (v instanceof String) {\n prefEdit.putString(key, ((String) v));\n } else if (v instanceof Set) {\n prefEdit.putStringSet(key, ((Set<String>) v));\n } else {\n Log.d(\"FsTools\", \"unknown type for '\" + key + \"': \" + v.getClass());\n }\n\n }\n if (prefEdit.commit()) {\n Log.d(\"FsTools\", \"prefs updated\");\n }\n\n } catch (IOException | ClassNotFoundException e) {\n Log.e(\"FsTools\", e.getMessage(), e);\n } finally {\n try {\n if (input != null) {\n input.close();\n }\n } catch (IOException e) {\n Log.e(\"FsTools\", e.getMessage(), e);\n }\n }\n }\n\n}",
"public class SpecialIconStore {\n\n\n\n public static void deleteBitmap(Context context, ComponentName cname, IconType iconType) {\n\n String fname = makeSafeName(cname, iconType);\n if (fileExists(context, fname)) {\n context.deleteFile(fname);\n }\n\n }\n\n public static void saveBitmap(Context context, ComponentName cname, Bitmap bitmap, IconType iconType) {\n\n try {\n String fname = makeSafeName(cname, iconType);\n FileOutputStream fos = context.openFileOutput(fname, Context.MODE_PRIVATE);\n bitmap.compress(Bitmap.CompressFormat.PNG,100,fos);\n fos.close();\n Log.d(\"SpecialIconStore\", \"Saved icon \" + fname);\n } catch (IOException e) {\n Log.e(\"SpecialIconStore\", e.getMessage(), e);\n }\n }\n\n public static boolean hasBitmap(Context context, ComponentName cname, IconType iconType) {\n\n return fileExists(context, makeSafeName(cname, iconType));\n }\n\n public static Bitmap loadBitmap(Context context, ComponentName cname, IconType iconType) {\n\n Bitmap bitmap;// = null;\n\n// for (String fn: context.fileList()) {\n// Log.d(\"SpecialIconStore\", \" I see file \" + fn);\n// }\n bitmap = loadBitmap(context,makeSafeName(cname, iconType));\n if (bitmap == null) {\n bitmap = loadBitmap(context, makeSafeName(cname, null));\n }\n if (bitmap == null) {\n bitmap = loadBitmap(context, makeSafeName(cname.getClassName()) + \".png\");\n }\n\n// if (bitmap != null) {\n// Log.d(\"SpecialIconStore\", \"found icon for \" + cname.toString());\n// }\n return bitmap;\n }\n\n\n public static List<File> getAllIcons(Context context) {\n List<File> files = new ArrayList<>();\n for (String fn: context.fileList()) {\n if (fn.endsWith(\".png\")) {\n Log.d(\"SpecialIconStore\", \" I see file \" + fn);\n files.add(new File(context.getFilesDir(), fn));\n }\n }\n return files;\n }\n\n private static String makeSafeName(ComponentName cname, IconType iconType) {\n String name = cname.getPackageName() + \":\" + cname.getClassName();\n\n String fname = makeSafeName(name);\n if (iconType!=null) fname += \".\" + iconType.name();\n\n fname += \".png\";\n\n return fname;\n }\n\n\n private static String makeSafeName(String name) {\n\n try {\n byte[] inbytes = name.getBytes(\"UTF-8\");\n\n MessageDigest md = MessageDigest.getInstance(\"SHA-256\");\n byte[] shabytes = md.digest(inbytes);\n\n StringBuilder hexString = new StringBuilder();\n for (int i=0;i<shabytes.length;i++) {\n String hex=Integer.toHexString(0xff & shabytes[i]);\n if(hex.length()==1) hexString.append('0');\n hexString.append(hex);\n }\n\n //Log.d(\"Icon\", \"name \" + name + \" => \" + hexString);\n return hexString.toString();\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n //return \"icon-\" + name.replaceAll(\"(\\\\.\\\\.|[\\\\\\\\//$&():=#])+\", \"_\");\n }\n\n\n private static Bitmap loadBitmap(Context context, String filename) {\n Bitmap bitmap = null;\n try {\n if (fileExists(context, filename)) {\n FileInputStream fis = context.openFileInput(filename);\n bitmap = BitmapFactory.decodeStream(fis);\n fis.close();\n }\n } catch (IOException e) {\n Log.e(\"SpecialIconStore\", e.getMessage(), e);\n }\n return bitmap;\n }\n\n\n private static boolean fileExists(Context context, String filename) {\n File file = context.getFileStreamPath(filename);\n if(file == null || !file.exists()) {\n return false;\n }\n return true;\n }\n\n\n public enum IconType {\n Cached, Shortcut, Custom\n }\n\n\n\n}",
"@SuppressLint(\"ApplySharedPref\")\npublic class Theme {\n\n\n //public final static String NEW_SYS = \"newish\";\n public static final String PREFS_UPDATE_KEY = \"prefsUpdate\";\n\n private enum Thing {Mask, Text, AltText, Background, AltBackground, Wallpaper}\n\n private final int [] COLOR_PREFS_REFS = {R.string.pref_key_icon_tint, R.string.pref_key_cattab_background,\n R.string.pref_key_cattabselected_background, R.string.pref_key_cattabselected_text,\n R.string.pref_key_cattabtextcolor, R.string.pref_key_cattabtextcolorinv,\n R.string.pref_key_wallpapercolor, R.string.pref_key_textcolor};\n\n private final String [] COLOR_PREFS;\n\n private final Thing [] THING_MAP = {Thing.Mask, Thing.Background, Thing.AltBackground, Thing.AltText, Thing.Text, Thing.Background, Thing.Wallpaper, Thing.Text};\n\n\n// private int [] getColorDefaultsClassic() {\n// return new int [] {getResColor(R.color.icon_tint), getResColor(R.color.cattab_background), getResColor(R.color.cattabselected_background),\n// getResColor(R.color.cattabselected_text), getResColor(R.color.textcolor), getResColor(R.color.textcolorinv),\n// Color.TRANSPARENT, getResColor(R.color.textcolor)};\n// }\n\n private int [] getColorDefaults() {\n return new int [] {getResColor(R.color.icon_tint), getResColor(R.color.cattab_background), getResColor(R.color.cattabselected_background),\n getResColor(R.color.cattabselected_text), getResColor(R.color.textcolor), getResColor(R.color.textcolorinv),\n getResColor(R.color.wallpaper_color), getResColor(R.color.textcolor)};\n }\n\n\n private final Context ctx;\n\n\n private final Map<String, BuiltinTheme> builtinThemes = new LinkedHashMap<>();\n\n private final IconsHandler iconsHandler;\n\n private final SharedPreferences prefs;\n\n Theme(Context ctx, IconsHandler ich) {\n this.ctx = ctx;\n\n COLOR_PREFS = new String[COLOR_PREFS_REFS.length];\n for (int i=0; i<COLOR_PREFS_REFS.length; i++) {\n COLOR_PREFS[i] = ctx.getString(COLOR_PREFS_REFS[i]);\n }\n\n prefs = PreferenceManager.getDefaultSharedPreferences(ctx.getApplicationContext());\n iconsHandler = ich;\n initBuiltinIconThemes();\n\n }\n\n\n\n //TODO: load these from a file / other package\n\n private void initBuiltinIconThemes() {\n //builtinThemes.put(IconsHandler.DEFAULT_PACK, new DefaultTheme(IconsHandler.DEFAULT_PACK, ctx.getString(R.string.icons_pack_default_name)));\n\n int[] defcolors = getColorDefaults();\n BuiltinTheme newish = new MonochromeTheme(IconsHandler.DEFAULT_PACK, ctx.getString(R.string.icons_pack_default_name))\n .setColor(Thing.Mask, defcolors[0])\n .setColor(Thing.Text, defcolors[4])\n .setColor(Thing.AltText, defcolors[3])\n .setColor(Thing.Background, defcolors[1])\n .setColor(Thing.Wallpaper, defcolors[6])\n .setColor(Thing.AltBackground, defcolors[2]);\n\n builtinThemes.put(newish.getPackKey(), newish);\n\n\n BuiltinTheme classic = new MonochromeTheme(\"classic\", ctx.getString(R.string.theme_classic))\n .setColor(Thing.Mask, Color.TRANSPARENT)\n .setColor(Thing.Text, getResColor(R.color.textcolor_classic))\n .setColor(Thing.AltText, Color.WHITE)\n .setColor(Thing.Background, getResColor(R.color.cattab_background_classic))\n .setColor(Thing.Wallpaper, Color.TRANSPARENT)\n .setColor(Thing.AltBackground, getResColor(R.color.cattabselected_background_classic));\n\n builtinThemes.put(classic.getPackKey(), classic);\n\n\n BuiltinTheme crystal1= new MonochromeTheme(\"crystal1\", ctx.getString(R.string.theme_crystal))\n .setColor(Thing.Mask, Color.parseColor(\"#CC888888\"))\n .setColor(Thing.Text, Color.argb(255,240,240,240))\n .setColor(Thing.AltText, Color.WHITE)\n .setColor(Thing.Wallpaper, Color.parseColor(\"#772955A8\"))\n .setColor(Thing.Background, Color.argb(20,250,250,255))\n .setColor(Thing.AltBackground, Color.argb(90,250,250,255));\n\n builtinThemes.put(crystal1.getPackKey(), crystal1);\n\n\n BuiltinTheme charcoal = new MonochromeTheme(\"charcoal\", ctx.getString(R.string.theme_charcoal))\n .setColor(Thing.Mask, Color.parseColor(\"#4F1D1D1D\"))\n .setColor(Thing.Text, Color.parseColor(\"#EFBBBBBB\"))\n .setColor(Thing.AltText, Color.LTGRAY)\n .setColor(Thing.Wallpaper, Color.parseColor(\"#C2505050\"))\n .setColor(Thing.Background, Color.parseColor(\"#DD434343\"))\n .setColor(Thing.AltBackground, Color.parseColor(\"#e3353535\"));\n\n builtinThemes.put(charcoal.getPackKey(), charcoal);\n\n BuiltinTheme paper= new MonochromeTheme(\"whitepaper\", ctx.getString(R.string.theme_paper))\n .setColor(Thing.Mask, Color.parseColor(\"#CB404040\"))\n .setColor(Thing.Text, Color.argb(255,20,20,20))\n .setColor(Thing.AltText, Color.DKGRAY)\n .setColor(Thing.Wallpaper, Color.parseColor(\"#DBF2F2F2\"))\n .setColor(Thing.Background, Color.parseColor(\"#C3F7F7F7\"))\n .setColor(Thing.AltBackground, Color.parseColor(\"#9FEFF2F2\"));\n\n builtinThemes.put(paper.getPackKey(), paper);\n\n BuiltinTheme transp = new MonochromeTheme(\"transparent\", ctx.getString(R.string.theme_transp))\n .setColor(Thing.Mask, Color.TRANSPARENT)\n .setColor(Thing.Text, Color.argb(255,240,240,240))\n .setColor(Thing.AltText, Color.WHITE)\n .setColor(Thing.Background, Color.TRANSPARENT)\n .setColor(Thing.Wallpaper, Color.parseColor(\"#77132951\"))\n .setColor(Thing.AltBackground, Color.TRANSPARENT);\n\n builtinThemes.put(transp.getPackKey(), transp);\n\n\n\n int [] ucolors = {Color.argb(127,50,50,50), Color.argb(127,10,10,160), Color.argb(127,170,10,10)};\n int [] ubcolors = {Color.BLACK, Color.argb(127,0,0,60), Color.argb(127,60,0,6)};\n for (int i=1; i<=3; i++) {\n BuiltinTheme u = new MonochromeTheme(\"user\" + i, ctx.getString(R.string.user_theme, i))\n .setColor(Thing.Mask, Color.TRANSPARENT)\n .setColor(Thing.Text, Color.argb(255,230,230,230))\n .setColor(Thing.AltText, Color.WHITE)\n .setColor(Thing.Background, ubcolors[i-1])\n .setColor(Thing.Wallpaper, ubcolors[i-1])\n .setColor(Thing.AltBackground, ucolors[i-1]);\n\n builtinThemes.put(u.getPackKey(), u);\n }\n\n\n BuiltinTheme bwicon = new MonochromeTheme(\"bwicon\", ctx.getString(R.string.theme_bw))\n .setColor(Thing.Mask, Color.WHITE)\n .setColor(Thing.Text, Color.argb(255,220,220,220))\n .setColor(Thing.AltText, Color.WHITE)\n .setColor(Thing.Background, Color.BLACK)\n .setColor(Thing.Wallpaper, Color.BLACK)\n .setColor(Thing.AltBackground, Color.parseColor(\"#ff222222\"));\n\n builtinThemes.put(bwicon.getPackKey(), bwicon);\n\n\n BuiltinTheme termcap = new MonochromeTheme(\"termcap\", ctx.getString(R.string.theme_termcap))\n .setColor(Thing.Mask, Color.parseColor(\"#dd22ff22\"))\n .setColor(Thing.Text, Color.parseColor(\"#dd22ff22\"))\n .setColor(Thing.AltText, Color.parseColor(\"#dd22ff22\"))\n .setColor(Thing.Background, Color.BLACK)\n .setColor(Thing.Wallpaper, Color.BLACK)\n .setColor(Thing.AltBackground, Color.parseColor(\"#dd112211\"));\n\n builtinThemes.put(termcap.getPackKey(), termcap);\n\n\n BuiltinTheme coolblue = new MonochromeTheme(\"coolblue\", ctx.getString(R.string.theme_coolblue))\n .setColor(Thing.Mask, Color.parseColor(\"#ff1111ff\"))\n .setColor(Thing.Text, Color.parseColor(\"#eeffffff\"))\n .setColor(Thing.AltText, Color.parseColor(\"#eeffffff\"))\n .setColor(Thing.Background, Color.parseColor(\"#88000077\"))\n .setColor(Thing.Wallpaper, Color.parseColor(\"#55000077\"))\n .setColor(Thing.AltBackground, Color.parseColor(\"#881111ff\"));\n\n builtinThemes.put(coolblue.getPackKey(), coolblue);\n\n BuiltinTheme redplanet = new MonochromeTheme(\"redplanet\", ctx.getString(R.string.theme_redplanet))\n .setColor(Thing.Mask, Color.parseColor(\"#ffff2222\"))\n .setColor(Thing.Text, Color.parseColor(\"#eeff2222\"))\n .setColor(Thing.AltText, Color.parseColor(\"#eeff2222\"))\n .setColor(Thing.Background, Color.parseColor(\"#77550000\"))\n .setColor(Thing.Wallpaper, Color.parseColor(\"#33550000\"))\n .setColor(Thing.AltBackground, Color.parseColor(\"#22121111\"));\n\n builtinThemes.put(redplanet.getPackKey(), redplanet);\n\n BuiltinTheme ladypink = new MonochromeTheme(\"ladypink\", ctx.getString(R.string.theme_ladypink))\n .setColor(Thing.Mask, Color.parseColor(\"#ffff1493\"))\n .setColor(Thing.Text, Color.parseColor(\"#eeffffff\"))\n .setColor(Thing.AltText, Color.parseColor(\"#eeffc0cb\"))\n .setColor(Thing.Background, Color.parseColor(\"#ffff69b4\"))\n .setColor(Thing.Wallpaper, Color.parseColor(\"#88ff69b4\"))\n .setColor(Thing.AltBackground, Color.parseColor(\"#ffff1493\"));\n\n builtinThemes.put(ladypink.getPackKey(), ladypink);\n }\n\n public Map<String, BuiltinTheme> getBuiltinIconThemes() {\n return builtinThemes;\n }\n\n\n public boolean isBuiltinTheme(String packagename) {\n return builtinThemes.containsKey(packagename);\n }\n\n public BuiltinTheme getBuiltinTheme(String packagename) {\n return builtinThemes.get(packagename);\n }\n\n\n public boolean isBuiltinThemeIconTintable(String packagename) {\n return isBuiltinTheme(packagename) && (builtinThemes.get(packagename) instanceof MonochromeTheme);\n }\n\n\n\n private int getResColor(int res) {\n if (Build.VERSION.SDK_INT >= 23) {\n return ctx.getColor(res);\n } else {\n return ctx.getResources().getColor(res);\n }\n }\n\n\n private int getCurrentThemeColor(String pref) {\n BuiltinTheme theme = builtinThemes.get(iconsHandler.getIconsPackPackageName());\n if (theme!=null && theme.hasColors()) {\n int max = COLOR_PREFS.length;\n for (int i=0; i<max; i++) {\n if (pref.equals(COLOR_PREFS[i])) {\n return theme.getColor(THING_MAP[i]);\n }\n }\n }\n\n int [] colorDefaults = getColorDefaults();\n int max = COLOR_PREFS.length;\n for (int i=0; i<max; i++) {\n if (pref.equals(COLOR_PREFS[i])) {\n return colorDefaults[i];\n }\n }\n throw new IllegalArgumentException(\"No such preference '\" + pref + \"'\");\n }\n\n\n private String getThemePrefName(String pref) {\n return \"theme_\" + iconsHandler.getIconsPackPackageName() + \"_\" + pref;\n }\n\n\n\n public void resetUserColors() {\n\n\n SharedPreferences.Editor themeedit = ctx.getSharedPreferences(\"theme\", Context.MODE_PRIVATE).edit();\n\n prefs.edit().putBoolean(Theme.PREFS_UPDATE_KEY, true).apply();\n SharedPreferences.Editor appedit = prefs.edit();\n\n try {\n\n int max = COLOR_PREFS.length;\n for (String COLOR_PREF : COLOR_PREFS) {\n appedit.putInt(COLOR_PREF, getCurrentThemeColor(COLOR_PREF));\n //themeedit.putInt(getThemePrefName(COLOR_PREFS[i]), getCurrentThemeColor(COLOR_PREFS[i]));\n themeedit.remove(getThemePrefName(COLOR_PREF));\n }\n\n } finally {\n appedit.apply();\n prefs.edit().remove(PREFS_UPDATE_KEY).apply();\n themeedit.apply();\n }\n }\n\n\n public void saveUserColors() {\n\n SharedPreferences appprefs = prefs;\n SharedPreferences.Editor themeedit = ctx.getSharedPreferences(\"theme\",Context.MODE_PRIVATE).edit();\n\n try {\n\n int max = COLOR_PREFS.length;\n for (String COLOR_PREF : COLOR_PREFS) {\n themeedit.putInt(getThemePrefName(COLOR_PREF), appprefs.getInt(COLOR_PREF, getCurrentThemeColor(COLOR_PREF)));\n }\n\n } finally {\n themeedit.apply();\n }\n }\n\n\n public boolean restoreUserColors() {\n Log.d(\"Theme\", \"restoreUserColors\");\n SharedPreferences themeprefs = ctx.getSharedPreferences(\"theme\",Context.MODE_PRIVATE);\n\n prefs.edit().putBoolean(PREFS_UPDATE_KEY, true).apply();\n\n SharedPreferences.Editor appedit = prefs.edit();\n\n try {\n\n int max = COLOR_PREFS.length;\n for (String COLOR_PREF : COLOR_PREFS) {\n appedit.putInt(COLOR_PREF, themeprefs.getInt(getThemePrefName(COLOR_PREF), getCurrentThemeColor(COLOR_PREF)));\n }\n } finally {\n appedit.apply();\n prefs.edit().remove(PREFS_UPDATE_KEY).apply();\n }\n return themeprefs.contains(getThemePrefName(COLOR_PREFS[0]));\n }\n\n\n\n public Map<String,String> getUserSetts() {\n\n Map<String,String> setts = new LinkedHashMap<>();\n\n for (Map.Entry<String,?> ent : prefs.getAll().entrySet()) {\n setts.put(ent.getKey(), ent.getValue()==null?\"\":ent.getValue().toString());\n }\n return setts;\n }\n\n\n\n\n abstract class BuiltinTheme {\n\n private final String mKey;\n private final String mName;\n\n private final Map<Thing,Integer> mColors = new HashMap<>();\n\n BuiltinTheme(String key, String name) {\n this(key, name, null);\n }\n\n BuiltinTheme(String key, String name, Map<Thing, Integer> colors) {\n mKey = key;\n mName = name;\n if (colors != null) {\n mColors.putAll(colors);\n }\n\n }\n\n String getPackKey() {\n return mKey;\n }\n\n String getPackName() {\n return mName;\n }\n\n public abstract Drawable getDrawable(AppLauncher app);\n\n boolean hasColors() {\n return mColors.size()>0;\n }\n\n BuiltinTheme setColor(Thing thing, int color) {\n mColors.put(thing, color);\n return this;\n }\n\n Integer getColor(Thing thing) {\n Integer val = mColors.get(thing);\n if (val == null) val = Color.BLACK;\n return val;\n }\n\n\n\n void applyTheme() {\n\n //SharedPreferences themeprefs = ctx.getSharedPreferences(\"theme\",Context.MODE_PRIVATE);\n Log.d(\"Theme\", \"applyTheme\");\n\n SharedPreferences appprefs = prefs;\n prefs.edit().putBoolean(PREFS_UPDATE_KEY, true).apply();\n\n SharedPreferences.Editor appedit = appprefs.edit();\n try {\n\n int[] colorDefaults = getColorDefaults();\n int max = COLOR_PREFS.length;\n for (int i = 0; i < max; i++) {\n if (hasColors()) {\n appedit.putInt(COLOR_PREFS[i], getColor(THING_MAP[i]));\n } else {\n appedit.putInt(COLOR_PREFS[i], colorDefaults[i]);\n }\n }\n } finally {\n appedit.apply();\n prefs.edit().remove(PREFS_UPDATE_KEY).apply();\n }\n\n }\n\n }\n\n\n private class DefaultTheme extends BuiltinTheme {\n\n DefaultTheme(String key, String name) {\n super(key, name);\n }\n\n// public DefaultTheme(String key, String name, Map<Thing, Integer> colors) {\n// super(key, name, colors);\n// }\n @Override\n public Drawable getDrawable(AppLauncher app) {\n return iconsHandler.getDefaultAppDrawable(app);\n }\n\n }\n\n\n\n private class MonochromeTheme extends BuiltinTheme {\n MonochromeTheme(String key, String name) {\n super(key, name);\n }\n\n// public MonochromeTheme(String key, String name, Map<Thing, Integer> colors) {\n// super(key, name, colors);\n// }\n\n @Override\n public Drawable getDrawable(AppLauncher app) {\n\n\n //Log.d(TAG, \"getDrawable called for \" + componentName.getPackageName());\n\n Drawable app_icon = iconsHandler.getDefaultAppDrawable(app);\n\n\n int mask_color = prefs.getInt(ctx.getString(R.string.pref_key_icon_tint), getColor(Thing.Mask));\n\n // Log.d(\"iconi\", mask_color + \" mask\");\n\n IconsHandler.applyIconTint(app_icon, mask_color);\n\n\n return app_icon;\n }\n\n\n }\n\n\n// public class PolychromeTheme extends BuiltinTheme {\n// private final int [] mFGColors;\n// private final int mBGColor;\n//\n// public PolychromeTheme(String key, String name, int [] color, int bgcolor) {\n// super(key, name);\n// mFGColors = Arrays.copyOf(color, color.length);\n// mBGColor = bgcolor;\n// }\n//\n// @Override\n// public Drawable getDrawable(AppLauncher app) {\n//\n// //Log.d(TAG, \"getDrawable called for \" + componentName.getPackageName());\n//\n// Drawable app_icon = iconsHandler.getDefaultAppDrawable(app);\n//\n// app_icon = app_icon.mutate();\n//\n//\n// PorterDuff.Mode mode = PorterDuff.Mode.MULTIPLY;\n//\n// int color = Math.abs(app.getComponentName().getPackageName().hashCode()) % mFGColors.length;\n// app_icon.setColorFilter(mFGColors[color], mode);\n//\n// return app_icon;\n// }\n//\n//\n// }\n\n}"
] | import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.ViewGroup;
import com.quaap.launchtime.R;
import com.quaap.launchtime.apps.AppLauncher;
import com.quaap.launchtime.components.Categories;
import com.quaap.launchtime.components.FsTools;
import com.quaap.launchtime.components.SpecialIconStore;
import com.quaap.launchtime.components.Theme;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern; | }
private static String buildIndexStmt(String tablename, String col) {
return "CREATE INDEX " + ((col + tablename).replaceAll("\\W+", "_")) + " on " + tablename + "(" + col + ");";
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
firstRun = true;
Log.i("db", "create database");
sqLiteDatabase.execSQL(APP_TABLE_CREATE);
for (String createind : appcolumnsindex) {
sqLiteDatabase.execSQL(buildIndexStmt(APP_TABLE, createind));
}
sqLiteDatabase.execSQL(APP_ORDER_TABLE_CREATE);
for (String createind : appordercolumnsindex) {
sqLiteDatabase.execSQL(buildIndexStmt(APP_ORDER_TABLE, createind));
}
sqLiteDatabase.execSQL(CATEGORIES_TABLE_CREATE);
for (String createind : categoriescolumnsindex) {
sqLiteDatabase.execSQL(buildIndexStmt(CATEGORIES_TABLE, createind));
}
sqLiteDatabase.execSQL(APP_HISTORY_TABLE_CREATE);
for (String createind : apphistorycolumnsindex) {
sqLiteDatabase.execSQL(buildIndexStmt(APP_HISTORY_TABLE, createind));
}
buildCatTable(sqLiteDatabase);
}
private void buildCatTable(SQLiteDatabase sqLiteDatabase) {
Log.i("db", "creating category table");
sqLiteDatabase.execSQL("drop table if exists " + APP_CAT_MAP_TABLE);
sqLiteDatabase.execSQL(APP_CAT_MAP_TABLE_CREATE);
for (String createind : appcatmapcolumnsindex) {
sqLiteDatabase.execSQL(buildIndexStmt(APP_CAT_MAP_TABLE, createind));
}
loadCategories(sqLiteDatabase, true, R.raw.submitted_activities,1);
loadCategories(sqLiteDatabase, false, R.raw.submitted_packages, 2);
loadCategories(sqLiteDatabase, false, R.raw.packages1,3);
loadCategories(sqLiteDatabase, false, R.raw.packages2,4);
}
@Override
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
Log.i("db", "upgrade database");
if (oldVersion==1) {
sqLiteDatabase.execSQL("alter table " + APP_TABLE_OLD + " add column " + ISUNINSTALLED + " SHORT");
//sqLiteDatabase.execSQL(buildIndexStmt(APP_TABLE_OLD, ISUNINSTALLED));
ContentValues values = new ContentValues();
values.put(ISUNINSTALLED, 0);
sqLiteDatabase.update(APP_TABLE_OLD, values, null, null);
}
if (oldVersion<=2) {
upgradeTo2(sqLiteDatabase);
}
if (oldVersion<6) {
sqLiteDatabase.execSQL("alter table " + APP_TABLE + " add column " + CUSTOMLABEL + " TEXT");
}
if (oldVersion<10) {
ContentValues values = new ContentValues();
values.put(INDEX, 101);
sqLiteDatabase.update(CATEGORIES_TABLE, values, CATID + "=?", new String[]{Categories.CAT_SEARCH});
}
if (oldVersion<11) {
buildCatTable(sqLiteDatabase);
}
sqLiteDatabase.delete(APP_ORDER_TABLE, PKGNAME + " is null", null);
}
public boolean isFirstRun() {
return firstRun;
}
public List<ComponentName> getAppNames() {
List<ComponentName> actvnames = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(APP_TABLE, new String[]{ACTVNAME, PKGNAME}, ISUNINSTALLED+"=0", null, null, null, LABEL);
try {
while (cursor.moveToNext()) {
String actv = cursor.getString(cursor.getColumnIndex(ACTVNAME));
String pkg = cursor.getString(cursor.getColumnIndex(PKGNAME));
try {
ComponentName cn = new ComponentName(pkg, actv);
actvnames.add(cn);
} catch (Exception e) {
Log.e("LaunchDB", e.getMessage(), e);
}
}
} finally {
cursor.close();
}
return actvnames;
}
| public AppLauncher getApp(ComponentName appname) { | 0 |
CreativeMD/EnhancedVisuals | src/main/java/team/creative/enhancedvisuals/common/event/EVEvents.java | [
"@Mod(modid = EnhancedVisuals.MODID, name = EnhancedVisuals.NAME, version = EnhancedVisuals.VERSION, acceptedMinecraftVersions = \"\", dependencies = \"required-after:creativecore\", guiFactory = \"team.creative.enhancedvisuals.client.EVSettings\")\npublic class EnhancedVisuals {\n\t\n\tpublic static final String MODID = \"enhancedvisuals\";\n\tpublic static final String NAME = \"Enhanced Visuals\";\n\tpublic static final String VERSION = \"1.3.0\";\n\t\n\tpublic static final Logger LOGGER = LogManager.getLogger(EnhancedVisuals.MODID);\n\tpublic static EVEvents EVENTS;\n\tpublic static DeathMessages MESSAGES;\n\tpublic static EnhancedVisualsConfig CONFIG;\n\t\n\t@SidedProxy(clientSide = \"team.creative.enhancedvisuals.client.EVClient\", serverSide = \"team.creative.enhancedvisuals.server.EVServer\")\n\tpublic static EVServer proxy;\n\t\n\t@EventHandler\n\tpublic void load(FMLInitializationEvent event) {\n\t\tCreativeCorePacket.registerPacket(ExplosionPacket.class);\n\t\tCreativeCorePacket.registerPacket(DamagePacket.class);\n\t\tCreativeCorePacket.registerPacket(PotionPacket.class);\n\t\t\n\t\tMinecraftForge.EVENT_BUS.register(EVENTS = new EVEvents());\n\t\t\n\t\tVisualHandlers.init();\n\t\tMESSAGES = new DeathMessages();\n\t\tCONFIG = new EnhancedVisualsConfig();\n\t\t\n\t\tif (Loader.isModLoaded(\"toughasnails\"))\n\t\t\tToughAsNailsAddon.load();\n\t\t\n\t\tif (Loader.isModLoaded(\"simpledifficulty\"))\n\t\t\tSimpleDifficultyAddon.load();\n\t\t\n\t\tproxy.load(event);\n\t\t\n\t\tConfigHolderDynamic root = CreativeConfigRegistry.ROOT.registerFolder(MODID);\n\t\troot.registerValue(\"general\", CONFIG, ConfigSynchronization.CLIENT, false);\n\t\troot.registerValue(\"messages\", MESSAGES);\n\t\tConfigHolderDynamic handlers = root.registerFolder(\"handlers\", ConfigSynchronization.CLIENT);\n\t\tfor (Entry<ResourceLocation, VisualHandler> entry : VisualRegistry.entrySet())\n\t\t\thandlers.registerValue(entry.getKey().getResourcePath(), entry.getValue());\n\t\t\n\t}\n\t\n}",
"@SideOnly(Side.CLIENT)\npublic class EVClient extends EVServer {\n \n private static Minecraft mc = Minecraft.getMinecraft();\n \n @Override\n public void load(FMLInitializationEvent event) {\n ((IReloadableResourceManager) mc.getResourceManager()).registerReloadListener(new IResourceManagerReloadListener() {\n \n @Override\n public void onResourceManagerReload(IResourceManager resourceManager) {\n VisualManager.clearParticles();\n \n for (VisualType type : VisualType.getTypes()) {\n type.loadResources(resourceManager);\n }\n }\n });\n \n IResourceManager manager = mc.getResourceManager();\n for (VisualType type : VisualType.getTypes())\n type.loadResources(manager);\n \n MinecraftForge.EVENT_BUS.register(EVRenderer.class);\n }\n \n public static boolean shouldRender() {\n return mc.player != null ? (!mc.player.isSpectator() && (!mc.player.isCreative() || EnhancedVisuals.CONFIG.doEffectsInCreative)) : true;\n }\n \n public static boolean shouldTick() {\n return true;\n }\n}",
"public class VisualManager {\n \n private static Minecraft mc = Minecraft.getMinecraft();\n public static Random rand = new Random();\n private static HashMapList<VisualCategory, Visual> visuals = new HashMapList<>();\n \n public static void onTick(@Nullable EntityPlayer player) {\n boolean areEyesInWater = player != null && EVEvents.areEyesInWater(player);\n \n synchronized (visuals) {\n for (Iterator<Visual> iterator = visuals.iterator(); iterator.hasNext();) {\n Visual visual = iterator.next();\n \n int factor = 1;\n if (areEyesInWater && visual.isAffectedByWater())\n factor = EnhancedVisuals.CONFIG.waterSubstractFactor;\n \n for (int i = 0; i < factor; i++) {\n if (!visual.tick()) {\n visual.removeFromDisplay();\n iterator.remove();\n break;\n }\n }\n }\n \n for (VisualHandler handler : VisualRegistry.handlers()) {\n if (handler.isEnabled(player))\n handler.tick(player);\n }\n }\n \n if (player != null && !player.isEntityAlive())\n VisualManager.clearParticles();\n }\n \n public static Collection<Visual> visuals(VisualCategory category) {\n return visuals.getValues(category);\n }\n \n public static void clearParticles() {\n synchronized (visuals) {\n visuals.removeKey(VisualCategory.particle);\n }\n }\n \n public static void add(Visual visual) {\n if (!visual.type.disabled) {\n visual.addToDisplay();\n visuals.add(visual.getCategory(), visual);\n }\n }\n \n public static Visual addVisualFadeOut(VisualType vt, VisualHandler handler, IntMinMax time) {\n return addVisualFadeOut(vt, handler, new DecimalCurve(0, 1, time.next(rand), 0));\n }\n \n public static Visual addVisualFadeOut(VisualType vt, VisualHandler handler, int time) {\n return addVisualFadeOut(vt, handler, new DecimalCurve(0, 1, time, 0));\n }\n \n public static Visual addVisualFadeOut(VisualType vt, VisualHandler handler, Curve curve) {\n Visual v = new Visual(vt, handler, curve, vt.getVariantAmount() > 1 ? rand.nextInt(vt.getVariantAmount()) : 0);\n add(v);\n return v;\n }\n \n public static void addParticlesFadeOut(VisualType vt, VisualHandler handler, int count, IntMinMax time, boolean rotate) {\n addParticlesFadeOut(vt, handler, count, new DecimalCurve(0, 1, time.next(rand), 0), rotate, null);\n }\n \n public static void addParticlesFadeOut(VisualType vt, VisualHandler handler, int count, IntMinMax time, boolean rotate, Color color) {\n addParticlesFadeOut(vt, handler, count, new DecimalCurve(0, 1, time.next(rand), 0), rotate, color);\n }\n \n public static void addParticlesFadeOut(VisualType vt, VisualHandler handler, int count, int time, boolean rotate) {\n addParticlesFadeOut(vt, handler, count, new DecimalCurve(0, 1, time, 0), rotate, null);\n }\n \n public static void addParticlesFadeOut(VisualType vt, VisualHandler handler, int count, Curve curve, boolean rotate, Color color) {\n if (vt.disabled)\n return;\n for (int i = 0; i < count; i++) {\n ScaledResolution resolution = new ScaledResolution(mc);\n int screenWidth = resolution.getScaledWidth();\n int screenHeight = resolution.getScaledHeight();\n \n int width = vt.getWidth(screenWidth);\n int height = vt.getHeight(screenHeight);\n \n if (vt.scaleVariants()) {\n double scale = vt.randomScale(rand);\n width *= scale;\n height *= scale;\n }\n \n Particle particle = new Particle(vt, handler, curve, generateOffset(rand, screenWidth, width), generateOffset(rand, screenHeight, height), width, height, vt\n .canRotate() && rotate ? rand\n .nextFloat() * 360 : 0, rand.nextInt(vt.getVariantAmount()));\n if (color != null)\n particle.color = color;\n add(particle);\n }\n }\n \n public static int generateOffset(Random rand, int dimensionLength, int spacingBuffer) {\n int half = dimensionLength / 2;\n float multiplier = (float) (1 - Math.pow(rand.nextDouble(), 2));\n float textureCenterPosition = rand.nextInt(2) == 0 ? half + half * multiplier : half - half * multiplier;\n return (int) (textureCenterPosition - (spacingBuffer / 2.0F));\n }\n \n}",
"public class SoundMuteHandler {\n\t\n\tpublic static boolean isMuting = false;\n\t\n\tpublic static HashMap<Source, Float> sources = null;\n\t\n\tpublic static Library soundLibrary;\n\tpublic static SoundSystem sndSystem;\n\t\n\tpublic static ArrayList<String> ignoredSounds;\n\t\n\tpublic static DecimalCurve muteGraph;\n\tpublic static int timeTick = 0;\n\t\n\tpublic static void tick() {\n\t\tif (isMuting) {\n\t\t\tdouble factor = muteGraph.valueAt(timeTick);\n\t\t\t\n\t\t\tif (factor <= 0)\n\t\t\t\tendMuting();\n\t\t\telse {\n\t\t\t\tsetMuteVolume((float) (1 - factor));\n\t\t\t\ttimeTick++;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic static void updateSounds() {\n\t\ttry {\n\t\t\tHashMap<String, Source> sourcesAndIDs = null;\n\t\t\tsynchronized (SoundSystemConfig.THREAD_SYNC) {\n\t\t\t\tsourcesAndIDs = new HashMap<>(soundLibrary.getSources());\n\t\t\t}\n\t\t\tfor (Source source : sourcesAndIDs.values()) {\n\t\t\t\tif (!sources.containsKey(source) && !ignoredSounds.contains(source.sourcename))\n\t\t\t\t\tsources.put(source, source.sourceVolume);\n\t\t\t}\n\t\t} catch (Exception e) {\n\t\t\t//Thread error\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\t\n\tpublic static boolean startMuting(DecimalCurve muteGraph) {\n\t\tif (soundLibrary == null) {\n\t\t\tSoundHandler handler = Minecraft.getMinecraft().getSoundHandler();\n\t\t\tSoundManager sndManager = ReflectionHelper.getPrivateValue(SoundHandler.class, handler, new String[] { \"sndManager\", \"field_147694_f\" });\n\t\t\tsndSystem = ReflectionHelper.getPrivateValue(SoundManager.class, sndManager, new String[] { \"sndSystem\", \"field_148620_e\" });\n\t\t\tsoundLibrary = ReflectionHelper.getPrivateValue(SoundSystem.class, sndSystem, new String[] { \"soundLibrary\" });\n\t\t}\n\t\t\n\t\tif (isMuting && SoundMuteHandler.muteGraph.valueAt(timeTick) > muteGraph.valueAt(0)) {\n\t\t\tSoundMuteHandler.muteGraph = muteGraph;\n\t\t\tSoundMuteHandler.timeTick = 0;\n\t\t\ttick();\n\t\t\treturn true;\n\t\t} else if (!isMuting) {\n\t\t\tSoundMuteHandler.muteGraph = muteGraph;\n\t\t\tSoundMuteHandler.timeTick = 0;\n\t\t\tignoredSounds = new ArrayList<>();\n\t\t\tisMuting = true;\n\t\t\ttick();\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tpublic static void endMuting() {\n\t\tsetMuteVolume(1F);\n\t\tsources = null;\n\t\tisMuting = false;\n\t\tignoredSounds = null;\n\t}\n\t\n\tpublic static synchronized void setMuteVolume(float muteVolume) {\n\t\tif (isMuting && sources != null) {\n\t\t\tsynchronized (SoundSystemConfig.THREAD_SYNC) {\n\t\t\t\tfor (Source source : sources.keySet()) {\n\t\t\t\t\tsndSystem.setVolume(source.sourcename, sources.get(source) * muteVolume);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n}",
"public class DamagePacket extends CreativeCorePacket {\n \n public String attackerClass;\n public ItemStack stack;\n public float damage;\n \n public float distance;\n public boolean fire;\n public String source;\n \n public DamagePacket(LivingDamageEvent event) {\n this.damage = event.getAmount();\n Entity attacker = event.getSource().getImmediateSource();\n this.fire = event.getSource().isFireDamage();\n if (attacker instanceof EntityLiving || attacker instanceof EntityArrow) {\n attackerClass = attacker.getClass().getName().toLowerCase();\n this.source = \"attacker\";\n \n if (attacker instanceof EntityLiving && ((EntityLiving) attacker).getHeldItemMainhand() != null)\n stack = ((EntityLiving) attacker).getHeldItemMainhand();\n \n } else\n this.source = event.getSource().damageType;\n }\n \n public DamagePacket() {\n \n }\n \n @Override\n public void writeBytes(ByteBuf buf) {\n if (attackerClass != null) {\n buf.writeBoolean(true);\n writeString(buf, attackerClass);\n } else\n buf.writeBoolean(false);\n \n if (stack != null) {\n buf.writeBoolean(true);\n writeItemStack(buf, stack);\n } else\n buf.writeBoolean(false);\n \n buf.writeFloat(damage);\n buf.writeFloat(distance);\n writeString(buf, source);\n buf.writeBoolean(fire);\n }\n \n @Override\n public void readBytes(ByteBuf buf) {\n if (buf.readBoolean())\n attackerClass = readString(buf);\n if (buf.readBoolean())\n stack = readItemStack(buf);\n damage = buf.readFloat();\n distance = buf.readFloat();\n source = readString(buf);\n fire = buf.readBoolean();\n }\n \n @Override\n public void executeClient(EntityPlayer player) {\n if (VisualHandlers.DAMAGE.isEnabled(player))\n VisualHandlers.DAMAGE.playerDamaged(player, this);\n }\n \n @Override\n public void executeServer(EntityPlayer player) {\n \n }\n \n}",
"public class ExplosionPacket extends CreativeCorePacket {\n\t\n\tpublic Vec3d pos;\n\tpublic float size;\n\tpublic int sourceEntity;\n\t\n\tpublic ExplosionPacket(Vec3d pos, float size, int sourceEntity) {\n\t\tthis.pos = pos;\n\t\tthis.size = size;\n\t\tthis.sourceEntity = sourceEntity;\n\t}\n\t\n\tpublic ExplosionPacket() {\n\t\t\n\t}\n\t\n\t@Override\n\tpublic void writeBytes(ByteBuf buf) {\n\t\twriteVec3d(pos, buf);\n\t\tbuf.writeFloat(size);\n\t\tbuf.writeInt(sourceEntity);\n\t}\n\t\n\t@Override\n\tpublic void readBytes(ByteBuf buf) {\n\t\tpos = readVec3d(buf);\n\t\tsize = buf.readFloat();\n\t\tsourceEntity = buf.readInt();\n\t}\n\t\n\t@Override\n\tpublic void executeClient(EntityPlayer player) {\n\t\tif (VisualHandlers.EXPLOSION.isEnabled(player))\n\t\t\tVisualHandlers.EXPLOSION.onExploded(player, pos, size, player.world.getEntityByID(sourceEntity));\n\t}\n\t\n\t@Override\n\tpublic void executeServer(EntityPlayer player) {\n\t\t\n\t}\n\t\n}",
"public class PotionPacket extends CreativeCorePacket {\n\t\n\tpublic double distance;\n\tpublic ItemStack stack;\n\t\n\tpublic PotionPacket() {\n\t\t\n\t}\n\t\n\tpublic PotionPacket(double distance, ItemStack stack) {\n\t\tthis.distance = distance;\n\t\tthis.stack = stack;\n\t}\n\t\n\t@Override\n\tpublic void writeBytes(ByteBuf buf) {\n\t\tbuf.writeDouble(distance);\n\t\twriteItemStack(buf, stack);\n\t}\n\t\n\t@Override\n\tpublic void readBytes(ByteBuf buf) {\n\t\tdistance = buf.readDouble();\n\t\tstack = readItemStack(buf);\n\t}\n\t\n\t@Override\n\tpublic void executeClient(EntityPlayer player) {\n\t\tif (VisualHandlers.POTION.isEnabled(player))\n\t\t\tVisualHandlers.POTION.impact(distance, stack);\n\t}\n\t\n\t@Override\n\tpublic void executeServer(EntityPlayer player) {\n\t\t\n\t}\n}"
] | import java.lang.reflect.Field;
import java.util.List;
import com.creativemd.creativecore.common.packet.PacketHandler;
import net.minecraft.block.material.Material;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.entity.projectile.EntityPotion;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.world.Explosion;
import net.minecraftforge.event.entity.ProjectileImpactEvent;
import net.minecraftforge.event.entity.living.LivingDamageEvent;
import net.minecraftforge.event.world.ExplosionEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.TickEvent.ClientTickEvent;
import net.minecraftforge.fml.common.gameevent.TickEvent.Phase;
import net.minecraftforge.fml.relauncher.ReflectionHelper;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import team.creative.enhancedvisuals.EnhancedVisuals;
import team.creative.enhancedvisuals.client.EVClient;
import team.creative.enhancedvisuals.client.VisualManager;
import team.creative.enhancedvisuals.client.sound.SoundMuteHandler;
import team.creative.enhancedvisuals.common.packet.DamagePacket;
import team.creative.enhancedvisuals.common.packet.ExplosionPacket;
import team.creative.enhancedvisuals.common.packet.PotionPacket; | package team.creative.enhancedvisuals.common.event;
public class EVEvents {
private Field size = ReflectionHelper.findField(Explosion.class, new String[] { "field_77280_f", "size" });
private Field exploder = ReflectionHelper.findField(Explosion.class, new String[] { "field_77283_e", "exploder" });
@SubscribeEvent
public void explosion(ExplosionEvent.Detonate event) {
if (event.getWorld() != null && !event.getWorld().isRemote) {
try {
int sourceEntity = -1;
Entity source = ((Entity) exploder.get(event.getExplosion()));
if (source != null)
sourceEntity = source.getEntityId(); | ExplosionPacket packet = new ExplosionPacket(event.getExplosion().getPosition(), size.getFloat(event.getExplosion()), sourceEntity); | 5 |
krazykira/VidEffects | videffects/src/main/java/com/sherazkhilji/videffects/view/VideoSurfaceView.java | [
"public class NoEffect implements ShaderInterface {\r\n\r\n @Override\r\n public String getShader(GLSurfaceView mGlSurfaceView) {\r\n return \"#extension GL_OES_EGL_image_external : require\\n\"\r\n + \"precision mediump float;\\n\"\r\n + \"varying vec2 vTextureCoord;\\n\"\r\n + \"uniform samplerExternalOES sTexture;\\n\" + \"void main() {\\n\"\r\n + \" gl_FragColor = texture2D(sTexture, vTextureCoord);\\n\"\r\n + \"}\\n\";\r\n\r\n }\r\n}",
"public class NoEffectFilter implements Filter {\n\n private static final String TAG = \"NoEffectFilter\";\n\n private static final String FRAGMENT_SHADER = \"#extension GL_OES_EGL_image_external : require\\n\"\n + \"precision mediump float;\\n\"\n + \"varying vec2 vTextureCoord;\\n\"\n + \"uniform samplerExternalOES sTexture;\\n\" + \"void main() {\\n\"\n + \" gl_FragColor = texture2D(sTexture, vTextureCoord);\\n\"\n + \"}\\n\";\n\n @Override\n public String getVertexShader() {\n return Constants.DEFAULT_VERTEX_SHADER;\n }\n\n @Override\n public String getFragmentShader() {\n return FRAGMENT_SHADER;\n }\n\n @Override\n public void setIntensity(float intensity) {\n Log.d(TAG,\"No effect\");\n }\n}",
"public interface Filter {\r\n\r\n\tpublic String getVertexShader();\r\n\r\n\tpublic String getFragmentShader();\r\n\r\n\tpublic void setIntensity(float intensity);\r\n}\r",
"@Deprecated\r\npublic interface ShaderInterface {\r\n\t/**\r\n\t * Returns Constants code\r\n\t *\r\n\t * @param mGlSurfaceView\r\n\t * send this for every shader but this will only be used when the\r\n\t * shader needs it.\r\n\t * @return complete shader code in C\r\n\t */\r\n\tpublic String getShader(GLSurfaceView mGlSurfaceView);\r\n\r\n}\r",
"public abstract class BaseRenderer {\n\n private static final String TAG = \"BaseRenderer\";\n\n private int[] bufferHandles = new int[2];\n private int[] textureHandles = new int[2];\n\n private float[] texMatrix = new float[16];\n private float[] mvpMatrix = new float[16];\n private int[] linkStatus = new int[1];\n\n protected BaseRenderer() {\n\n }\n\n protected abstract int getVertexShader();\n\n protected abstract int getFragmentShader();\n\n protected int getTexture() {\n return textureHandles[0];\n }\n\n protected float[] getTransformMatrix() {\n return texMatrix;\n }\n\n private int createProgram() {\n int program = GLES20.glCreateProgram();\n if (program != 0) {\n GLES20.glAttachShader(program, getVertexShader());\n GLES20.glAttachShader(program, getFragmentShader());\n GLES20.glLinkProgram(program);\n GLES20.glGetProgramiv(program, GLES20.GL_LINK_STATUS, linkStatus, 0);\n if (linkStatus[0] != GLES20.GL_TRUE) {\n Log.e(TAG, \"Could not link program: \");\n Log.e(TAG, GLES20.glGetProgramInfoLog(program));\n GLES20.glDeleteProgram(program);\n program = 0;\n }\n }\n return program;\n }\n\n protected void init() {\n GLES20.glGenBuffers(2, bufferHandles, 0);\n GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, bufferHandles[0]);\n GLES20.glBufferData(GLES20.GL_ARRAY_BUFFER, Utils.VERTICES.length * FLOAT_SIZE_BYTES, Utils.getVertexBuffer(), GLES20.GL_DYNAMIC_DRAW);\n GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, bufferHandles[1]);\n GLES20.glBufferData(GLES20.GL_ELEMENT_ARRAY_BUFFER, Utils.INDICES.length * FLOAT_SIZE_BYTES, Utils.getIndicesBuffer(), GLES20.GL_DYNAMIC_DRAW);\n GLES20.glGenTextures(2, textureHandles, 0);\n GLES20.glBindTexture(GL_TEXTURE_EXTERNAL_OES, textureHandles[0]);\n GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR);\n GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);\n GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE);\n GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE);\n GLES20.glEnable(GLES20.GL_BLEND);\n GLES20.glBlendFunc(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA);\n }\n\n protected void draw() {\n Matrix.setIdentityM(mvpMatrix, 0);\n\n int program = createProgram();\n int vertexHandle = GLES20.glGetAttribLocation(program, \"aPosition\");\n int uvsHandle = GLES20.glGetAttribLocation(program, \"aTextureCoord\");\n int texMatrixHandle = GLES20.glGetUniformLocation(program, \"uSTMatrix\");\n int mvpMatrixHandle = GLES20.glGetUniformLocation(program, \"uMVPMatrix\");\n int samplerHandle = GLES20.glGetUniformLocation(program, \"sTexture\");\n\n GLES20.glUseProgram(program);\n GLES20.glUniformMatrix4fv(texMatrixHandle, 1, false, texMatrix, 0);\n GLES20.glUniformMatrix4fv(mvpMatrixHandle, 1, false, mvpMatrix, 0);\n GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, bufferHandles[0]);\n GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, bufferHandles[1]);\n GLES20.glEnableVertexAttribArray(vertexHandle);\n GLES20.glVertexAttribPointer(vertexHandle, 3, GLES20.GL_FLOAT, false, 4 * 5, 0);\n GLES20.glEnableVertexAttribArray(uvsHandle);\n GLES20.glVertexAttribPointer(uvsHandle, 2, GLES20.GL_FLOAT, false, 4 * 5, 3 * 4);\n GLES20.glDrawElements(GLES20.GL_TRIANGLES, 6, GLES20.GL_UNSIGNED_INT, 0);\n }\n}",
"public class Utils {\n\n private static final String TAG = \"Utils\";\n\n private Utils() {\n\n }\n\n public static float[] VERTICES = {\n -1.0f, -1.0f, 0.0f, 0f, 0f,\n -1.0f, 1.0f, 0.0f, 0f, 1f,\n 1.0f, 1.0f, 0.0f, 1f, 1f,\n 1.0f, -1.0f, 0.0f, 1f, 0f\n };\n\n public static int[] INDICES = {\n 2, 1, 0, 0, 3, 2\n };\n\n public static int loadShader(int shaderType, String source) {\n int shader = GLES20.glCreateShader(shaderType);\n if (shader != 0) {\n GLES20.glShaderSource(shader, source);\n GLES20.glCompileShader(shader);\n int[] compiled = new int[1];\n GLES20.glGetShaderiv(shader, GLES20.GL_COMPILE_STATUS,\n compiled, 0);\n if (compiled[0] == 0) {\n Log.e(TAG, \"Could not compile shader \" + shaderType + \":\");\n Log.e(TAG, GLES20.glGetShaderInfoLog(shader));\n GLES20.glDeleteShader(shader);\n shader = 0;\n }\n }\n return shader;\n }\n\n public static FloatBuffer getVertexBuffer() {\n FloatBuffer vertexBuffer = ByteBuffer.allocateDirect(Utils.VERTICES.length * 4)\n .order(ByteOrder.nativeOrder()).asFloatBuffer();\n vertexBuffer.put(Utils.VERTICES);\n vertexBuffer.position(0);\n return vertexBuffer;\n }\n\n public static IntBuffer getIndicesBuffer() {\n IntBuffer indexBuffer = ByteBuffer.allocateDirect(Utils.INDICES.length * 4)\n .order(ByteOrder.nativeOrder()).asIntBuffer();\n indexBuffer.put(Utils.INDICES);\n indexBuffer.position(0);\n return indexBuffer;\n }\n}",
"public static final String DEFAULT_VERTEX_SHADER = \"uniform mat4 uMVPMatrix;\\n\"\n + \"uniform mat4 uSTMatrix;\\n\"\n + \"attribute vec4 aPosition;\\n\"\n + \"attribute vec4 aTextureCoord;\\n\"\n + \"varying vec2 vTextureCoord;\\n\"\n + \"void main() {\\n\"\n + \" gl_Position = uMVPMatrix * aPosition;\\n\"\n + \" vTextureCoord = (uSTMatrix * aTextureCoord).xy;\\n\"\n + \"}\\n\";"
] | import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.SurfaceTexture;
import android.media.MediaPlayer;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.opengl.Matrix;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Surface;
import com.sherazkhilji.videffects.NoEffect;
import com.sherazkhilji.videffects.filter.NoEffectFilter;
import com.sherazkhilji.videffects.interfaces.Filter;
import com.sherazkhilji.videffects.interfaces.ShaderInterface;
import com.sherazkhilji.videffects.model.BaseRenderer;
import com.sherazkhilji.videffects.model.Utils;
import java.io.IOException;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import static com.sherazkhilji.videffects.Constants.DEFAULT_VERTEX_SHADER; | * @param shaderEffect any effect that implements {@link ShaderInterface}
*/
@Deprecated
public void setShader(ShaderInterface shaderEffect) {
this.filter = null;
effect = shaderEffect != null ? shaderEffect : new NoEffect();
}
public void setFilter(Filter filter) {
this.effect = null;
this.filter = filter != null ? filter : new NoEffectFilter();
}
public ShaderInterface getShader() {
return effect;
}
public Filter getFilter() {
return filter;
}
@Override
public void onResume() {
if (mMediaPlayer == null) {
Log.e(TAG, "Call init() before Continuing");
return;
}
super.onResume();
}
@Override
public void onPause() {
super.onPause();
mMediaPlayer.pause();
}
private class VideoRender extends BaseRenderer implements Renderer,
SurfaceTexture.OnFrameAvailableListener {
private SurfaceTexture mSurface;
private boolean updateSurface = false;
private boolean isMediaPlayerPrepared = false;
VideoRender() {
Matrix.setIdentityM(getTransformMatrix(), 0);
}
@Override
public void onSurfaceCreated(GL10 glUnused, EGLConfig config) {
super.init();
/*
* Create the SurfaceTexture that will feed this textureID, and pass
* it to the MediaPlayer
*/
mSurface = new SurfaceTexture(getTexture());
mSurface.setOnFrameAvailableListener(this);
Surface surface = new Surface(mSurface);
mMediaPlayer.setSurface(surface);
mMediaPlayer.setScreenOnWhilePlaying(true);
surface.release();
if (!isMediaPlayerPrepared) {
try {
mMediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
isMediaPlayerPrepared = true;
}
synchronized (this) {
updateSurface = false;
}
mMediaPlayer.start();
}
@Override
public void onSurfaceChanged(GL10 glUnused, int width, int height) {
}
@Override
synchronized public void onFrameAvailable(SurfaceTexture surface) {
updateSurface = true;
}
@Override
public void onDrawFrame(GL10 glUnused) {
synchronized (this) {
if (updateSurface) {
mSurface.updateTexImage();
mSurface.getTransformMatrix(getTransformMatrix());
updateSurface = false;
}
}
GLES20.glClearColor(0.0f, 1.0f, 0.0f, 1.0f);
GLES20.glClear(GLES20.GL_DEPTH_BUFFER_BIT | GLES20.GL_COLOR_BUFFER_BIT);
draw();
}
@Override
protected void draw() {
super.draw();
GLES20.glDrawElements(GLES20.GL_TRIANGLES, 6, GLES20.GL_UNSIGNED_INT, 0);
GLES20.glFinish();
}
@Override
protected int getVertexShader() {
String vertexShaderString;
if (effect != null) {
vertexShaderString = DEFAULT_VERTEX_SHADER;
} else if (filter != null) {
vertexShaderString = filter.getVertexShader();
} else {
throw new IllegalStateException("Effect is not applied");
} | return Utils.loadShader(GLES20.GL_VERTEX_SHADER, vertexShaderString); | 5 |
spinnaker/fiat | fiat-web/src/main/java/com/netflix/spinnaker/fiat/controllers/RolesController.java | [
"@Data\npublic class UserPermission {\n private String id;\n\n private Set<Account> accounts = new LinkedHashSet<>();\n private Set<Application> applications = new LinkedHashSet<>();\n private Set<ServiceAccount> serviceAccounts = new LinkedHashSet<>();\n private Set<Role> roles = new LinkedHashSet<>();\n private Set<BuildService> buildServices = new LinkedHashSet<>();\n private Set<Resource> extensionResources = new LinkedHashSet<>();\n private boolean admin = false;\n\n /**\n * Custom setter to normalize the input. lombok.accessors.chain is enabled, so setters must return\n * {@code this}.\n */\n public UserPermission setId(String id) {\n this.id = id.toLowerCase();\n return this;\n }\n\n /** Custom getter to normalize the output. */\n public String getId() {\n return this.id.toLowerCase();\n }\n\n public void addResource(Resource resource) {\n addResources(Collections.singleton(resource));\n }\n\n public UserPermission addResources(Collection<Resource> resources) {\n if (resources == null) {\n return this;\n }\n\n resources.forEach(\n resource -> {\n if (resource instanceof Account) {\n accounts.add((Account) resource);\n } else if (resource instanceof Application) {\n applications.add((Application) resource);\n } else if (resource instanceof ServiceAccount) {\n serviceAccounts.add((ServiceAccount) resource);\n } else if (resource instanceof Role) {\n roles.add((Role) resource);\n } else if (resource instanceof BuildService) {\n buildServices.add((BuildService) resource);\n } else {\n extensionResources.add(resource);\n }\n });\n\n return this;\n }\n\n @JsonIgnore\n public Set<Resource> getAllResources() {\n Set<Resource> retVal = new HashSet<>();\n retVal.addAll(accounts);\n retVal.addAll(applications);\n retVal.addAll(serviceAccounts);\n retVal.addAll(roles);\n retVal.addAll(buildServices);\n retVal.addAll(extensionResources);\n return retVal;\n }\n\n /**\n * This method adds all of other's resources to this one.\n *\n * @param other\n */\n public UserPermission merge(UserPermission other) {\n this.addResources(other.getAllResources());\n return this;\n }\n\n @JsonIgnore\n public View getView() {\n return new View(this);\n }\n\n @Data\n @EqualsAndHashCode(callSuper = false)\n @NoArgsConstructor\n @SuppressWarnings(\"unchecked\")\n public static class View extends Viewable.BaseView {\n String name;\n Set<Account.View> accounts;\n Set<Application.View> applications;\n Set<ServiceAccount.View> serviceAccounts;\n Set<Role.View> roles;\n Set<BuildService.View> buildServices;\n HashMap<ResourceType, Set<Authorizable>> extensionResources;\n boolean admin;\n boolean legacyFallback = false;\n boolean allowAccessToUnknownApplications = false;\n\n public View(UserPermission permission) {\n this.name = permission.id;\n\n Function<Set<? extends Viewable>, Set<? extends Viewable.BaseView>> toViews =\n sourceSet ->\n sourceSet.stream()\n .map(viewable -> viewable.getView(permission.getRoles(), permission.isAdmin()))\n .collect(Collectors.toSet());\n\n this.accounts = (Set<Account.View>) toViews.apply(permission.getAccounts());\n this.applications = (Set<Application.View>) toViews.apply(permission.getApplications());\n this.serviceAccounts =\n (Set<ServiceAccount.View>) toViews.apply(permission.getServiceAccounts());\n this.roles = (Set<Role.View>) toViews.apply(permission.getRoles());\n this.buildServices = (Set<BuildService.View>) toViews.apply(permission.getBuildServices());\n\n this.extensionResources = new HashMap<>();\n for (val resource : permission.extensionResources) {\n val set =\n this.extensionResources.computeIfAbsent(\n resource.getResourceType(), (ignore) -> new HashSet<>());\n val view = ((Viewable) resource).getView(permission.getRoles(), permission.isAdmin());\n if (view instanceof Authorizable) {\n set.add((Authorizable) view);\n }\n }\n\n this.admin = permission.isAdmin();\n }\n }\n}",
"@Component\n@Data\n@EqualsAndHashCode(of = \"name\")\n@NoArgsConstructor\npublic class Role implements Resource, Viewable {\n\n private final ResourceType resourceType = ResourceType.ROLE;\n private String name;\n\n public enum Source {\n EXTERNAL,\n FILE,\n GOOGLE_GROUPS,\n GITHUB_TEAMS,\n LDAP\n }\n\n private Source source;\n\n public Role(String name) {\n this.setName(name);\n }\n\n public Role setName(@Nonnull String name) {\n if (!StringUtils.hasText(name)) {\n throw new IllegalArgumentException(\"name cannot be empty\");\n }\n this.name = name.toLowerCase();\n return this;\n }\n\n @JsonIgnore\n @Override\n public View getView(Set<Role> ignored, boolean isAdmin) {\n return new View(this);\n }\n\n @Data\n @EqualsAndHashCode(callSuper = false)\n @NoArgsConstructor\n public static class View extends BaseView {\n private String name;\n private Source source;\n\n public View(Role role) {\n this.name = role.name;\n this.source = role.getSource();\n }\n }\n}",
"@Data\npublic class ExternalUser {\n private String id;\n private List<Role> externalRoles = new ArrayList<>();\n}",
"public class PermissionResolutionException extends IntegrationException {\n public PermissionResolutionException(String message) {\n super(message);\n setRetryable(true);\n }\n\n public PermissionResolutionException(String message, Throwable cause) {\n super(message, cause);\n setRetryable(true);\n }\n}",
"public interface PermissionsRepository {\n\n /**\n * Adds the specified permission to the repository, overwriting anything under the same id.\n *\n * @param permission\n * @return This PermissionRepository\n */\n PermissionsRepository put(UserPermission permission);\n\n /**\n * Gets the UserPermission from the repository, if available. Returns an empty Optional if not\n * found.\n *\n * @param id\n * @return The UserPermission wrapped in an Optional.\n */\n Optional<UserPermission> get(String id);\n\n /** Gets all UserPermissions in the repository keyed by user ID. */\n Map<String, UserPermission> getAllById();\n\n /**\n * Gets all UserPermissions in the repository that has at least 1 of the specified roles, keyed by\n * user ID. Because this method is usually used in conjuction with updating/syncing the users in\n * question, the returned map will also contain the unrestricted user. If anyRoles is null,\n * returns the same result as getAllById() (which includes the unrestricted user). If anyRoles is\n * empty, this is an indication to sync only the anonymous/unrestricted user. When this is the\n * case, this method returns a map with a single entry for the unrestricted user.\n *\n * @param anyRoles\n * @return\n */\n Map<String, UserPermission> getAllByRoles(List<String> anyRoles);\n\n /**\n * Delete the specified user permission.\n *\n * @param id\n */\n void remove(String id);\n}",
"public interface PermissionsResolver {\n\n /** @return The UserPermission for an anonymous user. */\n UserPermission resolveUnrestrictedUser() throws PermissionResolutionException;\n\n /** Resolves a single user's permissions. */\n UserPermission resolve(String userId) throws PermissionResolutionException;\n\n /**\n * Resolves a single user's permissions, taking into account externally provided list of roles.\n */\n UserPermission resolveAndMerge(ExternalUser user) throws PermissionResolutionException;\n\n /** Resolves multiple user's permissions. Returned map is keyed by userId. */\n Map<String, UserPermission> resolve(Collection<ExternalUser> users)\n throws PermissionResolutionException;\n\n /** Clears resource cache: apps, service accounts,... */\n void clearCache();\n}",
"@Slf4j\n@Component\n@ConditionalOnExpression(\"${fiat.write-mode.enabled:true}\")\npublic class UserRolesSyncer {\n private final DiscoveryStatusListener discoveryStatusListener;\n\n private final LockManager lockManager;\n private final PermissionsRepository permissionsRepository;\n private final PermissionsResolver permissionsResolver;\n private final ResourceProvider<ServiceAccount> serviceAccountProvider;\n private final ResourceProvidersHealthIndicator healthIndicator;\n\n private final long retryIntervalMs;\n private final long syncDelayMs;\n private final long syncFailureDelayMs;\n private final long syncDelayTimeoutMs;\n\n private final Registry registry;\n private final Gauge userRolesSyncCount;\n\n @Autowired\n public UserRolesSyncer(\n DiscoveryStatusListener discoveryStatusListener,\n Registry registry,\n LockManager lockManager,\n PermissionsRepository permissionsRepository,\n PermissionsResolver permissionsResolver,\n ResourceProvider<ServiceAccount> serviceAccountProvider,\n ResourceProvidersHealthIndicator healthIndicator,\n @Value(\"${fiat.write-mode.retry-interval-ms:10000}\") long retryIntervalMs,\n @Value(\"${fiat.write-mode.sync-delay-ms:600000}\") long syncDelayMs,\n @Value(\"${fiat.write-mode.sync-failure-delay-ms:600000}\") long syncFailureDelayMs,\n @Value(\"${fiat.write-mode.sync-delay-timeout-ms:30000}\") long syncDelayTimeoutMs) {\n this.discoveryStatusListener = discoveryStatusListener;\n\n this.lockManager = lockManager;\n this.permissionsRepository = permissionsRepository;\n this.permissionsResolver = permissionsResolver;\n this.serviceAccountProvider = serviceAccountProvider;\n this.healthIndicator = healthIndicator;\n\n this.retryIntervalMs = retryIntervalMs;\n this.syncDelayMs = syncDelayMs;\n this.syncFailureDelayMs = syncFailureDelayMs;\n this.syncDelayTimeoutMs = syncDelayTimeoutMs;\n\n this.registry = registry;\n this.userRolesSyncCount = registry.gauge(metricName(\"syncCount\"));\n }\n\n @Scheduled(fixedDelay = 30000L)\n public void schedule() {\n if (syncDelayMs < 0 || !discoveryStatusListener.isEnabled()) {\n log.warn(\n \"User roles syncing is disabled (syncDelayMs: {}, isEnabled: {})\",\n syncDelayMs,\n discoveryStatusListener.isEnabled());\n return;\n }\n\n LockManager.LockOptions lockOptions =\n new LockManager.LockOptions()\n .withLockName(\"Fiat.UserRolesSyncer\".toLowerCase())\n .withMaximumLockDuration(Duration.ofMillis(syncDelayMs + syncDelayTimeoutMs))\n .withSuccessInterval(Duration.ofMillis(syncDelayMs))\n .withFailureInterval(Duration.ofMillis(syncFailureDelayMs));\n\n lockManager.acquireLock(\n lockOptions,\n () -> {\n try {\n timeIt(\"syncTime\", () -> userRolesSyncCount.set(this.syncAndReturn(new ArrayList<>())));\n } catch (Exception e) {\n log.error(\"User roles synchronization failed\", e);\n userRolesSyncCount.set(-1);\n }\n });\n }\n\n public long syncAndReturn(List<String> roles) {\n FixedBackOff backoff = new FixedBackOff();\n backoff.setInterval(retryIntervalMs);\n backoff.setMaxAttempts(Math.floorDiv(syncDelayTimeoutMs, retryIntervalMs) + 1);\n BackOffExecution backOffExec = backoff.start();\n\n // after this point the execution will get rescheduled\n final long timeout = System.currentTimeMillis() + syncDelayTimeoutMs;\n\n if (!isServerHealthy()) {\n log.warn(\n \"Server is currently UNHEALTHY. User permission role synchronization and \"\n + \"resolution may not complete until this server becomes healthy again.\");\n }\n\n // Ensure we're going to reload app and service account definitions\n permissionsResolver.clearCache();\n\n while (true) {\n try {\n Map<String, UserPermission> combo = new HashMap<>();\n // force a refresh of the unrestricted user in case the backing repository is empty:\n combo.put(UnrestrictedResourceConfig.UNRESTRICTED_USERNAME, new UserPermission());\n Map<String, UserPermission> temp;\n if (!(temp = getUserPermissions(roles)).isEmpty()) {\n combo.putAll(temp);\n }\n if (!(temp = getServiceAccountsAsMap(roles)).isEmpty()) {\n combo.putAll(temp);\n }\n\n return updateUserPermissions(combo);\n } catch (ProviderException | PermissionResolutionException ex) {\n registry\n .counter(metricName(\"syncFailure\"), \"cause\", ex.getClass().getSimpleName())\n .increment();\n Status status = healthIndicator.health().getStatus();\n long waitTime = backOffExec.nextBackOff();\n if (waitTime == BackOffExecution.STOP || System.currentTimeMillis() > timeout) {\n String cause = (waitTime == BackOffExecution.STOP) ? \"backoff-exhausted\" : \"timeout\";\n registry.counter(\"syncAborted\", \"cause\", cause).increment();\n log.error(\"Unable to resolve service account permissions.\", ex);\n return 0;\n }\n String message =\n new StringBuilder(\"User permission sync failed. \")\n .append(\"Server status is \")\n .append(status)\n .append(\". Trying again in \")\n .append(waitTime)\n .append(\" ms. Cause:\")\n .append(ex.getMessage())\n .toString();\n if (log.isDebugEnabled()) {\n log.debug(message, ex);\n } else {\n log.warn(message);\n }\n\n try {\n Thread.sleep(waitTime);\n } catch (InterruptedException ignored) {\n }\n } finally {\n isServerHealthy();\n }\n }\n }\n\n private boolean isServerHealthy() {\n return healthIndicator.health().getStatus() == Status.UP;\n }\n\n private Map<String, UserPermission> getServiceAccountsAsMap(List<String> roles) {\n List<UserPermission> allServiceAccounts =\n serviceAccountProvider.getAll().stream()\n .map(ServiceAccount::toUserPermission)\n .collect(Collectors.toList());\n if (roles == null || roles.isEmpty()) {\n return allServiceAccounts.stream()\n .collect(Collectors.toMap(UserPermission::getId, Function.identity()));\n } else {\n return allServiceAccounts.stream()\n .filter(p -> p.getRoles().stream().map(Role::getName).anyMatch(roles::contains))\n .collect(Collectors.toMap(UserPermission::getId, Function.identity()));\n }\n }\n\n private Map<String, UserPermission> getUserPermissions(List<String> roles) {\n if (roles == null || roles.isEmpty()) {\n return permissionsRepository.getAllById();\n } else {\n return permissionsRepository.getAllByRoles(roles);\n }\n }\n\n public long updateUserPermissions(Map<String, UserPermission> permissionsById) {\n if (permissionsById.remove(UnrestrictedResourceConfig.UNRESTRICTED_USERNAME) != null) {\n timeIt(\n \"syncAnonymous\",\n () -> {\n permissionsRepository.put(permissionsResolver.resolveUnrestrictedUser());\n log.info(\"Synced anonymous user role.\");\n });\n }\n\n List<ExternalUser> extUsers =\n permissionsById.values().stream()\n .map(\n permission ->\n new ExternalUser()\n .setId(permission.getId())\n .setExternalRoles(\n permission.getRoles().stream()\n .filter(role -> role.getSource() == Role.Source.EXTERNAL)\n .collect(Collectors.toList())))\n .collect(Collectors.toList());\n\n if (extUsers.isEmpty()) {\n log.info(\"Found no non-anonymous user roles to sync.\");\n return 0;\n }\n\n long count =\n timeIt(\n \"syncUsers\",\n () -> {\n Collection<UserPermission> values = permissionsResolver.resolve(extUsers).values();\n values.forEach(permissionsRepository::put);\n return values.size();\n });\n log.info(\"Synced {} non-anonymous user roles.\", count);\n return count;\n }\n\n private static String metricName(String name) {\n return \"fiat.userRoles.\" + name;\n }\n\n private void timeIt(String timerName, Runnable theThing) {\n Callable<Object> c =\n () -> {\n theThing.run();\n return null;\n };\n timeIt(timerName, c);\n }\n\n private <T> T timeIt(String timerName, Callable<T> theThing) {\n long startTime = System.nanoTime();\n String cause = null;\n try {\n return theThing.call();\n } catch (RuntimeException re) {\n cause = re.getClass().getSimpleName();\n throw re;\n } catch (Exception ex) {\n cause = ex.getClass().getSimpleName();\n throw new RuntimeException(ex);\n } finally {\n boolean success = cause == null;\n Id timer = registry.createId(metricName(timerName)).withTag(\"success\", success);\n registry\n .timer(success ? timer : timer.withTag(\"cause\", cause))\n .record(System.nanoTime() - startTime, TimeUnit.NANOSECONDS);\n }\n }\n}"
] | import com.netflix.spinnaker.fiat.model.UserPermission;
import com.netflix.spinnaker.fiat.model.resources.Role;
import com.netflix.spinnaker.fiat.permissions.ExternalUser;
import com.netflix.spinnaker.fiat.permissions.PermissionResolutionException;
import com.netflix.spinnaker.fiat.permissions.PermissionsRepository;
import com.netflix.spinnaker.fiat.permissions.PermissionsResolver;
import com.netflix.spinnaker.fiat.roles.UserRolesSyncer;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;
import lombok.NonNull;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController; | /*
* Copyright 2016 Google, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.fiat.controllers;
@Slf4j
@RestController
@RequestMapping("/roles")
@ConditionalOnExpression("${fiat.write-mode.enabled:true}")
public class RolesController {
@Autowired @Setter PermissionsResolver permissionsResolver;
@Autowired @Setter PermissionsRepository permissionsRepository;
@Autowired @Setter UserRolesSyncer syncer;
@RequestMapping(value = "/{userId:.+}", method = RequestMethod.POST)
public void putUserPermission(@PathVariable String userId) {
try {
UserPermission userPermission =
permissionsResolver.resolve(ControllerSupport.convert(userId));
log.debug(
"Updated user permissions (userId: {}, roles: {})",
userId,
userPermission.getRoles().stream().map(Role::getName).collect(Collectors.toList()));
permissionsRepository.put(userPermission);
} catch (PermissionResolutionException pre) {
throw new UserPermissionModificationException(pre);
}
}
@RequestMapping(value = "/{userId:.+}", method = RequestMethod.PUT)
public void putUserPermission(
@PathVariable String userId, @RequestBody @NonNull List<String> externalRoles) {
List<Role> convertedRoles =
externalRoles.stream()
.map(extRole -> new Role().setSource(Role.Source.EXTERNAL).setName(extRole))
.collect(Collectors.toList());
| ExternalUser extUser = | 2 |
374901588/PaperPlane | app/src/main/java/com/hut/zero/homepage/DoubanMomentPresenter.java | [
"public enum BeanType {\n\n TYPE_ZHIHU, TYPE_GUOKE,TYPE_DOUBAN;\n\n}",
"public class DoubanCache extends DataSupport {\n private int douban_id;\n private String douban_news;\n private float douban_time;\n private String douban_content;\n private boolean bookmark=false;\n\n public int getDouban_id() {\n return douban_id;\n }\n\n public void setDouban_id(int douban_id) {\n this.douban_id = douban_id;\n }\n\n public String getDouban_news() {\n return douban_news;\n }\n\n public void setDouban_news(String douban_news) {\n this.douban_news = douban_news;\n }\n\n public float getDouban_time() {\n return douban_time;\n }\n\n public void setDouban_time(float douban_time) {\n this.douban_time = douban_time;\n }\n\n public String getDouban_content() {\n return douban_content;\n }\n\n public void setDouban_content(String douban_content) {\n this.douban_content = douban_content;\n }\n\n public boolean isBookmark() {\n return bookmark;\n }\n\n public void setBookmark(boolean bookmark) {\n this.bookmark = bookmark;\n }\n\n @Override\n public String toString() {\n return \"douban_id=\"+douban_id+\",bookmark=\"+bookmark;\n }\n}",
"public class DoubanMomentNews {\n\n private int count;\n private ArrayList<Posts> posts;\n private int offset;\n private String date;\n private int total;\n\n public int getCount() {\n return count;\n }\n\n public void setCount(int count) {\n this.count = count;\n }\n\n public ArrayList<Posts> getPosts() {\n return posts;\n }\n\n public void setPosts(ArrayList<Posts> posts) {\n this.posts = posts;\n }\n\n public int getOffset() {\n return offset;\n }\n\n public void setOffset(int offset) {\n this.offset = offset;\n }\n\n public String getDate() {\n return date;\n }\n\n public void setDate(String date) {\n this.date = date;\n }\n\n public int getTotal() {\n return total;\n }\n\n public void setTotal(int total) {\n this.total = total;\n }\n\n public class Posts {\n\n private int display_style;\n private boolean is_editor_choice;\n private String published_time;\n private String url;\n private String short_url;\n private boolean is_liked;\n private author author;\n private String column;\n private int app_css;\n @SerializedName(\"abstract\")\n private String abs;\n private String date;\n private int like_count;\n private int comments_count;\n private ArrayList<thumbs> thumbs;\n private String created_time;\n private String title;\n private String share_pic_url;\n private String type;\n private int id;\n\n public class thumbs {\n medium medium;\n String description;\n large large;\n String tag_name;\n small small;\n int id;\n\n public Posts.medium getMedium() {\n return medium;\n }\n\n public void setMedium(Posts.medium medium) {\n this.medium = medium;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public Posts.large getLarge() {\n return large;\n }\n\n public void setLarge(Posts.large large) {\n this.large = large;\n }\n\n public String getTag_name() {\n return tag_name;\n }\n\n public void setTag_name(String tag_name) {\n this.tag_name = tag_name;\n }\n\n public Posts.small getSmall() {\n return small;\n }\n\n public void setSmall(Posts.small small) {\n this.small = small;\n }\n\n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n }\n\n public class small {\n String url;\n int width;\n int height;\n\n public String getUrl() {\n return url;\n }\n }\n\n public class medium {\n String url;\n int width;\n int height;\n\n public String getUrl() {\n return url;\n }\n }\n\n public class large {\n String url;\n int width;\n int height;\n\n public String getUrl() {\n return url;\n }\n }\n\n public int getDisplay_style() {\n return display_style;\n }\n\n public void setDisplay_style(int display_style) {\n this.display_style = display_style;\n }\n\n public boolean is_editor_choice() {\n return is_editor_choice;\n }\n\n public void setIs_editor_choice(boolean is_editor_choice) {\n this.is_editor_choice = is_editor_choice;\n }\n\n public String getPublished_time() {\n return published_time;\n }\n\n public void setPublished_time(String published_time) {\n this.published_time = published_time;\n }\n\n public String getUrl() {\n return url;\n }\n\n public void setUrl(String url) {\n this.url = url;\n }\n\n public String getShort_url() {\n return short_url;\n }\n\n public void setShort_url(String short_url) {\n this.short_url = short_url;\n }\n\n public boolean is_liked() {\n return is_liked;\n }\n\n public void setIs_liked(boolean is_liked) {\n this.is_liked = is_liked;\n }\n\n public DoubanMomentNews.author getAuthor() {\n return author;\n }\n\n public void setAuthor(DoubanMomentNews.author author) {\n this.author = author;\n }\n\n public String getColumn() {\n return column;\n }\n\n public void setColumn(String column) {\n this.column = column;\n }\n\n public int getApp_css() {\n return app_css;\n }\n\n public void setApp_css(int app_css) {\n this.app_css = app_css;\n }\n\n public String getAbs() {\n return abs;\n }\n\n public void setAbs(String abs) {\n this.abs = abs;\n }\n\n public String getDate() {\n return date;\n }\n\n public void setDate(String date) {\n this.date = date;\n }\n\n public int getLike_count() {\n return like_count;\n }\n\n public void setLike_count(int like_count) {\n this.like_count = like_count;\n }\n\n public int getComments_count() {\n return comments_count;\n }\n\n public void setComments_count(int comments_count) {\n this.comments_count = comments_count;\n }\n\n public ArrayList<thumbs> getThumbs() {\n return thumbs;\n }\n\n public void setThumbs(ArrayList<thumbs> thumbs) {\n this.thumbs = thumbs;\n }\n\n public String getCreated_time() {\n return created_time;\n }\n\n public void setCreated_time(String created_time) {\n this.created_time = created_time;\n }\n\n public String getTitle() {\n return title;\n }\n\n public void setTitle(String title) {\n this.title = title;\n }\n\n public String getShare_pic_url() {\n return share_pic_url;\n }\n\n public void setShare_pic_url(String share_pic_url) {\n this.share_pic_url = share_pic_url;\n }\n\n public String getType() {\n return type;\n }\n\n public void setType(String type) {\n this.type = type;\n }\n\n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n }\n\n private class author {\n boolean is_followed;\n String uid;\n String url;\n String avatar;\n String name;\n boolean is_special_user;\n int n_posts;\n String alt;\n String large_avatar;\n String id;\n boolean is_auth_author;\n }\n\n}",
"public class DetailActivity extends AppCompatActivity {\n private DetailFragment fragment;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.frame);\n\n if (savedInstanceState != null) {\n fragment = (DetailFragment) getSupportFragmentManager().getFragment(savedInstanceState,\"detailFragment\");\n } else {\n fragment = new DetailFragment();\n getSupportFragmentManager().beginTransaction()\n .replace(R.id.container, fragment)\n .commit();\n }\n\n Intent intent = getIntent();\n DetailPresenter presenter = new DetailPresenter(DetailActivity.this, fragment);\n presenter.setType((BeanType) intent.getSerializableExtra(\"type\"));\n presenter.setId(intent.getIntExtra(\"id\", 0));\n presenter.setTitle(intent.getStringExtra(\"title\"));\n presenter.setCoverUrl(intent.getStringExtra(\"coverUrl\"));\n presenter.logMsg();\n }\n\n @Override\n protected void onSaveInstanceState(Bundle outState) {\n super.onSaveInstanceState(outState);\n if (fragment.isAdded()) {\n getSupportFragmentManager().putFragment(outState, \"detailFragment\", fragment);\n }\n }\n}",
"public class DoubanModelImpl {\n\n public void load(String date, retrofit2.Callback<DoubanMomentNews> callback) {\n DoubanService.SERVICE.loadMoment(date).enqueue(callback);\n }\n\n public void loadArticleDetail(String id, retrofit2.Callback<DoubanMomentStory> callback) {\n DoubanService.SERVICE.loadArticleDetail(id).enqueue(callback);\n }\n\n public void loadArticleDetailForResponeBody(String id, retrofit2.Callback<ResponseBody> callback) {\n DoubanService.SERVICE.loadArticleDetailForResponseBody(id).enqueue(callback);\n }\n}",
"public class CacheService extends Service {\n public static final int TYPE_ZHIHU = 0x00;\n public static final int TYPE_GUOKE = 0x01;\n public static final int TYPE_DOUBAN = 0x02;\n\n private LocalBroadcastManager manager;\n private LocalReceiver localReceiver = new LocalReceiver();\n\n @Override\n public void onCreate() {\n IntentFilter filter = new IntentFilter();\n filter.addAction(\"com.hut.zero.LOCAL_BROADCAST\");\n manager = LocalBroadcastManager.getInstance(this);\n localReceiver = new LocalReceiver();\n manager.registerReceiver(localReceiver, filter);\n }\n\n @Nullable\n @Override\n public IBinder onBind(Intent intent) {\n return null;\n }\n\n @Override\n public int onStartCommand(Intent intent, int flags, int startId) {\n return super.onStartCommand(intent, flags, startId);\n }\n\n @Override\n public boolean onUnbind(Intent intent) {\n return super.onUnbind(intent);\n }\n\n /**\n * 网络请求id对应的知乎日报的内容主体\n * 当type为0时,存储body中的数据\n * 当type为1时,再次请求share url中的内容并储存\n *\n * @param id 所要获取的知乎日报消息内容对应的id\n */\n private void startZhihuCache(final int id) {\n ZhihuCache cache=DataSupport.select(\"zhihu_content\").where(\"zhihu_id = ?\",\"\"+id).findFirst(ZhihuCache.class);\n if (cache!=null && TextUtils.isEmpty(cache.getZhihu_content())) {\n ZhihuService.SERVICE_NEWS.loadNews(id+\"\").enqueue(new Callback<ResponseBody>() {\n @Override\n public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response1) {\n try {\n String s1=response1.body().string();\n ZhihuDailyStory zhihuDailyStory= new Gson().fromJson(s1, ZhihuDailyStory.class);\n if (zhihuDailyStory.getType()==1) {\n CommonService.SERVICE_DYNAMIC_URL.loadDynamic(zhihuDailyStory.getShare_url()).enqueue(new Callback<ResponseBody>() {\n @Override\n public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response2) {\n try {\n String s2 = response2.body().string();\n ContentValues values = new ContentValues();\n values.put(\"zhihu_content\",s2);\n DataSupport.updateAll(ZhihuCache.class, values, \"zhihu_id = ?\", \"\"+id);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n @Override\n public void onFailure(Call<ResponseBody> call, Throwable t) {\n Log.d(\"CacheService===>\\n\",\"startZhihuCache()->CommonService.SERVICE_DYNAMIC_URL.loadDynamic()请求失败!\");\n }\n });\n } else {\n ContentValues values = new ContentValues();\n values.put(\"zhihu_content\",s1);\n DataSupport.updateAll(ZhihuCache.class, values, \"zhihu_id = ?\", \"\" + id);\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n @Override\n public void onFailure(Call<ResponseBody> call, Throwable t) {\n Log.d(\"CacheService===>\\n\",\"startZhihuCache()->ZhihuService.SERVICE_NEWS.loadNews()请求失败!\");\n }\n });\n }\n }\n\n class LocalReceiver extends BroadcastReceiver {\n\n @Override\n public void onReceive(Context context, Intent intent) {\n int id = intent.getIntExtra(\"id\", 0);\n switch (intent.getIntExtra(\"type\", -1)) {\n case TYPE_ZHIHU:\n startZhihuCache(id);\n break;\n case TYPE_GUOKE:\n startGuokeCache(id);\n break;\n case TYPE_DOUBAN:\n startDoubanCache(id);\n break;\n default:\n case -1:\n break;\n }\n }\n\n\n }\n\n private void startDoubanCache(final int id) {\n DoubanCache cache=DataSupport.select(\"douban_content\").where(\"douban_id = ?\",\"\"+id).findFirst(DoubanCache.class);\n if (cache!=null && TextUtils.isEmpty(cache.getDouban_content())) {\n new Retrofit.Builder()\n .baseUrl(\"https://moment.douban.com/\")\n .client(new OkHttpClient.Builder()\n .retryOnConnectionFailure(true)//设置失败重试\n .build())\n .build().create(DoubanService.class)\n .loadArticleDetailForResponseBody(\"\" + id)\n .enqueue(new Callback<ResponseBody>() {\n @Override\n public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {\n try {\n String s = response.body().string();\n ContentValues values = new ContentValues();\n values.put(\"douban_content\", s);\n DataSupport.updateAll(DoubanCache.class, values, \"douban_id = ?\", id + \"\");\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n }\n\n @Override\n public void onFailure(Call<ResponseBody> call, Throwable t) {\n Log.d(\"CacheService===>\\n\",\"startDoubanCache()->DoubanService-loadArticleDetailForResponseBody()请求失败!\");\n }\n });\n }\n }\n\n private void deleteTimeoutPosts() {\n\n SharedPreferences sp = getSharedPreferences(SettingsPreferenceActivity.SETTINGS_CONFIG_FILE_NAME, MODE_PRIVATE);\n\n long timeStamp = (Calendar.getInstance().getTimeInMillis() / 1000) - Long.parseLong(sp.getString(\"time_of_saving_articles\", \"7\")) * 24 * 60 * 60;\n DataSupport.deleteAll(ZhihuCache.class, \"zhihu_time < ? and bookmark != 1\", \"\"+timeStamp);\n DataSupport.deleteAll(DoubanCache.class, \"douban_time < ? and bookmark != 1\", \"\"+timeStamp);\n DataSupport.deleteAll(GuokeCache.class, \"guoke_time < ? and bookmark != 1\", \"\"+timeStamp);\n }\n\n private void startGuokeCache(final int id) {\n GuokeCache cache=DataSupport.select(\"guoke_content\").where(\"guoke_id = ?\",\"\"+id).findFirst(GuokeCache.class);\n if (cache!=null && TextUtils.isEmpty(cache.getGuoke_content())) {\n GuokeService.SERVICE_JINGXUAN.loadJingxuan(id+\"\").enqueue(new Callback<ResponseBody>() {\n @Override\n public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {\n try {\n String s = response.body().string();\n ContentValues values = new ContentValues();\n values.put(\"guoke_content\", s);\n DataSupport.updateAll(GuokeCache.class, values, \"guoke_id = ?\", id + \"\");\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n @Override\n public void onFailure(Call<ResponseBody> call, Throwable t) {\n Log.d(\"CacheService===>\\n\",\"startGuokeCache()->GuokeService.SERVICE_JINGXUAN.loadJingxuan()请求失败!\");\n }\n });\n }\n }\n\n @Override\n public void onDestroy() {\n super.onDestroy();\n manager.unregisterReceiver(localReceiver);\n deleteTimeoutPosts();\n }\n\n}",
"public class DateFormatter {\n\n /**\n * 将long类date转换为String类型\n * @param date date\n * @return String date\n */\n public String ZhihuDailyDateFormat(long date) {\n String sDate;\n Date d = new Date(date + 24*60*60*1000);\n SimpleDateFormat format = new SimpleDateFormat(\"yyyyMMdd\");\n sDate = format.format(d);\n return sDate;\n }\n\n public String DoubanDateFormat(long date){\n String sDate;\n Date d = new Date(date);\n SimpleDateFormat format = new SimpleDateFormat(\"yyyy-MM-dd\");\n sDate = format.format(d);\n return sDate;\n }\n\n}",
"public class NetworkState {\n\n // 检查是否连接到网络\n // whether connect to internet\n public static boolean networkConnected(Context context){\n\n if (context != null){\n ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);\n NetworkInfo info = manager.getActiveNetworkInfo();\n if (info != null)\n return info.isAvailable();\n }\n\n return false;\n }\n\n // 检查WiFi是否连接\n // if wifi connect\n public static boolean wifiConnected(Context context){\n if (context != null){\n ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);\n NetworkInfo info = manager.getActiveNetworkInfo();\n if (info != null){\n if (info.getType() == ConnectivityManager.TYPE_WIFI)\n return info.isAvailable();\n }\n }\n return false;\n }\n\n // 检查移动网络是否连接\n // if mobile data connect\n public static boolean mobileDataConnected(Context context){\n if (context != null){\n ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);\n NetworkInfo info = manager.getActiveNetworkInfo();\n if (info != null){\n if (info.getType() == ConnectivityManager.TYPE_MOBILE)\n return true;\n }\n }\n return false;\n }\n\n}"
] | import android.content.Context;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.hut.zero.bean.BeanType;
import com.hut.zero.bean.DoubanCache;
import com.hut.zero.bean.DoubanMomentNews;
import com.hut.zero.detail.DetailActivity;
import com.hut.zero.model.DoubanModelImpl;
import com.hut.zero.service.CacheService;
import com.hut.zero.util.DateFormatter;
import com.hut.zero.util.NetworkState;
import org.litepal.crud.DataSupport;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response; | package com.hut.zero.homepage;
/**
* Created by Zero on 2017/4/2.
*/
public class DoubanMomentPresenter implements DoubanMomentContract.Presenter {
private Context mContext;
private DoubanMomentContract.View mView;
private Gson gson=new Gson();
| private DoubanModelImpl model; | 4 |
aolshevskiy/songo | src/main/java/songo/MainModule.java | [
"public class LoggingTypeListener implements TypeListener {\n\t@Override\n\tpublic <I> void hear(TypeLiteral<I> aTypeLiteral, TypeEncounter<I> aTypeEncounter) {\n\t\tfor(Field field : aTypeLiteral.getRawType().getDeclaredFields()) {\n\t\t\tif(field.getType() == Logger.class && field.isAnnotationPresent(InjectLogger.class)) {\n\t\t\t\taTypeEncounter.register(new LoggingMembersInjector<I>(field));\n\t\t\t}\n\t\t}\n\t}\n}",
"@Singleton\npublic class Configuration {\n\tprivate static final File CONFIGURATION_FILE = new File(HOME_DIR, \"configuration.properties\");\n\tprivate Properties props;\n\n\t@Inject\n\tConfiguration() {\n\t\tload();\n\t}\n\n\tprivate void load() {\n\t\tprops = new Properties();\n\t\tif(!CONFIGURATION_FILE.exists())\n\t\t\treturn;\n\t\ttry {\n\t\t\tprops.load(new FileInputStream(CONFIGURATION_FILE));\n\t\t} catch (IOException e) {\n\t\t\tthrow Throwables.propagate(e);\n\t\t}\n\t}\n\n\tprivate void save() {\n\t\ttry {\n\t\t\tprops.store(new FileOutputStream(CONFIGURATION_FILE), \"\");\n\t\t} catch (IOException e) {\n\t\t\tthrow Throwables.propagate(e);\n\t\t}\n\t}\n\n\tpublic boolean isAuthorized() {\n\t\treturn props.getProperty(\"vk.accessToken\") != null;\n\t}\n\n\tpublic void setAccessToken(String token) {\n\t\tprops.setProperty(\"vk.accessToken\", token);\n\t\tsave();\n\t}\n\n\tpublic String getAccessToken() {\n\t\treturn props.getProperty(\"vk.accessToken\");\n\t}\n}",
"@SessionScoped\npublic class Playlist {\n\tprivate List<Audio> tracks = ImmutableList.of();\n\tprivate int currentTrackIndex = -1;\n\tprivate final EventBus bus;\n\n\tpublic List<Audio> getTracks() {\n\t\treturn tracks;\n\t}\n\n\tpublic void setTracks(List<Audio> tracks) {\n\t\tAudio track = getCurrentTrack();\n\t\tthis.tracks = tracks;\n\t\tfixCurrentTrack(track);\n\t\tchanged();\n\t}\n\n\tprivate void fixCurrentTrack(Audio track) {\n\t\tcurrentTrackIndex = -1;\n\t\tint i = 0;\n\t\tfor(Audio t : tracks) {\n\t\t\tif(t == track) {\n\t\t\t\tcurrentTrackIndex = i;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\ti++;\n\t\t}\n\t}\n\n\tpublic Audio getCurrentTrack() {\n\t\tif(currentTrackIndex == -1)\n\t\t\treturn null;\n\t\treturn tracks.get(currentTrackIndex);\n\t}\n\n\tpublic int getCurrentTrackIndex() {\n\t\treturn currentTrackIndex;\n\t}\n\n\tpublic void setCurrentTrackIndex(int currentTrackIndex) {\n\t\tthis.currentTrackIndex = currentTrackIndex;\n\t\tchanged();\n\t}\n\n\t@Inject\n\tPlaylist(@GlobalBus EventBus bus) {\n\t\tthis.bus = bus;\n\t}\n\n\tpublic void add(List<Audio> newTracks) {\n\t\ttracks = new ImmutableList.Builder<Audio>().addAll(tracks).addAll(newTracks).build();\n\t\tchanged();\n\t}\n\n\tpublic void replace(List<Audio> selectedTracks) {\n\t\ttracks = selectedTracks;\n\t\tcurrentTrackIndex = -1;\n\t\tchanged();\n\t}\n\n\tpublic void remove(int[] indices) {\n\t\tAudio current = getCurrentTrack();\n\t\tArrayList<Audio> view = Lists.newArrayList(tracks);\n\t\tfor(int i = indices.length - 1; i >= 0; i--)\n\t\t\tview.remove(indices[i]);\n\t\ttracks = ImmutableList.copyOf(view);\n\t\tfixCurrentTrack(current);\n\t\tchanged();\n\t}\n\n\tprivate void changed() {\n\t\tbus.post(new Changed());\n\t}\n\n\tpublic static class Changed {\n\t\tprivate Changed() { }\n\t}\n}",
"public interface Mpg123Native extends Library {\n\tint mpg123_init();\n\n\tvoid mpg123_exit();\n\n\tPointer mpg123_new(String decoder, IntByReference err);\n\n\tint mpg123_close(Pointer handle);\n\n\tint mpg123_delete(Pointer handle);\n\n\tint mpg123_open_feed(Pointer handle);\n\n\tint mpg123_decode(Pointer handle, byte[] inmem, int inmemsize, byte[] outmem, int outmemsize, IntByReference done);\n\n\tint mpg123_getformat(Pointer handle, IntByReference rate, IntByReference channels, IntByReference encoding);\n\n\tint mpg123_set_filesize(Pointer handle, int size);\n\n\tint mpg123_length(Pointer handle);\n\n\tint mpg123_tell(Pointer handle);\n\n\tint mpg123_feedseek(Pointer handle, int sampleoff, int whence, IntByReference input_offset);\n\n\tint mpg123_tell_stream(Pointer handle);\n}",
"@SessionScoped\npublic class MainView implements View {\n\tprivate final Shell shell;\n\tprivate final SWTUtil util;\n\tprivate final TabItem searchTab;\n\tprivate final TabItem playlistTab;\n\tprivate final ShellAdapter hideOnClose;\n\n\tpublic TabItem getSearchTab() {\n\t\treturn searchTab;\n\t}\n\n\tpublic TabItem getPlaylistTab() {\n\t\treturn playlistTab;\n\t}\n\n\t@Inject\n\tMainView(final Shell shell, SWTUtil util, TrayView trayView, @SessionBus EventBus bus) {\n\t\tthis.shell = shell;\n\t\tthis.util = util;\n\t\tbus.register(this);\n\t\thideOnClose = new ShellAdapter() {\n\t\t\t@Override\n\t\t\tpublic void shellClosed(ShellEvent shellEvent) {\n\t\t\t\tshell.setVisible(false);\n\t\t\t\tshellEvent.doit = false;\n\t\t\t}\n\t\t};\n\t\tshell.addShellListener(hideOnClose);\n\t\tshell.setText(\"Songo\");\n\t\tshell.setLayout(new GridLayout());\n\t\tTabFolder tabs = new TabFolder(shell, SWT.NONE);\n\t\ttabs.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));\n\t\tplaylistTab = new TabItem(tabs, SWT.NONE);\n\t\tplaylistTab.setText(\"Playlist\");\n\t\tsearchTab = new TabItem(tabs, SWT.NONE);\n\t\tsearchTab.setText(\"Search\");\n\t\ttabs.setSelection(1);\n\t\ttrayView.setShell(shell);\n\t}\n\n\t@Subscribe\n\tpublic void restore(TrayView.Restore e) {\n\t\tshell.setVisible(!shell.getVisible());\n\t}\n\n\t@Subscribe\n\tpublic void close(TrayView.Exit e) {\n\t\tshell.removeShellListener(hideOnClose);\n\t\tutil.exitOnClose(shell);\n\t\tshell.close();\n\t}\n\n\t@Override\n\tpublic Shell getShell() {\n\t\treturn shell;\n\t}\n}"
] | import com.google.common.eventbus.EventBus;
import com.google.inject.*;
import com.google.inject.assistedinject.FactoryModuleBuilder;
import com.google.inject.matcher.Matchers;
import com.google.inject.servlet.SessionScoped;
import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.AsyncHttpClientConfig;
import com.sun.jna.Native;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TabItem;
import songo.annotation.*;
import songo.logging.LoggingTypeListener;
import songo.model.Configuration;
import songo.model.Playlist;
import songo.model.streams.*;
import songo.mpg123.Mpg123Native;
import songo.view.MainView;
import songo.vk.*;
import javax.annotation.Nullable;
import java.io.File;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; | package songo;
public class MainModule extends AbstractModule {
private static int getNativeBrowserStyle() {
if(System.getProperty("os.name").equals("Linux"))
return SWT.WEBKIT;
return SWT.NONE;
}
private static boolean isRunningWindows() {
return System.getProperty("os.name").toLowerCase().contains("windows");
}
@Override
protected void configure() {
bind(Boolean.class).annotatedWith(RunningWindows.class).toInstance(isRunningWindows());
SimpleScope sessionScope = new SimpleScope();
bindScope(SessionScoped.class, sessionScope);
bind(SimpleScope.class).annotatedWith(SessionScope.class).toInstance(sessionScope);
bind(EventBus.class).annotatedWith(GlobalBus.class).to(EventBus.class).in(Singleton.class);
bind(EventBus.class).annotatedWith(SessionBus.class).to(EventBus.class).in(SessionScoped.class);
bind(String.class).annotatedWith(VkAppId.class).toInstance("3192319");
bind(String.class).annotatedWith(VkRegisterUrl.class).toInstance("http://vk.com/join");
bind(Integer.class).annotatedWith(BrowserStyle.class).toInstance(getNativeBrowserStyle());
bind(Stream.class).toProvider(StreamProvider.class);
install(
new FactoryModuleBuilder()
.implement(RemoteStream.class, RemoteStream.class)
.implement(LocalStream.class, LocalStream.class)
.build(StreamFactory.class));
bindListener(Matchers.any(), new LoggingTypeListener());
}
@Provides
@VkAuthUrl
@Singleton
String provideAuthUrl(@VkAppId String appId) {
return "https://oauth.vk.com/authorize?client_id=" + appId + "&scope=audio,offline&redirect_url=http://oauth.vk.com/blank.html&display=popup&response_type=token";
}
@Provides
Display provideDisplay(SongoService service) {
return service.getDisplay();
}
@Provides
Shell provideShell(Display display) {
return new Shell(display);
}
@Provides
@VkAccessToken | String provideAccessToken(Configuration configuration) { | 1 |
EndlessCodeGroup/RPGInventory | src/main/java/ru/endlesscode/rpginventory/inventory/craft/CraftManager.java | [
"public class RPGInventory extends PluginLifecycle {\n private static RPGInventory instance;\n\n private Permission perms;\n private Economy economy;\n\n private BukkitLevelSystem.Provider levelSystemProvider;\n private BukkitClassSystem.Provider classSystemProvider;\n\n private FileLanguage language;\n private boolean placeholderApiHooked = false;\n private boolean myPetHooked = false;\n private ResourcePackModule resourcePackModule = null;\n\n public static RPGInventory getInstance() {\n return instance;\n }\n\n public static FileLanguage getLanguage() {\n return instance.language;\n }\n\n public static Permission getPermissions() {\n return instance.perms;\n }\n\n public static Economy getEconomy() {\n return instance.economy;\n }\n\n @Contract(pure = true)\n public static boolean economyConnected() {\n return instance.economy != null;\n }\n\n @Contract(pure = true)\n public static boolean isPlaceholderApiHooked() {\n return instance.placeholderApiHooked;\n }\n\n @Contract(pure = true)\n public static boolean isMyPetHooked() {\n return instance.myPetHooked;\n }\n\n public static BukkitLevelSystem getLevelSystem(@NotNull Player player) {\n return instance.levelSystemProvider.getSystem(player);\n }\n\n public static BukkitClassSystem getClassSystem(@NotNull Player player) {\n return instance.classSystemProvider.getSystem(player);\n }\n\n @Nullable\n public static ResourcePackModule getResourcePackModule() {\n return instance.resourcePackModule;\n }\n\n @Override\n public void init() {\n instance = this;\n Log.init(this.getLogger());\n Config.init(this);\n }\n\n @Override\n public void onLoad() {\n if (checkMimic()) {\n getServer()\n .getServicesManager()\n .register(BukkitItemsRegistry.class, new RPGInventoryItemsRegistry(), this, ServicePriority.High);\n }\n }\n\n @Override\n public void onEnable() {\n if (!initMimicSystems()) {\n return;\n }\n\n loadConfigs();\n Serialization.registerTypes();\n\n if (!this.checkRequirements()) {\n this.getPluginLoader().disablePlugin(this);\n return;\n }\n\n PluginManager pm = this.getServer().getPluginManager();\n\n // Hook Placeholder API\n if (pm.isPluginEnabled(\"PlaceholderAPI\")) {\n new StringUtils.Placeholders().register();\n placeholderApiHooked = true;\n Log.i(\"Placeholder API hooked!\");\n } else {\n placeholderApiHooked = false;\n }\n\n loadModules();\n\n this.loadPlayers();\n this.startMetrics();\n\n // Enable commands\n this.getCommand(\"rpginventory\")\n .setExecutor(new TrackedCommandExecutor(new RPGInventoryCommandExecutor(), getReporter()));\n\n this.checkUpdates(null);\n }\n\n private boolean initMimicSystems() {\n boolean isMimicFound = checkMimic();\n if (isMimicFound) {\n ServicesManager servicesManager = getServer().getServicesManager();\n this.levelSystemProvider = servicesManager.load(BukkitLevelSystem.Provider.class);\n Log.i(\"Level system ''{0}'' found.\", this.levelSystemProvider.getId());\n this.classSystemProvider = servicesManager.load(BukkitClassSystem.Provider.class);\n Log.i(\"Class system ''{0}'' found.\", this.classSystemProvider.getId());\n } else {\n Log.s(\"Mimic is required for RPGInventory to use levels and classes from other RPG plugins!\");\n Log.s(\"Download it from SpigotMC: https://www.spigotmc.org/resources/82515/\");\n getServer().getPluginManager().disablePlugin(this);\n }\n return isMimicFound;\n }\n\n void reload() {\n // Unload\n saveData();\n removeListeners();\n\n // Load\n loadConfigs();\n loadModules();\n loadPlayers();\n }\n\n private void loadConfigs() {\n this.updateConfig();\n Config.reload();\n language = new FileLanguage(this);\n }\n\n private void loadModules() {\n PluginManager pm = getServer().getPluginManager();\n\n // Hook MyPet\n if (pm.isPluginEnabled(\"MyPet\") && MyPetManager.init(this)) {\n myPetHooked = true;\n Log.i(\"MyPet used as pet system\");\n } else {\n myPetHooked = false;\n Log.i(PetManager.init(this) ? \"Pet system is enabled\" : \"Pet system isn''t loaded\");\n }\n\n // Load modules\n Log.i(CraftManager.init(this) ? \"Craft extensions is enabled\" : \"Craft extensions isn''t loaded\");\n Log.i(InventoryLocker.init(this) ? \"Inventory lock system is enabled\" : \"Inventory lock system isn''t loaded\");\n Log.i(ItemManager.init(this) ? \"Item system is enabled\" : \"Item system isn''t loaded\");\n Log.i(BackpackManager.init(this) ? \"Backpack system is enabled\" : \"Backpack system isn''t loaded\");\n\n // Registering other listeners\n pm.registerEvents(new ArmorEquipListener(), this);\n pm.registerEvents(new HandSwapListener(), this);\n pm.registerEvents(new PlayerListener(), this);\n pm.registerEvents(new WorldListener(), this);\n\n if (SlotManager.instance().getElytraSlot() != null) {\n pm.registerEvents(new ElytraListener(), this);\n }\n this.resourcePackModule = ResourcePackModule.init(this);\n }\n\n private void removeListeners() {\n ProtocolLibrary.getProtocolManager().removePacketListeners(this);\n HandlerList.unregisterAll(this);\n }\n\n private boolean checkMimic() {\n if (getServer().getPluginManager().getPlugin(\"Mimic\") == null) {\n return false;\n } else if (MimicApiLevel.checkApiLevel(MimicApiLevel.VERSION_0_6)) {\n return true;\n } else {\n Log.w(\"At least Mimic 0.6.1 required for RPGInventory.\");\n return false;\n }\n }\n\n private boolean checkRequirements() {\n // Check if plugin is enabled\n if (!Config.getConfig().getBoolean(\"enabled\")) {\n Log.w(\"RPGInventory is disabled in the config!\");\n return false;\n }\n\n // Check version compatibility\n if (VersionHandler.isNotSupportedVersion()) {\n Log.w(\"This version of RPG Inventory is not tested with \\\"{0}\\\"!\", Bukkit.getBukkitVersion());\n } else if (VersionHandler.isExperimentalSupport()) {\n Log.w(\"Support of {0} is experimental! Use RPGInventory with caution.\", Bukkit.getBukkitVersion());\n }\n\n // Check dependencies\n if (this.setupPermissions()) {\n Log.i(\"Permissions hooked: {0}\", perms.getName());\n } else {\n Log.s(\"Permissions not found!\");\n return false;\n }\n\n if (this.setupEconomy()) {\n Log.i(\"Economy hooked: {0}\", economy.getName());\n } else {\n Log.w(\"Economy not found!\");\n }\n\n return InventoryManager.init(this) && SlotManager.init();\n }\n\n @Override\n public void onDisable() {\n saveData();\n }\n\n private void saveData() {\n BackpackManager.saveBackpacks();\n this.savePlayers();\n }\n\n private void startMetrics() {\n new Metrics(holder, 4210);\n }\n\n private void savePlayers() {\n if (this.getServer().getOnlinePlayers().size() == 0) {\n return;\n }\n\n Log.i(\"Saving players inventories...\");\n for (Player player : this.getServer().getOnlinePlayers()) {\n InventoryManager.unloadPlayerInventory(player);\n }\n }\n\n private void loadPlayers() {\n if (this.getServer().getOnlinePlayers().size() == 0) {\n return;\n }\n\n Log.i(\"Loading players inventories...\");\n for (Player player : this.getServer().getOnlinePlayers()) {\n InventoryManager.loadPlayerInventory(player);\n }\n }\n\n private boolean setupPermissions() {\n RegisteredServiceProvider<Permission> permissionProvider = getServer().getServicesManager().getRegistration(Permission.class);\n if (permissionProvider != null) {\n perms = permissionProvider.getProvider();\n }\n\n return perms != null;\n }\n\n private boolean setupEconomy() {\n RegisteredServiceProvider<Economy> rsp = this.getServer().getServicesManager().getRegistration(Economy.class);\n if (rsp != null) {\n economy = rsp.getProvider();\n }\n\n return economy != null;\n }\n\n public void checkUpdates(@Nullable final Player player) {\n if (!Config.getConfig().getBoolean(\"check-update\")) {\n return;\n }\n\n new TrackedBukkitRunnable() {\n @Override\n public void run() {\n Updater updater = new Updater(RPGInventory.instance, Updater.UpdateType.NO_DOWNLOAD);\n if (updater.getResult() == Updater.UpdateResult.UPDATE_AVAILABLE) {\n String[] lines = {\n StringUtils.coloredLine(\"&3=================&b[&eRPGInventory&b]&3===================\"),\n StringUtils.coloredLine(\"&6New version available: &a\" + updater.getLatestName() + \"&6!\"),\n StringUtils.coloredLine(updater.getDescription()),\n StringUtils.coloredLine(\"&6Changelog: &e\" + updater.getInfoLink()),\n StringUtils.coloredLine(\"&6Download it on &eSpigotMC&6!\"),\n StringUtils.coloredLine(\"&3==================================================\")\n };\n\n for (String line : lines) {\n if (player == null) {\n StringUtils.coloredConsole(line);\n } else {\n PlayerUtils.sendMessage(player, line);\n }\n }\n }\n }\n }.runTaskAsynchronously(RPGInventory.getInstance());\n }\n\n private void updateConfig() {\n final Version version = Version.parseVersion(this.getDescription().getVersion());\n\n if (!Config.getConfig().contains(\"version\")) {\n Config.getConfig().set(\"version\", version.toString());\n Config.save();\n return;\n }\n\n final Version configVersion = Version.parseVersion(Config.getConfig().getString(\"version\"));\n if (version.compareTo(configVersion) > 0) {\n ConfigUpdater.update(configVersion);\n Config.getConfig().set(\"version\", null);\n Config.getConfig().set(\"version\", version.toString());\n Config.save();\n }\n }\n\n @NotNull\n public Path getDataPath() {\n return getDataFolder().toPath();\n }\n}",
"public class VersionHandler {\n\n public static final int VERSION_1_11 = 1_11_00;\n public static final int VERSION_1_12 = 1_12_00;\n public static final int VERSION_1_13 = 1_13_00;\n public static final int VERSION_1_14 = 1_14_00;\n public static final int VERSION_1_15 = 1_15_00;\n public static final int VERSION_1_16 = 1_16_00;\n public static final int VERSION_1_17 = 1_17_00;\n public static final int VERSION_1_18 = 1_18_00;\n\n private static final Pattern pattern = Pattern.compile(\"(?<version>\\\\d\\\\.\\\\d{1,2}(\\\\.\\\\d)?)-.*\");\n\n private static int versionCode = -1;\n\n public static boolean isNotSupportedVersion() {\n return getVersionCode() < VERSION_1_14 || getVersionCode() >= VERSION_1_18;\n }\n\n public static boolean isExperimentalSupport() {\n return getVersionCode() == VERSION_1_17;\n }\n\n public static boolean isLegacy() {\n return getVersionCode() < VERSION_1_13;\n }\n\n public static int getVersionCode() {\n if (versionCode == -1) {\n initVersionCode();\n }\n\n return versionCode;\n }\n\n private static void initVersionCode() {\n Matcher matcher = pattern.matcher(Bukkit.getBukkitVersion());\n if (matcher.find()) {\n String versionString = matcher.group(\"version\");\n versionCode = Version.parseVersion(versionString).getVersionCode();\n } else {\n versionCode = 0;\n }\n }\n}",
"public class CraftListener extends PacketAdapter implements Listener {\n\n public CraftListener(@NotNull Plugin plugin) {\n super(plugin, WrapperPlayServerWindowItems.TYPE);\n\n plugin.getServer().getPluginManager().registerEvents(this, plugin);\n }\n\n @Override\n public void onPacketSending(@NotNull PacketEvent event) {\n Player player = event.getPlayer();\n if (event.isCancelled() || !InventoryManager.playerIsLoaded(player)\n || isExtensionsNotNeededHere(player)) {\n return;\n }\n\n WrapperPlayServerWindowItems packet = new WrapperPlayServerWindowItems(event.getPacket());\n if (player.getOpenInventory().getType() == InventoryType.WORKBENCH) {\n List<ItemStack> contents = packet.getSlotData();\n\n List<CraftExtension> extensions = CraftManager.getExtensions(player);\n for (CraftExtension extension : extensions) {\n for (int slot : extension.getSlots()) {\n contents.set(slot, extension.getCapItem());\n }\n }\n\n packet.setSlotData(contents);\n }\n }\n\n @EventHandler(priority = EventPriority.LOW)\n public void onInventoryOpen(@NotNull InventoryOpenEvent event) {\n final Player player = (Player) event.getPlayer();\n if (!InventoryManager.playerIsLoaded(player)\n || event.getInventory().getType() != InventoryType.WORKBENCH\n || isExtensionsNotNeededHere(player)) {\n return;\n }\n\n //noinspection deprecation\n player.updateInventory();\n }\n\n @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH)\n public void onInventoryClick(@NotNull InventoryClickEvent event) {\n final Player player = (Player) event.getWhoClicked();\n if (!InventoryManager.playerIsLoaded(player)\n || event.getInventory().getType() != InventoryType.WORKBENCH\n || isExtensionsNotNeededHere(player)) {\n return;\n }\n\n List<CraftExtension> extensions = CraftManager.getExtensions(player);\n for (CraftExtension extension : extensions) {\n for (int slot : extension.getSlots()) {\n if (slot == event.getRawSlot()) {\n event.setCancelled(true);\n PlayerUtils.updateInventory(player);\n return;\n }\n }\n }\n }\n\n /**\n * Checks that inventory extensions not needed there.\n * It always should be used after `InventoryManager.playerIsLoaded(player)` check.\n *\n * @param player Player to check\n */\n private boolean isExtensionsNotNeededHere(Player player) {\n return !InventoryManager.get(player).isPocketCraft()\n && !Config.getConfig().getBoolean(\"craft.workbench\", true);\n }\n\n @EventHandler(priority = EventPriority.MONITOR)\n public void onWorkbenchClosed(@NotNull InventoryCloseEvent event) {\n Player player = (Player) event.getPlayer();\n if (!InventoryManager.playerIsLoaded(player)) {\n return;\n }\n\n if (event.getInventory().getType() == InventoryType.WORKBENCH) {\n InventoryManager.get(player).onWorkbenchClosed();\n }\n }\n}",
"public class Texture {\n\n private static final Texture EMPTY_TEXTURE = new Texture(new ItemStack(Material.AIR));\n\n @NotNull\n private final ItemStack prototype;\n private final int data;\n\n private Texture(@NotNull ItemStack prototype) {\n this(prototype, (short) -1);\n }\n\n private Texture(@NotNull ItemStack prototype, int data) {\n this.prototype = prototype;\n this.data = data;\n }\n\n public boolean isEmpty() {\n return this.equals(EMPTY_TEXTURE);\n }\n\n @NotNull\n public ItemStack getItemStack() {\n return prototype.clone();\n }\n\n public int getData() {\n return data;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n\n if (!(o instanceof Texture)) {\n return false;\n }\n\n Texture texture = (Texture) o;\n return prototype.equals(texture.prototype);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(prototype);\n }\n\n public static Texture parseTexture(String texture) {\n if (texture == null) {\n return EMPTY_TEXTURE;\n }\n\n String[] textureParts = texture.split(\":\");\n\n Material material = MaterialCompat.getMaterialOrNull(textureParts[0]);\n if (material == null) {\n Log.w(\"Unknown material: {0}\", textureParts[0]);\n return EMPTY_TEXTURE;\n }\n\n ItemStack item = ItemUtils.toBukkitItemStack(new ItemStack(material));\n if (ItemUtils.isEmpty(item)) {\n return EMPTY_TEXTURE;\n }\n\n if (textureParts.length > 1) {\n // MONSTER_EGG before 1.13\n if (material.name().equals(\"MONSTER_EGG\")) {\n return parseLegacyMonsterEgg(item, textureParts[1]);\n } else if (material.name().startsWith(\"LEATHER_\")) {\n return parseLeatherArmor(item, textureParts[1]);\n } else {\n return parseItemWithData(item, textureParts[1]);\n }\n }\n\n return new Texture(item);\n }\n\n private static Texture parseLegacyMonsterEgg(ItemStack item, String entityType) {\n NbtCompound nbt = NbtFactoryMirror.fromItemCompound(item);\n nbt.put(ItemUtils.ENTITY_TAG, NbtFactory.ofCompound(\"temp\").put(\"id\", entityType));\n\n return new Texture(item);\n }\n\n private static Texture parseLeatherArmor(ItemStack item, String hexColor) {\n try {\n LeatherArmorMeta meta = (LeatherArmorMeta) item.getItemMeta();\n assert meta != null;\n meta.setColor(Color.fromRGB(Integer.parseInt(hexColor, 16)));\n item.setItemMeta(meta);\n } catch (ClassCastException | IllegalArgumentException | NullPointerException e) {\n Log.w(\"Can''t parse leather color: {0}\", e.toString());\n }\n\n return new Texture(item);\n }\n\n private static Texture parseItemWithData(ItemStack item, String textureDataValue) {\n if (item.getItemMeta() == null) {\n return new Texture(item);\n }\n\n int textureData = -1;\n try {\n textureData = Integer.parseInt(textureDataValue);\n } catch (NumberFormatException e) {\n Log.w(\"Can''t parse texture modifier. Specify a number instead of \\\"{0}\\\"\", textureData);\n }\n\n if (Config.texturesType == TexturesType.DAMAGE) {\n return parseItemWithDurability(item, textureData);\n }\n return parseItemWithCustomModelData(item, textureData);\n }\n\n private static Texture parseItemWithDurability(ItemStack item, int damage) {\n ItemMeta meta = item.getItemMeta();\n assert meta != null;\n\n meta.addItemFlags(ItemFlag.values());\n if (damage != -1) {\n ((Damageable) meta).setDamage(damage);\n if (ItemUtils.isItemHasDurability(item)) {\n meta.setUnbreakable(true);\n }\n }\n item.setItemMeta(meta);\n\n return new Texture(item, damage);\n }\n\n private static Texture parseItemWithCustomModelData(ItemStack item, int customModelData) {\n ItemMeta meta = item.getItemMeta();\n assert meta != null;\n\n meta.addItemFlags(ItemFlag.values());\n if (customModelData != -1) {\n meta.setCustomModelData(customModelData);\n }\n item.setItemMeta(meta);\n\n return new Texture(item, customModelData);\n }\n}",
"public class Config {\n\n /* Config options */\n public static VanillaSlotAction craftSlotsAction = VanillaSlotAction.RPGINV;\n public static VanillaSlotAction armorSlotsAction = VanillaSlotAction.DEFAULT;\n\n public static TexturesType texturesType = TexturesType.DAMAGE;\n\n private static final FileConfiguration config = new YamlConfiguration();\n private static Path configFile;\n\n public static void init(RPGInventory plugin) {\n configFile = plugin.getDataPath().resolve(\"config.yml\");\n plugin.saveDefaultConfig();\n\n final InputStream defaultConfigStream = plugin.getResource(\"config.yml\");\n if (defaultConfigStream != null) {\n loadDefaultConfig(defaultConfigStream);\n }\n\n reload();\n }\n\n public static FileConfiguration getConfig() {\n return config;\n }\n\n public static void reload() {\n try {\n config.load(configFile.toFile());\n } catch (IOException | InvalidConfigurationException e) {\n Log.w(e, \"Error on load config.yml\");\n }\n\n copyOptionsFromConfig();\n save();\n }\n\n public static void save() {\n try {\n config.save(configFile.toFile());\n } catch (IOException e) {\n Log.w(e, \"Error on save config.yml\");\n }\n }\n\n private static void loadDefaultConfig(@NotNull InputStream defaultConfigStream) {\n final Path exampleConfigPath = configFile.getParent().resolve(\"config-example.yml\");\n\n // Update example config\n try (final InputStream stream = defaultConfigStream) {\n Files.copy(stream, exampleConfigPath, StandardCopyOption.REPLACE_EXISTING);\n } catch (IOException e) {\n Log.w(e, \"Error on copying config-example.yml\");\n }\n\n config.setDefaults(YamlConfiguration.loadConfiguration(exampleConfigPath.toFile()));\n config.options().copyDefaults(true);\n }\n\n private static void copyOptionsFromConfig() {\n craftSlotsAction = VanillaSlotAction.parseString(config.getString(\"craft-slots-action\"));\n armorSlotsAction = VanillaSlotAction.parseString(config.getString(\"armor-slots-action\"));\n\n texturesType = TexturesType.parseString(config.getString(\"textures-type\"));\n }\n}",
"@SuppressWarnings(\"CheckStyle\")\npublic final class Log {\n\n private static Logger logger;\n\n private Log() {\n // static class\n }\n\n public static void init(@NotNull Logger logger) {\n Log.logger = logger;\n }\n\n public static void i(@NotNull String message, Object... args) {\n logger.info(prepareMessage(message, args));\n }\n\n public static void w(Throwable t) {\n logger.log(Level.WARNING, t.getMessage(), t);\n }\n\n public static void w(@NotNull String message, Object... args) {\n logger.warning(prepareMessage(message, args));\n }\n\n public static void w(Throwable t, @NotNull String message, Object... args) {\n logger.log(Level.WARNING, prepareMessage(message, args), t);\n }\n\n public static void d(Throwable t) {\n logger.log(Level.FINE, \"\", t);\n }\n\n public static void s(@NotNull String message, Object... args) {\n logger.severe(prepareMessage(message, args));\n }\n\n private static String prepareMessage(String message, Object... args) {\n return MessageFormat.format(message, args);\n }\n}"
] | import ru.endlesscode.rpginventory.item.Texture;
import ru.endlesscode.rpginventory.misc.config.Config;
import ru.endlesscode.rpginventory.utils.Log;
import java.util.ArrayList;
import java.util.List;
import com.comphenix.protocol.PacketType;
import com.comphenix.protocol.ProtocolLibrary;
import com.comphenix.protocol.events.PacketAdapter;
import com.comphenix.protocol.events.PacketEvent;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.MemorySection;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import ru.endlesscode.rpginventory.RPGInventory;
import ru.endlesscode.rpginventory.compat.VersionHandler;
import ru.endlesscode.rpginventory.event.listener.CraftListener; | /*
* This file is part of RPGInventory.
* Copyright (C) 2015-2017 Osip Fatkullin
*
* RPGInventory is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* RPGInventory is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with RPGInventory. If not, see <http://www.gnu.org/licenses/>.
*/
package ru.endlesscode.rpginventory.inventory.craft;
/**
* Created by OsipXD on 29.08.2016
* It is part of the RpgInventory.
* All rights reserved 2014 - 2016 © «EndlessCode Group»
*/
public class CraftManager {
@NotNull
private static final List<CraftExtension> EXTENSIONS = new ArrayList<>();
private static Texture textureOfExtendable;
private CraftManager() {
}
public static boolean init(@NotNull RPGInventory instance) {
MemorySection config = (MemorySection) Config.getConfig().get("craft");
if (config == null) {
Log.w("Section ''craft'' not found in config.yml");
return false;
}
if (!config.getBoolean("enabled")) {
Log.i("Craft system is disabled in config");
return false;
}
try {
Texture texture = Texture.parseTexture(config.getString("extendable"));
if (texture.isEmpty()) {
Log.s("Invalid texture in ''craft.extendable''");
return false;
}
textureOfExtendable = texture;
@Nullable final ConfigurationSection extensions = config.getConfigurationSection("extensions");
if (extensions == null) {
Log.s("Section ''craft.extensions'' not found in config.yml");
return false;
}
EXTENSIONS.clear();
for (String extensionName : extensions.getKeys(false)) {
EXTENSIONS.add(new CraftExtension(extensionName, extensions.getConfigurationSection(extensionName)));
}
// Register listeners | ProtocolLibrary.getProtocolManager().addPacketListener(new CraftListener(instance)); | 2 |
suninformation/ymate-payment-v2 | ymate-payment-wxpay/src/main/java/net/ymate/payment/wxpay/impl/DefaultModuleCfg.java | [
"public interface IWxPay {\n\n String MODULE_NAME = \"payment.wxpay\";\n\n /**\n * @return 返回所属YMP框架管理器实例\n */\n YMP getOwner();\n\n /**\n * @return 返回模块配置对象\n */\n IWxPayModuleCfg getModuleCfg();\n\n /**\n * @return 返回模块是否已初始化\n */\n boolean isInited();\n\n /**\n * @param appId 公众账号ID\n * @param body 商品描述\n * @param outTradeNo 商户订单号\n * @param totalFee 总金额\n * @param spbillCreateIp 终端IP\n * @param notifyUrl 通知地址\n * @param tradeType 交易类型\n * @return 统一下单\n * @throws Exception 可能产生的任何异常\n */\n WxPayUnifiedOrder unifiedOrder(String appId, String body, String outTradeNo, Integer totalFee, String spbillCreateIp, String notifyUrl, TradeType tradeType) throws Exception;\n\n /**\n * @param appId 公众账号ID\n * @param outTradeNo 商户订单号\n * @return 关闭订单\n * @throws Exception 可能产生的任何异常\n */\n WxPayCloseOrder closeOrder(String appId, String outTradeNo) throws Exception;\n\n /**\n * @param appId 公众账号ID\n * @param billData 对账单日期\n * @param billType 账单类型\n * @return 下载对账单\n * @throws Exception 可能产生的任何异常\n */\n WxPayDownloadBill downloadBill(String appId, String billData, IWxPay.BillType billType) throws Exception;\n\n /**\n * @param appId 公众账号ID\n * @param partnerTradeNo 商户订单号\n * @param openId 微信用户唯一标识\n * @param checkName 校验用户姓名选项\n * @param amount 金额\n * @param desc 企业付款描述信息\n * @param spbillCreateIp Ip地址\n * @return 企业付款\n * @throws Exception 可能产生的任何异常\n */\n WxPayMchPay mchPay(String appId, String partnerTradeNo, String openId, boolean checkName, Integer amount, String desc, String spbillCreateIp) throws Exception;\n\n /**\n * @param appId 公众账号ID\n * @param partnerTradeNo 商户订单号\n * @return 查询企业付款\n * @throws Exception 可能产生的任何异常\n */\n WxPayMchPayQuery mchPayQuery(String appId, String partnerTradeNo) throws Exception;\n\n /**\n * @param appId 公众账号ID\n * @param transactionId 微信订单号\n * @param outTradeNo 商户订单号\n * @return 查询订单\n * @throws Exception 可能产生的任何异常\n */\n WxPayOrderQuery orderQuery(String appId, String transactionId, String outTradeNo) throws Exception;\n\n /**\n * @param appId 公众账号ID\n * @param mchBillNo 商户订单号\n * @param sendName 商户名称\n * @param reOpenId 微信用户唯一标识\n * @param totalAmount 总金额\n * @param totalNum 红包发放总人数\n * @param wishing 红包祝福语\n * @param clientIp Ip地址\n * @param actName 活动名称\n * @param remark 备注\n * @return 发送普通红包\n * @throws Exception 可能产生的任何异常\n */\n WxPayRedPackSend redPackSend(String appId, String mchBillNo, String sendName, String reOpenId, Integer totalAmount, Integer totalNum, String wishing, String clientIp, String actName, String remark) throws Exception;\n\n /**\n * @param appId 公众账号ID\n * @param mchBillNo 商户订单号\n * @param sendName 商户名称\n * @param reOpenId 微信用户唯一标识\n * @param totalAmount 总金额\n * @param totalNum 红包发放总人数\n * @param wishing 红包祝福语\n * @param clientIp Ip地址\n * @param actName 活动名称\n * @param remark 备注\n * @return 发放裂变红包\n * @throws Exception 可能产生的任何异常\n */\n WxPayRedPackSendGroup redPackSendGroup(String appId, String mchBillNo, String sendName, String reOpenId, Integer totalAmount, Integer totalNum, String wishing, String clientIp, String actName, String remark) throws Exception;\n\n /**\n * @param appId 公众账号ID\n * @param mchBillNo 商户订单号\n * @return 查询红包记录\n * @throws Exception 可能产生的任何异常\n */\n WxPayRedPackInfo redPackInfo(String appId, String mchBillNo) throws Exception;\n\n /**\n * @param appId 公众账号ID\n * @param transactionId 微信订单号\n * @param outTradeNo 商户订单号\n * @param outRefundNo 商户退款单号\n * @param totalFee 总金额\n * @param refundFee 退款金额\n * @return 申请退款\n * @throws Exception 可能产生的任何异常\n */\n WxPayRefund refund(String appId, String transactionId, String outTradeNo, String outRefundNo, Integer totalFee, Integer refundFee) throws Exception;\n\n /**\n * @param appId 公众账号ID\n * @param transactionId 微信订单号\n * @param outTradeNo 商户订单号\n * @param outRefundNo 商户退款单号\n * @param refundId 微信退款单号\n * @return 查询退款\n * @throws Exception 可能产生的任何异常\n */\n WxPayRefundQuery refundQuery(String appId, String transactionId, String outTradeNo, String outRefundNo, String refundId) throws Exception;\n\n /**\n * @param appId 公众账号ID\n * @param longUrl URL链接\n * @return 转换短链接\n * @throws Exception 可能产生的任何异常\n */\n WxPayShortUrl shortUrl(String appId, String longUrl) throws Exception;\n\n /**\n * @param appId 公众账号ID\n * @param body 商品描述\n * @param outTradeNo 商户订单号\n * @param totalFee 总金额\n * @param spbillCreateIp 终端IP\n * @param authCode 授权码\n * @return 提交刷卡支付\n * @throws Exception 可能产生的任何异常\n */\n WxPayMicroPay microPay(String appId, String body, String outTradeNo, Integer totalFee, String spbillCreateIp, String authCode) throws Exception;\n\n /**\n * @param appId 公众账号ID\n * @param transactionId 微信订单号\n * @param outTradeNo 商户订单号\n * @return 撤销订单\n * @throws Exception 可能产生的任何异常\n */\n WxPayReverse reverse(String appId, String transactionId, String outTradeNo) throws Exception;\n\n /**\n * @param appId 公众账号ID\n * @param authCode 授权码\n * @return 授权码查询openid\n * @throws Exception 可能产生的任何异常\n */\n WxPayAuthCodeToOpenId authCodeToOpenId(String appId, String authCode) throws Exception;\n\n /**\n * 账单类型\n */\n enum BillType {\n ALL, SUCCESS, REFUND, RECHARGE_REFUND;\n }\n\n /**\n * 返回状态码\n */\n enum ReturnCode {\n SUCCESS, FAIL;\n }\n\n /**\n * 业务结果\n */\n enum ResultCode {\n SUCCESS, FAIL;\n }\n\n /**\n * 业务异常状态码\n */\n enum ErrCode {\n\n NOAUTH(\"商户无此接口权限\"),\n NOTENOUGH(\"余额不足\"),\n ORDERPAID(\"商户订单已支付\"),\n ORDERCLOSED(\"订单已关闭\"),\n SYSTEMERROR(\"系统错误\"),\n APPID_NOT_EXIST(\"APPID不存在\"),\n MCHID_NOT_EXIST(\"MCH_ID不存在\"),\n APPID_MCHID_NOT_MATCH(\"APPID和MCH_ID不匹配\"),\n LACK_PARAMS(\"缺少参数\"),\n OUT_TRADE_NO_USED(\"商户订单号重复\"),\n SIGNERROR(\"签名错误\"),\n XML_FORMAT_ERROR(\"XML格式错误\"),\n REQUIRE_POST_METHOD(\"请使用POST方法\"),\n POST_DATA_EMPTY(\"POST数据为空\"),\n NOT_UTF8(\"编码格式错误\"),\n //\n ORDERNOTEXIST(\"此交易订单号不存在\"),\n //\n REFUNDNOTEXIST(\"退款订单查询失败\"),\n INVALID_TRANSACTIONID(\"无效TRANSACTION_ID\"),\n PARAM_ERROR(\"参数错误\"),\n //\n CA_ERROR(\"请求未携带证书,或请求携带的证书出错\"),\n SIGN_ERROR(\"商户签名错误\"),\n NO_AUTH(\"没有权限\"),\n FREQ_LIMIT(\"受频率限制\"),\n NOT_FOUND(\"指定单号数据不存在\"),\n //\n AMOUNT_LIMIT(\"付款金额不能小于最低限额\"),\n OPENID_ERROR(\"OPENID错误\"),\n NAME_MISMATCH(\"姓名校验出错\"),\n FATAL_ERROR(\"两次请求参数不一致\"),\n V2_ACCOUNT_SIMPLE_BAN(\"无法给非实名用户付款\"),\n //\n BIZERR_NEED_RETRY(\"退款业务流程错误,需要商户触发重试来解决\"),\n TRADE_OVERDUE(\"订单已经超过退款期限\"),\n USER_ACCOUNT_ABNORMAL(\"退款请求失败\"),\n INVALID_REQ_TOO_MUCH(\"无效请求过多\"),\n FREQUENCY_LIMITED(\"频率限制\"),\n //\n AUTHCODEEXPIRE(\"二维码已过期,请用户在微信上刷新后再试\"),\n NOTSUPORTCARD(\"不支持卡类型\"),\n ORDERREVERSED(\"订单已撤销\"),\n BANKERROR(\"银行系统异常\"),\n USERPAYING(\"用户支付中,需要输入密码\"),\n AUTH_CODE_ERROR(\"授权码参数错误\"),\n AUTH_CODE_INVALID(\"授权码检验错误\"),\n BUYER_MISMATCH(\"支付帐号错误\");\n\n private String desc;\n\n ErrCode(String desc) {\n this.desc = desc;\n }\n\n public String desc() {\n return this.desc;\n }\n }\n\n /**\n * 银行类型\n */\n enum BlankType {\n ICBC_DEBIT(\"工商银行(借记卡)\"),\n ICBC_CREDIT(\"工商银行(信用卡)\"),\n ABC_DEBIT(\"农业银行(借记卡)\"),\n ABC_CREDIT(\"农业银行(信用卡)\"),\n PSBC_DEBIT(\"邮政储蓄银行(借记卡)\"),\n PSBC_CREDIT(\"邮政储蓄银行(信用卡)\"),\n CCB_DEBIT(\"建设银行(借记卡)\"),\n CCB_CREDIT(\"建设银行(信用卡)\"),\n CMB_DEBIT(\"招商银行(借记卡)\"),\n CMB_CREDIT(\"招商银行(信用卡)\"),\n BOC_DEBIT(\"中国银行(借记卡)\"),\n BOC_CREDIT(\"中国银行(信用卡)\"),\n COMM_DEBIT(\"交通银行(借记卡)\"),\n COMM_CREDIT(\"交通银行(信用卡)\"),\n SPDB_DEBIT(\"浦发银行(借记卡)\"),\n SPDB_CREDIT(\"浦发银行(信用卡)\"),\n GDB_DEBIT(\"广发银行(借记卡)\"),\n GDB_CREDIT(\"广发银行(信用卡)\"),\n CMBC_DEBIT(\"民生银行(借记卡)\"),\n CMBC_CREDIT(\"民生银行(信用卡)\"),\n PAB_DEBIT(\"平安银行(借记卡)\"),\n PAB_CREDIT(\"平安银行(信用卡)\"),\n CEB_DEBIT(\"光大银行(借记卡)\"),\n CEB_CREDIT(\"光大银行(信用卡)\"),\n CIB_DEBIT(\"兴业银行(借记卡)\"),\n CIB_CREDIT(\"兴业银行(信用卡)\"),\n CITIC_DEBIT(\"中信银行(借记卡)\"),\n CITIC_CREDIT(\"中信银行(信用卡)\"),\n BOSH_DEBIT(\"上海银行(借记卡)\"),\n BOSH_CREDIT(\"上海银行(信用卡)\"),\n CRB_DEBIT(\"华润银行(借记卡)\"),\n HZB_DEBIT(\"杭州银行(借记卡)\"),\n HZB_CREDIT(\"杭州银行(信用卡)\"),\n BSB_DEBIT(\"包商银行(借记卡)\"),\n BSB_CREDIT(\"包商银行(信用卡)\"),\n CQB_DEBIT(\"重庆银行(借记卡)\"),\n SDEB_DEBIT(\"顺德农商行(借记卡)\"),\n SZRCB_DEBIT(\"深圳农商银行(借记卡)\"),\n SZRCB_CREDIT(\"深圳农商银行(信用卡)\"),\n HRBB_DEBIT(\"哈尔滨银行(借记卡)\"),\n BOCD_DEBIT(\"成都银行(借记卡)\"),\n GDNYB_DEBIT(\"南粤银行(借记卡)\"),\n GDNYB_CREDIT(\"南粤银行(信用卡)\"),\n GZCB_DEBIT(\"广州银行(借记卡)\"),\n GZCB_CREDIT(\"广州银行(信用卡)\"),\n JSB_DEBIT(\"江苏银行(借记卡)\"),\n JSB_CREDIT(\"江苏银行(信用卡)\"),\n NBCB_DEBIT(\"宁波银行(借记卡)\"),\n NBCB_CREDIT(\"宁波银行(信用卡)\"),\n NJCB_DEBIT(\"南京银行(借记卡)\"),\n QHNX_DEBIT(\"青海农信(借记卡)\"),\n ORDOSB_CREDIT(\"鄂尔多斯银行(信用卡)\"),\n ORDOSB_DEBIT(\"鄂尔多斯银行(借记卡)\"),\n BJRCB_CREDIT(\"北京农商(信用卡)\"),\n BHB_DEBIT(\"河北银行(借记卡)\"),\n BGZB_DEBIT(\"贵州银行(借记卡)\"),\n BEEB_DEBIT(\"鄞州银行(借记卡)\"),\n PZHCCB_DEBIT(\"攀枝花银行(借记卡)\"),\n QDCCB_CREDIT(\"青岛银行(信用卡)\"),\n QDCCB_DEBIT(\"青岛银行(借记卡)\"),\n SHINHAN_DEBIT(\"新韩银行(借记卡)\"),\n QLB_DEBIT(\"齐鲁银行(借记卡)\"),\n QSB_DEBIT(\"齐商银行(借记卡)\"),\n ZZB_DEBIT(\"郑州银行(借记卡)\"),\n CCAB_DEBIT(\"长安银行(借记卡)\"),\n RZB_DEBIT(\"日照银行(借记卡)\"),\n SCNX_DEBIT(\"四川农信(借记卡)\"),\n BEEB_CREDIT(\"鄞州银行(信用卡)\"),\n SDRCU_DEBIT(\"山东农信(借记卡)\"),\n BCZ_DEBIT(\"沧州银行(借记卡)\"),\n SJB_DEBIT(\"盛京银行(借记卡)\"),\n LNNX_DEBIT(\"辽宁农信(借记卡)\"),\n JUFENGB_DEBIT(\"临朐聚丰村镇银行(借记卡)\"),\n ZZB_CREDIT(\"郑州银行(信用卡)\"),\n JXNXB_DEBIT(\"江西农信(借记卡)\"),\n JZB_DEBIT(\"晋中银行(借记卡)\"),\n JZCB_CREDIT(\"锦州银行(信用卡)\"),\n JZCB_DEBIT(\"锦州银行(借记卡)\"),\n KLB_DEBIT(\"昆仑银行(借记卡)\"),\n KRCB_DEBIT(\"昆山农商(借记卡)\"),\n KUERLECB_DEBIT(\"库尔勒市商业银行(借记卡)\"),\n LJB_DEBIT(\"龙江银行(借记卡)\"),\n NYCCB_DEBIT(\"南阳村镇银行(借记卡)\"),\n LSCCB_DEBIT(\"乐山市商业银行(借记卡)\"),\n LUZB_DEBIT(\"柳州银行(借记卡)\"),\n LWB_DEBIT(\"莱商银行(借记卡)\"),\n LYYHB_DEBIT(\"辽阳银行(借记卡)\"),\n LZB_DEBIT(\"兰州银行(借记卡)\"),\n MINTAIB_CREDIT(\"民泰银行(信用卡)\"),\n MINTAIB_DEBIT(\"民泰银行(借记卡)\"),\n NCB_DEBIT(\"宁波通商银行(借记卡)\"),\n NMGNX_DEBIT(\"内蒙古农信(借记卡)\"),\n XAB_DEBIT(\"西安银行(借记卡)\"),\n WFB_CREDIT(\"潍坊银行(信用卡)\"),\n WFB_DEBIT(\"潍坊银行(借记卡)\"),\n WHB_CREDIT(\"威海商业银行(信用卡)\"),\n WHB_DEBIT(\"威海市商业银行(借记卡)\"),\n WHRC_CREDIT(\"武汉农商(信用卡)\"),\n WHRC_DEBIT(\"武汉农商行(借记卡)\"),\n WJRCB_DEBIT(\"吴江农商行(借记卡)\"),\n WLMQB_DEBIT(\"乌鲁木齐银行(借记卡)\"),\n WRCB_DEBIT(\"无锡农商(借记卡)\"),\n WZB_DEBIT(\"温州银行(借记卡)\"),\n XAB_CREDIT(\"西安银行(信用卡)\"),\n WEB_DEBIT(\"微众银行(借记卡)\"),\n XIB_DEBIT(\"厦门国际银行(借记卡)\"),\n XJRCCB_DEBIT(\"新疆农信银行(借记卡)\"),\n XMCCB_DEBIT(\"厦门银行(借记卡)\"),\n YNRCCB_DEBIT(\"云南农信(借记卡)\"),\n YRRCB_CREDIT(\"黄河农商银行(信用卡)\"),\n YRRCB_DEBIT(\"黄河农商银行(借记卡)\"),\n YTB_DEBIT(\"烟台银行(借记卡)\"),\n ZJB_DEBIT(\"紫金农商银行(借记卡)\"),\n ZJLXRB_DEBIT(\"兰溪越商银行(借记卡)\"),\n ZJRCUB_CREDIT(\"浙江农信(信用卡)\"),\n AHRCUB_DEBIT(\"安徽省农村信用社联合社(借记卡)\"),\n BCZ_CREDIT(\"沧州银行(信用卡)\"),\n SRB_DEBIT(\"上饶银行(借记卡)\"),\n ZYB_DEBIT(\"中原银行(借记卡)\"),\n ZRCB_DEBIT(\"张家港农商行(借记卡)\"),\n SRCB_CREDIT(\"上海农商银行(信用卡)\"),\n SRCB_DEBIT(\"上海农商银行(借记卡)\"),\n ZJTLCB_DEBIT(\"浙江泰隆银行(借记卡)\"),\n SUZB_DEBIT(\"苏州银行(借记卡)\"),\n SXNX_DEBIT(\"山西农信(借记卡)\"),\n SXXH_DEBIT(\"陕西信合(借记卡)\"),\n ZJRCUB_DEBIT(\"浙江农信(借记卡)\"),\n AE_CREDIT(\"AE(信用卡)\"),\n TACCB_CREDIT(\"泰安银行(信用卡)\"),\n TACCB_DEBIT(\"泰安银行(借记卡)\"),\n TCRCB_DEBIT(\"太仓农商行(借记卡)\"),\n TJBHB_CREDIT(\"天津滨海农商行(信用卡)\"),\n TJBHB_DEBIT(\"天津滨海农商行(借记卡)\"),\n TJB_DEBIT(\"天津银行(借记卡)\"),\n TRCB_DEBIT(\"天津农商(借记卡)\"),\n TZB_DEBIT(\"台州银行(借记卡)\"),\n URB_DEBIT(\"联合村镇银行(借记卡)\"),\n DYB_CREDIT(\"东营银行(信用卡)\"),\n CSRCB_DEBIT(\"常熟农商银行(借记卡)\"),\n CZB_CREDIT(\"浙商银行(信用卡)\"),\n CZB_DEBIT(\"浙商银行(借记卡)\"),\n CZCB_CREDIT(\"稠州银行(信用卡)\"),\n CZCB_DEBIT(\"稠州银行(借记卡)\"),\n DANDONGB_CREDIT(\"丹东银行(信用卡)\"),\n DANDONGB_DEBIT(\"丹东银行(借记卡)\"),\n DLB_CREDIT(\"大连银行(信用卡)\"),\n DLB_DEBIT(\"大连银行(借记卡)\"),\n DRCB_CREDIT(\"东莞农商银行(信用卡)\"),\n DRCB_DEBIT(\"东莞农商银行(借记卡)\"),\n CSRCB_CREDIT(\"常熟农商银行(信用卡)\"),\n DYB_DEBIT(\"东营银行(借记卡)\"),\n DYCCB_DEBIT(\"德阳银行(借记卡)\"),\n FBB_DEBIT(\"富邦华一银行(借记卡)\"),\n FDB_DEBIT(\"富滇银行(借记卡)\"),\n FJHXB_CREDIT(\"福建海峡银行(信用卡)\"),\n FJHXB_DEBIT(\"福建海峡银行(借记卡)\"),\n FJNX_DEBIT(\"福建农信银行(借记卡)\"),\n FUXINB_DEBIT(\"阜新银行(借记卡)\"),\n BOCDB_DEBIT(\"承德银行(借记卡)\"),\n JSNX_DEBIT(\"江苏农商行(借记卡)\"),\n BOLFB_DEBIT(\"廊坊银行(借记卡)\"),\n CCAB_CREDIT(\"长安银行(信用卡)\"),\n CBHB_DEBIT(\"渤海银行(借记卡)\"),\n CDRCB_DEBIT(\"成都农商银行(借记卡)\"),\n BYK_DEBIT(\"营口银行(借记卡)\"),\n BOZ_DEBIT(\"张家口市商业银行(借记卡)\"),\n CFT(\"零钱\"),\n BOTSB_DEBIT(\"唐山银行(借记卡)\"),\n BOSZS_DEBIT(\"石嘴山银行(借记卡)\"),\n BOSXB_DEBIT(\"绍兴银行(借记卡)\"),\n BONX_DEBIT(\"宁夏银行(借记卡)\"),\n BONX_CREDIT(\"宁夏银行(信用卡)\"),\n GDHX_DEBIT(\"广东华兴银行(借记卡)\"),\n BOLB_DEBIT(\"洛阳银行(借记卡)\"),\n BOJX_DEBIT(\"嘉兴银行(借记卡)\"),\n BOIMCB_DEBIT(\"内蒙古银行(借记卡)\"),\n BOHN_DEBIT(\"海南银行(借记卡)\"),\n BOD_DEBIT(\"东莞银行(借记卡)\"),\n CQRCB_CREDIT(\"重庆农商银行(信用卡)\"),\n CQRCB_DEBIT(\"重庆农商银行(借记卡)\"),\n CQTGB_DEBIT(\"重庆三峡银行(借记卡)\"),\n BOD_CREDIT(\"东莞银行(信用卡)\"),\n CSCB_DEBIT(\"长沙银行(借记卡)\"),\n BOB_CREDIT(\"北京银行(信用卡)\"),\n GDRCU_DEBIT(\"广东农信银行(借记卡)\"),\n BOB_DEBIT(\"北京银行(借记卡)\"),\n HRXJB_DEBIT(\"华融湘江银行(借记卡)\"),\n HSBC_DEBIT(\"恒生银行(借记卡)\"),\n HSB_CREDIT(\"徽商银行(信用卡)\"),\n HSB_DEBIT(\"徽商银行(借记卡)\"),\n HUNNX_DEBIT(\"湖南农信(借记卡)\"),\n HUSRB_DEBIT(\"湖商村镇银行(借记卡)\"),\n HXB_CREDIT(\"华夏银行(信用卡)\"),\n HXB_DEBIT(\"华夏银行(借记卡)\"),\n HNNX_DEBIT(\"河南农信(借记卡)\"),\n BNC_DEBIT(\"江西银行(借记卡)\"),\n BNC_CREDIT(\"江西银行(信用卡)\"),\n BJRCB_DEBIT(\"北京农商行(借记卡)\"),\n JCB_DEBIT(\"晋城银行(借记卡)\"),\n JJCCB_DEBIT(\"九江银行(借记卡)\"),\n JLB_DEBIT(\"吉林银行(借记卡)\"),\n JLNX_DEBIT(\"吉林农信(借记卡)\"),\n JNRCB_DEBIT(\"江南农商(借记卡)\"),\n JRCB_DEBIT(\"江阴农商行(借记卡)\"),\n JSHB_DEBIT(\"晋商银行(借记卡)\"),\n HAINNX_DEBIT(\"海南农信(借记卡)\"),\n GLB_DEBIT(\"桂林银行(借记卡)\"),\n GRCB_CREDIT(\"广州农商银行(信用卡)\"),\n GRCB_DEBIT(\"广州农商银行(借记卡)\"),\n GSB_DEBIT(\"甘肃银行(借记卡)\"),\n GSNX_DEBIT(\"甘肃农信(借记卡)\"),\n GXNX_DEBIT(\"广西农信(借记卡)\"),\n GYCB_CREDIT(\"贵阳银行(信用卡)\"),\n GYCB_DEBIT(\"贵阳银行(借记卡)\"),\n GZNX_DEBIT(\"贵州农信(借记卡)\"),\n HAINNX_CREDIT(\"海南农信(信用卡)\"),\n HKB_DEBIT(\"汉口银行(借记卡)\"),\n HANAB_DEBIT(\"韩亚银行(借记卡)\"),\n HBCB_CREDIT(\"湖北银行(信用卡)\"),\n HBCB_DEBIT(\"湖北银行(借记卡)\"),\n HBNX_CREDIT(\"湖北农信(信用卡)\"),\n HBNX_DEBIT(\"湖北农信(借记卡)\"),\n HDCB_DEBIT(\"邯郸银行(借记卡)\"),\n HEBNX_DEBIT(\"河北农信(借记卡)\"),\n HFB_DEBIT(\"恒丰银行(借记卡)\"),\n HKBEA_DEBIT(\"东亚银行(借记卡)\"),\n JCB_CREDIT(\"JCB(信用卡)\"),\n MASTERCARD_CREDIT(\"MASTERCARD(信用卡)\"),\n VISA_CREDIT(\"VISA(信用卡)\");\n\n private String desc;\n\n BlankType(String desc) {\n this.desc = desc;\n }\n\n public String desc() {\n return this.desc;\n }\n }\n\n /**\n * 货币类型\n */\n enum FeeType {\n CNY\n }\n\n /**\n * 交易类型\n */\n enum TradeType {\n JSAPI, NATIVE, APP, MICROPAY, MWEB;\n }\n\n /**\n * 交易状态\n */\n enum TradeState {\n SUCCESS, REFUND, NOTPAY, CLOSED, REVOKED, USERPAYING, PAYERROR;\n }\n\n /**\n * 转账状态\n */\n enum Status {\n SUCCESS, FAILED, PROCESSING;\n }\n\n /**\n * 代金券类型\n */\n enum CouponType {\n CASH, NO_CASH;\n }\n\n /**\n * 指定支付方式\n */\n enum LimitPay {\n NO_CREDIT\n }\n\n /**\n * 常量\n */\n interface Const {\n\n /**\n * 公众账号ID\n */\n String APP_ID = \"appid\";\n\n String MCH_ID = \"mch_id\";\n\n String MCH_KEY = \"mch_key\";\n\n String NONCE_STR = \"nonce_str\";\n\n String DEVICE_INFO = \"device_info\";\n\n String SIGN = \"sign\";\n\n String SIGN_TYPE = \"sign_type\";\n\n String NOTIFY_URL = \"notify_url\";\n\n String SIGN_TYPE_MD5 = \"MD5\";\n\n String RETURN_CODE = \"return_code\";\n\n String RETURN_MSG = \"return_msg\";\n\n String RESULT_CODE = \"result_code\";\n\n String ERR_CODE = \"err_code\";\n\n String ERR_CODE_DES = \"err_code_des\";\n\n /**\n * 商户订单号\n */\n String OUT_TRADE_NO = \"out_trade_no\";\n }\n}",
"public interface IWxPayAccountProvider {\n\n void init(IWxPay owner) throws Exception;\n\n void destroy() throws Exception;\n\n void registerAccount(WxPayAccountMeta accountMeta);\n\n WxPayAccountMeta unregisterAccount(String accountId);\n\n Collection<String> getAccountIds();\n\n boolean hasAccount(String accountId);\n\n WxPayAccountMeta getAccount(String accountId);\n}",
"public interface IWxPayEventHandler {\n\n /**\n * @param accountMeta 微信支付账户\n * @param tradeType 交易类型\n * @param orderId 订单ID\n * @param attach 附加信息\n * @return 构建微信统一支付请求数据对象\n * @throws Exception 可能产生的任何异常\n */\n WxPayUnifiedOrder buildUnifiedOrderRequest(WxPayAccountMeta accountMeta, IWxPay.TradeType tradeType, String orderId, String attach) throws Exception;\n\n /**\n * 异步支付通知消息到达事件处理方法,该方法的执行过程中若无任何异常被抛出则视为执行成功并向微信通知服务返回SUCCESS字符串\n *\n * @param notifyData 异步通知对象\n * @throws Exception 可能产生的任何异常\n */\n void onNotifyReceived(WxPayNotifyResponse notifyData) throws Exception;\n\n /**\n * @param orderId 订单ID\n * @return 返回是否需要发起订单状态查询\n * @throws Exception 可能产生的任何异常\n */\n boolean onReturnCallback(String orderId) throws Exception;\n\n /**\n * 异常处理方法\n *\n * @param cause 产生的异常对象\n * @throws Exception 可能产生的任何异常\n */\n void onExceptionCaught(Throwable cause) throws Exception;\n\n /**\n * @param appId 微信公众号应用ID\n * @return 获取微信JS接口的临时票据\n * @throws Exception 可能产生的任何异常\n */\n String getJsApiTicket(String appId) throws Exception;\n}",
"public interface IWxPayModuleCfg {\n\n /**\n * @return 微信支付账户提供者接口实现类, 若未提供则使用默认配置\n */\n IWxPayAccountProvider getAccountProvider();\n\n /**\n * @return 支付事件处理器\n */\n IWxPayEventHandler getEventHandler();\n\n /**\n * @return 默认微信支付帐户ID, 默认值: 若采用账户提供者接口默认实现时取值默认应用ID, 否则为空\n */\n String getDefaultAccountId();\n\n /**\n * @return 调用JS支付的JSP视图文件路径, 默认值: wxpay_jsapi\n */\n String getJsApiView();\n\n /**\n * @return 调用扫码支付的JSP视图文件路径, 默认值: wxpay_native\n */\n String getNativeView();\n\n /**\n * @return 禁用报文签名验证(验签), 默认值: false\n */\n boolean isSignCheckDisabled();\n}",
"public class WxPayAccountMeta implements Serializable {\n\n private static final Log _LOG = LogFactory.getLog(WxPayAccountMeta.class);\n\n /**\n * 公众帐号APP_ID\n */\n private String appId;\n\n /**\n * 商户号\n */\n private String mchId;\n\n /**\n * 商号密钥\n */\n private String mchKey;\n\n /**\n * 证书文件路径\n */\n private String certFilePath;\n\n /**\n * 是否开启沙箱测试模式, 默认值: false\n */\n private boolean sandboxEnabled;\n\n /**\n * 获取沙箱测试模式下的接口URL地址前缀, 默认值: sandboxnew\n */\n private String sandboxPrefix;\n\n private SSLConnectionSocketFactory connectionSocketFactory;\n\n /**\n * 异步通知URL\n */\n private String notifyUrl;\n\n public WxPayAccountMeta(String appId, String mchId, String mchKey, String notifyUrl) {\n this.appId = appId;\n this.mchId = mchId;\n this.mchKey = mchKey;\n this.notifyUrl = notifyUrl;\n }\n\n public WxPayAccountMeta(String appId, String mchId, String mchKey, String certFilePath, String notifyUrl) {\n this.appId = appId;\n this.mchId = mchId;\n this.mchKey = mchKey;\n this.certFilePath = certFilePath;\n this.notifyUrl = notifyUrl;\n }\n\n private void __doGetSandboxSignKeyIfNeed() {\n if (sandboxEnabled) {\n try {\n WxPaySandboxSignKey _request = new WxPaySandboxSignKey(this);\n WxPaySandboxSignKey.Response _response = _request.execute();\n if (_response.checkReturnCode()) {\n this.mchKey = _response.signkey();\n }\n } catch (Exception e) {\n _LOG.error(\"try get sandbox signkey error: \", RuntimeUtils.unwrapThrow(e));\n }\n }\n }\n\n public String getAppId() {\n return appId;\n }\n\n public void setAppId(String appId) {\n this.appId = appId;\n }\n\n public String getMchId() {\n return mchId;\n }\n\n public void setMchId(String mchId) {\n this.mchId = mchId;\n }\n\n public String getMchKey() {\n return mchKey;\n }\n\n public void setMchKey(String mchKey) {\n this.mchKey = mchKey;\n }\n\n public String getCertFilePath() {\n return certFilePath;\n }\n\n public void setCertFilePath(String certFilePath) {\n this.certFilePath = certFilePath;\n }\n\n public SSLConnectionSocketFactory getConnectionSocketFactory() {\n if (connectionSocketFactory == null) {\n synchronized (this) {\n if (connectionSocketFactory == null && StringUtils.isNotBlank(mchId) && StringUtils.isNotBlank(certFilePath)) {\n try {\n connectionSocketFactory = HttpClientHelper.createConnectionSocketFactory(new URL(certFilePath), mchId.toCharArray());\n } catch (Exception e) {\n _LOG.warn(\"\", RuntimeUtils.unwrapThrow(e));\n }\n }\n }\n }\n return connectionSocketFactory;\n }\n\n public void setConnectionSocketFactory(SSLConnectionSocketFactory connectionSocketFactory) {\n this.connectionSocketFactory = connectionSocketFactory;\n }\n\n public String getNotifyUrl() {\n return notifyUrl;\n }\n\n public void setNotifyUrl(String notifyUrl) {\n this.notifyUrl = notifyUrl;\n }\n\n public boolean isSandboxEnabled() {\n return sandboxEnabled;\n }\n\n public void setSandboxEnabled(boolean sandboxEnabled) {\n this.sandboxEnabled = sandboxEnabled;\n //\n __doGetSandboxSignKeyIfNeed();\n }\n\n public String getSandboxPrefix() {\n if (sandboxEnabled) {\n return sandboxPrefix;\n }\n return \"\";\n }\n\n public void setSandboxPrefix(String sandboxPrefix) {\n sandboxPrefix = StringUtils.defaultIfBlank(sandboxPrefix, \"sandboxnew\");\n if (StringUtils.startsWith(sandboxPrefix, \"/\")) {\n sandboxPrefix = StringUtils.substringAfter(sandboxPrefix, \"/\");\n }\n if (!StringUtils.endsWith(this.sandboxPrefix, \"/\")) {\n sandboxPrefix = sandboxPrefix + \"/\";\n }\n this.sandboxPrefix = sandboxPrefix;\n }\n}"
] | import net.ymate.payment.wxpay.IWxPay;
import net.ymate.payment.wxpay.IWxPayAccountProvider;
import net.ymate.payment.wxpay.IWxPayEventHandler;
import net.ymate.payment.wxpay.IWxPayModuleCfg;
import net.ymate.payment.wxpay.base.WxPayAccountMeta;
import net.ymate.platform.core.YMP;
import net.ymate.platform.core.lang.BlurObject;
import net.ymate.platform.core.util.ClassUtils;
import org.apache.commons.lang.NullArgumentException;
import org.apache.commons.lang.StringUtils;
import java.util.Map; | /*
* Copyright 2007-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.ymate.payment.wxpay.impl;
/**
* @author 刘镇 (suninformation@163.com) on 2017/06/15 下午 13:12
* @version 1.0
*/
public class DefaultModuleCfg implements IWxPayModuleCfg {
private IWxPayAccountProvider __accountProvider;
private IWxPayEventHandler __eventHandler;
private String __defaultAccountId;
private String __jsApiView;
private String __nativeView;
private boolean __signCheckDisabled;
public DefaultModuleCfg(YMP owner) {
Map<String, String> _moduleCfgs = owner.getConfig().getModuleConfigs(IWxPay.MODULE_NAME);
//
__accountProvider = ClassUtils.impl(_moduleCfgs.get("account_provider_class"), IWxPayAccountProvider.class, getClass());
if (__accountProvider == null) {
__accountProvider = new DefaultWxPayAccountProvider();
// | WxPayAccountMeta _meta = new WxPayAccountMeta(_moduleCfgs.get("app_id"), | 4 |
shekhargulati/rx-docker-client | rx-docker-client/src/main/java/com/shekhargulati/reactivex/docker/client/DefaultRxDockerClient.java | [
"public abstract class Dates {\n public static final String DOCKER_DATE_TIME_FORMAT = \"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'\";\n}",
"public abstract class StreamUtils {\n\n public static <T> Stream<T> iteratorToStream(Iterator<T> iterator) {\n return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false);\n }\n}",
"public abstract class Strings {\n\n public static boolean isEmptyOrNull(String str) {\n Optional<String> optional = Optional.ofNullable(str);\n return optional.flatMap(s -> s.trim().length() == 0 ? Optional.of(true) : Optional.of(false)).orElse(true);\n }\n}",
"public static <T> Stream<T> iteratorToStream(Iterator<T> iterator) {\n return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false);\n}",
"public static <T> void validate(T t, Predicate<T> predicate, String message) throws IllegalArgumentException {\n if (predicate.test(t)) {\n throw new IllegalArgumentException(message);\n }\n}"
] | import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.shekhargulati.reactivex.docker.client.representations.*;
import com.shekhargulati.reactivex.docker.client.utils.Dates;
import com.shekhargulati.reactivex.docker.client.utils.StreamUtils;
import com.shekhargulati.reactivex.docker.client.utils.Strings;
import com.shekhargulati.reactivex.rxokhttp.*;
import com.shekhargulati.reactivex.rxokhttp.functions.*;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.Observable;
import rx.Subscriber;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.util.AbstractMap.SimpleEntry;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Stream;
import static com.google.gson.FieldNamingPolicy.UPPER_CAMEL_CASE;
import static com.shekhargulati.reactivex.docker.client.utils.StreamUtils.iteratorToStream;
import static com.shekhargulati.reactivex.docker.client.utils.Validations.validate;
import static com.shekhargulati.reactivex.rxokhttp.ClientConfig.defaultConfig;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap; | /*
* The MIT License
*
* Copyright 2015 Shekhar Gulati <shekhargulati84@gmail.com>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.shekhargulati.reactivex.docker.client;
class DefaultRxDockerClient implements RxDockerClient {
private static final String EMPTY_BODY = "";
private final Logger logger = LoggerFactory.getLogger(DefaultRxDockerClient.class);
private final String apiUri;
private final RxHttpClient httpClient;
private final Gson gson = new GsonBuilder()
.setFieldNamingPolicy(UPPER_CAMEL_CASE) | .setDateFormat(Dates.DOCKER_DATE_TIME_FORMAT) | 0 |
xcurator/xcurator | src/edu/toronto/cs/xcurator/discoverer/HashBasedEntityInterlinking.java | [
"public class RdfUriBuilder {\n\n private final String typeUriBase;\n private final String propertyUriBase;\n\n private final String typePrefix;\n private final String propertyPrefix;\n\n public RdfUriBuilder(RdfUriConfig config) {\n this.typeUriBase = config.getTypeResourceUriBase();\n this.propertyUriBase = config.getPropertyResourceUriBase();\n this.typePrefix = config.getTypeResourcePrefix();\n this.propertyPrefix = config.getPropertyResourcePrefix();\n }\n\n private String getUri(Node node, String uriBase) {\n return uriBase + \"/\" + node.getLocalName();\n }\n\n public String getRdfTypeUri(Element element) {\n return getUri(element, typeUriBase);\n }\n\n public String getRdfPropertyUri(Node node) {\n return getUri(node, propertyUriBase);\n }\n\n public String getRdfPropertyUriForValue(Element element) {\n return propertyUriBase + \"/value\";\n }\n\n public String getRdfRelationUriFromElements(Element subject, Element object) {\n return getUri(object, propertyUriBase);\n }\n\n public String getRdfRelationUriFromEntities(Schema subject, Schema object) {\n return propertyUriBase + \"/\" + object.getName();\n }\n\n}",
"public class Attribute implements MappingModel {\n\n Schema schema;\n\n SearchPath paths;\n\n String rdfUri;\n\n String xmlTypeUri;\n\n private Set<String> instances;\n\n boolean isKey;\n\n public Attribute(Schema schema, String rdfUri, String xmlTypeUri) {\n this.schema = schema;\n this.rdfUri = rdfUri;\n this.xmlTypeUri = xmlTypeUri;\n this.paths = new SearchPath();\n this.instances = new HashSet<>();\n this.isKey = false;\n }\n\n @Override\n public String getId() {\n return schema.xmlTypeUri + \".\" + xmlTypeUri;\n }\n\n @Override\n public void addPath(String path) {\n paths.addPath(path);\n }\n\n @Override\n public String getPath() {\n return paths.getPath();\n }\n\n public boolean isKey() {\n return this.isKey;\n }\n\n public void asKey() {\n isKey = true;\n }\n\n public void addInstance(String value) {\n value = value.trim();\n value = value.replaceAll(\"[\\\\t\\\\n\\\\r]+\", \" \");\n this.instances.add(value);\n }\n\n public void addInstances(Set<String> others) {\n for (String val : others) {\n addInstance(val);\n }\n }\n\n public Set<String> getInstances() {\n return instances;\n }\n\n public String getRdfUri() {\n return rdfUri;\n }\n\n public void resetRdfUri(String rdfUri) {\n this.rdfUri = rdfUri;\n }\n\n public Schema getSchema() {\n return this.schema;\n }\n\n @Override\n public String toString() {\n StringBuilder instanceSb = new StringBuilder();\n instanceSb.append(\"[\");\n if (!instances.isEmpty()) {\n for (String str : instances) {\n// str = str.replace(\"\\\"\", \"\\\\\\\"\");\n str = StringEscapeUtils.escapeJava(str);\n if (str.length() > 30) {\n str = str.substring(0, 30) + \"...\";\n }\n instanceSb.append(\"\\\"\").append(str).append(\"\\\"\").append(\", \");\n }\n instanceSb.deleteCharAt(instanceSb.length() - 1);\n instanceSb.deleteCharAt(instanceSb.length() - 1);\n }\n instanceSb.append(\"]\");\n return \"{\"\n + \"\\\"Attribute\\\": {\"\n + \"\\\"rdfUri\\\":\" + \"\\\"\" + rdfUri + \"\\\"\"\n + \", \\\"xmlTypeUri\\\":\" + \"\\\"\" + xmlTypeUri + \"\\\"\"\n + \", \\\"instances\\\":\" + instanceSb\n + '}'\n + '}';\n }\n}",
"public class Schema implements MappingModel {\n\n NsContext namespaceContext;\n\n // The XML type URI of this entity\n String xmlTypeUri;\n\n Map<String, Relation> relations;\n\n Map<String, Attribute> attributes;\n\n SearchPath paths;\n\n String rdfTypeUri;\n\n // The xml instances of this entity\n Set<Element> instances;\n\n // The name of the entity, used to construct relation\n String name;\n\n public Schema(String rdfTypeUri, String xmlTypeUri, NsContext nsContext,\n String name) {\n this(rdfTypeUri, xmlTypeUri, nsContext);\n this.name = name;\n }\n\n public Schema(String rdfTypeUri, String xmlTypeUri, NsContext nsContext) {\n this.rdfTypeUri = rdfTypeUri;\n this.paths = new SearchPath();\n this.instances = new HashSet<>();\n this.namespaceContext = nsContext;\n relations = new HashMap<>();\n attributes = new HashMap<>();\n this.xmlTypeUri = xmlTypeUri;\n }\n\n @Override\n /**\n * The entity uses the XML type URI as its ID\n */\n public String getId() {\n return xmlTypeUri;\n }\n\n @Override\n public String getPath() {\n return paths.getPath();\n }\n\n @Override\n public void addPath(String path) {\n paths.addPath(path);\n }\n\n public String getName() {\n return name;\n }\n\n public void addInstance(Element element) {\n this.instances.add(element);\n }\n\n public void addAttribute(Attribute attr) {\n Attribute existAttr = attributes.get(attr.getId());\n if (existAttr != null) {\n existAttr.addPath(attr.getPath());\n existAttr.addInstances(attr.getInstances());\n return;\n }\n attributes.put(attr.getId(), attr);\n }\n\n public void addRelation(Relation rl) {\n Relation existRel = relations.get(rl.getId());\n if (existRel != null) {\n existRel.addPath(rl.getPath());\n return;\n }\n relations.put(rl.getId(), rl);\n }\n\n public void mergeNamespaceContext(NsContext nsContext, boolean override) {\n this.namespaceContext.merge(nsContext, override);\n }\n\n public boolean hasAttribute(String id) {\n return attributes.containsKey(id);\n }\n\n public boolean hasRelation(String id) {\n return relations.containsKey(id);\n }\n\n public Attribute getAttribute(String id) {\n return attributes.get(id);\n }\n\n public int getAttributesCount() {\n return attributes.size();\n }\n\n public int getRelationsCount() {\n return relations.size();\n }\n\n public Relation getRelation(String id) {\n return relations.get(id);\n }\n\n public void removeRelation(String id) {\n relations.remove(id);\n }\n\n public Iterator<Attribute> getAttributeIterator() {\n return attributes.values().iterator();\n }\n\n public Iterator<Relation> getRelationIterator() {\n return relations.values().iterator();\n }\n\n public NsContext getNamespaceContext() {\n return namespaceContext;\n }\n\n public Iterator<Element> getXmlInstanceIterator() {\n return instances.iterator();\n }\n\n public int getXmlInstanceCount() {\n return instances.size();\n }\n\n // Return the XML type from which this entity was extracted\n public String getXmlTypeUri() {\n return xmlTypeUri;\n }\n\n public String getRdfTypeUri() {\n return rdfTypeUri;\n }\n\n public void resetRdfTypeUri(String typeUri) {\n rdfTypeUri = typeUri;\n }\n\n @Override\n public String toString() {\n StringBuilder sbForInstances = new StringBuilder();\n sbForInstances.append(\"[\");\n if (!instances.isEmpty()) {\n for (Element elem : instances) {\n sbForInstances.append(elem.getNodeValue()).append(\", \");\n }\n sbForInstances.deleteCharAt(sbForInstances.length() - 1);\n sbForInstances.deleteCharAt(sbForInstances.length() - 1);\n }\n sbForInstances.append(\"]\");\n return \"{\"\n + \"\\\"Schema\\\": {\"\n + \"\\\"namespaceContext\\\":\" + \"\\\"\" + namespaceContext + \"\\\"\"\n + \", \\\"xmlTypeUri\\\":\" + \"\\\"\" + xmlTypeUri + \"\\\"\"\n + \", \\\"relations\\\":\" + IOUtils.printMapAsJson(relations)\n + \", \\\"attributes\\\":\" + IOUtils.printMapAsJson(attributes)\n + \", \\\"paths\\\":\" + \"\\\"\" + paths + \"\\\"\"\n + \", \\\"rdfTypeUri\\\":\" + \"\\\"\" + rdfTypeUri + \"\\\"\"\n// + \", \\\"instances\\\":\" + \"\\\"\" + sbForInstances + \"\\\"\"\n + \", \\\"name\\\":\" + \"\\\"\" + name + \"\\\"\"\n + \"}\"\n + \"}\";\n }\n\n}",
"public interface Mapping {\n\n /**\n * Check if this mapping is initialized.\n *\n * @return\n */\n boolean isInitialized();\n\n /**\n * Set this mapping as initialized, return success flag.\n *\n * @return true if successfully initialized, false if not successful.\n */\n boolean setInitialized();\n\n /**\n * Set the base namespace context of the XML document to be transformed\n * using this mapping. This namespace context can be overrided by individual\n * entities.\n *\n * @param nsContext\n */\n void setBaseNamespaceContext(NsContext nsContext);\n\n /**\n * Get the base namespace context of the XML document to be transformed\n * using this mapping.\n *\n * @return\n */\n NsContext getBaseNamespaceContext();\n\n void addEntity(Schema schema);\n\n Schema getEntity(String id);\n\n void removeEntity(String id);\n\n public Map<String, Schema> getEntities();\n\n Iterator<Schema> getEntityIterator();\n\n public void removeInvalidRelations();\n\n}",
"public class Relation implements MappingModel {\n\n Schema subject;\n\n Schema object;\n\n String rdfUri;\n\n String objectXmlTypeUri;\n\n Set<Reference> references;\n\n // The path to the \n SearchPath paths;\n\n public Relation(Schema subject, Schema object, String rdfUri) {\n this.subject = subject;\n this.object = object;\n this.rdfUri = rdfUri;\n this.references = new HashSet<>();\n this.paths = new SearchPath();\n }\n\n // This constructor is for deserializing the mapping file\n // since the object entity may not have deserialized yet.\n public Relation(Schema subject, Schema object, String rdfUri, String objectXmlTypeUri) {\n this(subject, null, rdfUri);\n this.objectXmlTypeUri = objectXmlTypeUri;\n }\n\n public void addReference(Reference reference) {\n references.add(reference);\n }\n\n public Iterator<Reference> getReferenceIterator() {\n return references.iterator();\n }\n\n public Set<Reference> getReferences() {\n return references;\n }\n\n public String getObjectXmlTypeUri() {\n return object == null ? objectXmlTypeUri : object.getXmlTypeUri();\n }\n\n @Override\n public String getId() {\n return subject.getXmlTypeUri() + \".\" + getObjectXmlTypeUri();\n }\n\n @Override\n public void addPath(String path) {\n paths.addPath(path);\n }\n\n @Override\n public String getPath() {\n return paths.getPath();\n }\n\n public String getRdfUri() {\n return rdfUri;\n }\n\n @Override\n public String toString() {\n return \"{\"\n + \"\\\"Relation\\\": {\"\n + \"\\\"rdfUri\\\":\" + \"\\\"\" + rdfUri + \"\\\"\"\n + \", \\\"objectXmlTypeUri\\\":\" + \"\\\"\" + objectXmlTypeUri + \"\\\"\"\n + '}'\n + '}';\n }\n\n}"
] | import edu.toronto.cs.xcurator.common.DataDocument;
import edu.toronto.cs.xcurator.common.RdfUriBuilder;
import edu.toronto.cs.xcurator.mapping.Attribute;
import edu.toronto.cs.xcurator.mapping.Schema;
import edu.toronto.cs.xcurator.mapping.Mapping;
import edu.toronto.cs.xcurator.mapping.Reference;
import edu.toronto.cs.xcurator.mapping.Relation;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set; | /*
* Copyright (c) 2013, University of Toronto.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package edu.toronto.cs.xcurator.discoverer;
/**
*
* @author ekzhu
*/
public class HashBasedEntityInterlinking implements MappingDiscoveryStep {
private final RdfUriBuilder rdfUriBuilder;
public HashBasedEntityInterlinking(RdfUriBuilder rdfUriBuilder) {
this.rdfUriBuilder = rdfUriBuilder;
}
@Override | public void process(List<DataDocument> dataDocuments, Mapping mapping) { | 3 |
dariober/ASCIIGenome | src/test/java/samTextViewer/GenomicCoordsTest.java | [
"public class Config {\n\t\n\t// C O N S T R U C T O R \n\t\n\tprivate static final Map<ConfigKey, String> config= new HashMap<ConfigKey, String>();\n\n\tpublic Config(String source) throws IOException, InvalidConfigException {\n\t\t\n\t\tnew Xterm256();\n\t\t\n\t\tString RawConfigFile= Config.getConfigFileAsString(source).replaceAll(\"\\t\", \" \").toLowerCase();\n\t\t\n\t\t// This will give one string per line\n\t\tList<String> raw= Splitter.on(\"\\n\").omitEmptyStrings().trimResults().splitToList(RawConfigFile);\n\n\t\t//List<String> config= new ArrayList<String>();\n\t\tfor(String x : raw){\n\t\t\tx= x.replaceAll(\"#.*\", \"\").trim();\n\t\t\tif( ! x.isEmpty()){\n\t\t\t\tList<String> keyValuePair= Splitter.on(\" \").omitEmptyStrings().trimResults().splitToList(x);\n\t\t\t\tif(ConfigKey.getValues().contains(keyValuePair.get(0))){\n\t\t\t\t\tconfig.put(ConfigKey.valueOf(keyValuePair.get(0)), keyValuePair.get(1));\n\t\t\t\t} else {\n\t\t\t\t\tSystem.err.println(\"Unrecognized configuration key: \" + keyValuePair.get(0));\n\t\t\t\t\t// throw new RuntimeException();\n\t\t\t\t\tthrow new InvalidConfigException();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// Check all fields have been populated\n\t\tfor(ConfigKey key : ConfigKey.values()){\n\t\t\tif( ! config.containsKey(key)){\n\t\t\t\tSystem.err.println(\"Missing configuration key: \" + key);\n\t\t\t\tthrow new InvalidConfigException();\n\t\t\t}\n\t\t}\n\t\ttry {\n\t\t\tcolorNameToInt();\n\t\t} catch (InvalidColourException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\t// M E T H O D S\n\tpublic static String help(){\n\t\tList<String> help= new ArrayList<String>();\n\t\tfor(ConfigKey key : ConfigKey.values()){\n\t\t\thelp.add(key + \"\\t\" + Config.get(key) + \"\\t#\\t\" + key.getDescription());\n\t\t}\n\t\tList<String> table = Utils.tabulateList(help, -1);\n\t\treturn Joiner.on(\"\\n\").join(table);\n\t}\n\t\n\tprivate static String getConfigFileAsString(String source) throws IOException, InvalidConfigException{\n\t\t\n\t\tString rawConfigFile= \"\";\n\n\t\t// Is source null or empty string?\n\t\tif(source == null || source.isEmpty()){\n\t\t\t// See if default config file exists\n\t\t\tFile def= new File(System.getProperty(\"user.home\"), \".asciigenome_config\");\n\t\t\tif(def.isFile()){\n\t\t\t\trawConfigFile= FileUtils.readFileToString(def, \"UTF-8\");\n\t\t\t} else {\n\t\t\t\t// If not, read from resource\n\t\t\t\tInputStream res= Config.class.getResourceAsStream(\"/config/black_on_white.conf\");\n\t\t\t\trawConfigFile= IOUtils.toString(res, \"UTF-8\");\n\t\t\t}\n\t\t\treturn rawConfigFile;\n\t\t}\n\n\t\tsource= Utils.tildeToHomeDir(source);\n\t\t\n\t\t// Is source a local file? E.g. /path/to/my.conf\n\t\tif((new File(source)).isFile()){\n\t\t\trawConfigFile= FileUtils.readFileToString(new File(source), \"UTF-8\");\n\t\t\treturn rawConfigFile;\n\t\t}\n\t\t\n\t\t// Is source a tag matching a configuration file in resources? E.g. \"black_on_white\"\n\t\ttry{\n\t\t\tInputStream res= Config.class.getResourceAsStream(\"/config/\" + source + \".conf\");\n\t\t\trawConfigFile= IOUtils.toString(res, \"UTF-8\");\n\t\t\treturn rawConfigFile;\n\t\t} catch(Exception e){\n\t\t\t// \n\t\t}\t\t\n\t\tthrow new InvalidConfigException();\n\t\t\n\t} \n\t\n\t/** We convert the color names to the corresponding int. This is because looking up\n\t * by int is much faster than by name. \n\t * @throws InvalidColourException \n\t * */\n\tprivate static void colorNameToInt() throws InvalidColourException{\n\t\tfor(ConfigKey key : config.keySet()){\n\t\t\tif(ConfigKey.colorKeys().contains(key)){\n\t\t\t\tint colorInt = Xterm256.colorNameToXterm256(config.get(key));\n\t\t\t\tconfig.put(key, Integer.toString(colorInt));\n\t\t\t}\n\t\t}\n\t}\n\t\n\t/** Get xterm256 color corresponding to this configuration key\n\t * */\n\tpublic static int get256Color(ConfigKey key) throws InvalidColourException{\n\t\tnew Xterm256();\n\t\treturn Xterm256.colorNameToXterm256(config.get(key));\n\t}\n\n\t/** Get value associated to this configuration key \n\t * */\n\tpublic static String get(ConfigKey key) {\n\t\treturn config.get(key);\n\t}\t\t\n\n\tpublic static void set(ConfigKey key, String value) throws InvalidColourException{\n\t\tif(ConfigKey.booleanKeys().contains(key)){\n\t\t\tboolean bool= Utils.asBoolean(value);\n\t\t\tconfig.put(key, Boolean.toString(bool));\n\t\t} \n\t\telse if(ConfigKey.integerKeys().contains(key)){\n\t\t\tInteger.valueOf(value);\n\t\t\tconfig.put(key, value);\n\t\t}\n\t\telse {\n\t\t\tconfig.put(key, value);\n\t\t\tcolorNameToInt();\n\t\t}\n\t}\n\t\n//\t/**Return the key-value map of configuration parameters\n//\t * */\n//\tpublic static Map<ConfigKey, String> getConfigMap(){\n//\t\treturn config;\n//\t}\n}",
"public class InvalidColourException extends Exception {\n\n\t/**\n\t * \n\t */\n\tprivate static final long serialVersionUID = 1L;\n\n}",
"public class InvalidCommandLineException extends Exception {\n\n\t/**\n\t * \n\t */\n\tprivate static final long serialVersionUID = 1L;\n\n}",
"public class InvalidConfigException extends Exception {\n\tprivate static final long serialVersionUID = 1L;\n}",
"public class InvalidGenomicCoordsException extends Exception {\n\n\t/**\n\t * \n\t */\n\tprivate static final long serialVersionUID = 1L;\n\n}"
] | import static org.junit.Assert.*;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import coloring.Config;
import exceptions.InvalidColourException;
import exceptions.InvalidCommandLineException;
import exceptions.InvalidConfigException;
import exceptions.InvalidGenomicCoordsException;
import htsjdk.samtools.SAMSequenceDictionary;
import htsjdk.samtools.SAMSequenceRecord;
import htsjdk.samtools.SamReader;
import htsjdk.samtools.SamReaderFactory; | package samTextViewer;
public class GenomicCoordsTest {
static SamReaderFactory srf=SamReaderFactory.make();
static SamReader samReader= srf.open(new File("test_data/ds051.short.bam"));
public static SAMSequenceDictionary samSeqDict= samReader.getFileHeader().getSequenceDictionary();
public static String fastaFile= "test_data/chr7.fa";
@Before
public void initConfig() throws IOException, InvalidConfigException{ | new Config(null); | 0 |
pedrovgs/Nox | nox/src/main/java/com/github/pedrovgs/nox/NoxView.java | [
"public interface ImageLoader {\n\n /**\n * Configures an url to be downloaded.\n */\n ImageLoader load(String url);\n\n /**\n * Configures a resource id to be loaded.\n */\n ImageLoader load(Integer resourceId);\n\n /**\n * Loads a placeholder using a resource id to be shown while the external resource is being\n * downloaded.\n */\n ImageLoader withPlaceholder(Integer placeholderId);\n\n /**\n * Applies a circular transformation to transform the source bitmap into a circular one.\n */\n ImageLoader useCircularTransformation(boolean useCircularTransformation);\n\n /**\n * Changes the external resource size once it downloaded and before to notify the listener.\n */\n ImageLoader size(int size);\n\n /**\n * Configures a listener where the ImageLoader will notify once the resource be loaded. This\n * method has to be called to start the resource download. The listener used can't be null.\n */\n void notify(Listener listener);\n\n /**\n * Pauses all the resource downloads associated to this library.\n */\n void pause();\n\n /**\n * Resumes all the resource downloads associated to this library.\n */\n void resume();\n\n /**\n * Cancels all the pending requests to download a resource.\n */\n void cancelPendingRequests();\n\n /**\n * Declares some methods which will be called during the resource download process implemented by\n * the ImageLoader. Use this interface to be notified when the placeholder and the final resource\n * be ready to be used.\n */\n interface Listener {\n\n void onPlaceholderLoaded(Drawable placeholder);\n\n void onImageLoaded(Bitmap image);\n\n void onError();\n\n void onDrawableLoaded(Drawable drawable);\n }\n}",
"public class ImageLoaderFactory {\n\n public static ImageLoader getPicassoImageLoader(Context context) {\n return new PicassoImageLoader(context);\n }\n}",
"public abstract class Shape {\n\n private final ShapeConfig shapeConfig;\n\n private float[] noxItemsXPositions;\n private float[] noxItemsYPositions;\n private int offsetX;\n private int offsetY;\n private int minX;\n private int maxX;\n private int minY;\n private int maxY;\n\n public Shape(ShapeConfig shapeConfig) {\n this.shapeConfig = shapeConfig;\n int numberOfElements = shapeConfig.getNumberOfElements();\n this.noxItemsXPositions = new float[numberOfElements];\n this.noxItemsYPositions = new float[numberOfElements];\n }\n\n /**\n * Configures the new offset to apply to the Shape.\n */\n public void setOffset(int offsetX, int offsetY) {\n this.offsetX = offsetX;\n this.offsetY = offsetY;\n }\n\n /**\n * Shape extensions have implement this method and configure the position in the x and y axis for\n * every NoxItem.\n */\n public abstract void calculate();\n\n /**\n * Returns the X position of a NoxItem for the current Shape.\n */\n public final float getXForItemAtPosition(int position) {\n return noxItemsXPositions[position];\n }\n\n /**\n * Returns the Y position of a NoxItem for the current Shape.\n */\n public final float getYForItemAtPosition(int position) {\n return noxItemsYPositions[position];\n }\n\n /**\n * Returns true if the view should be rendered inside the view window taking into account the\n * offset applied by the scroll effect.\n */\n public final boolean isItemInsideView(int position) {\n float x = (getXForItemAtPosition(position) + offsetX);\n float y = (getYForItemAtPosition(position) + offsetY);\n float itemSize = getNoxItemSize();\n int viewWidth = shapeConfig.getViewWidth();\n boolean matchesHorizontally = x + itemSize >= 0 && x <= viewWidth;\n float viewHeight = shapeConfig.getViewHeight();\n boolean matchesVertically = y + itemSize >= 0 && y <= viewHeight;\n return matchesHorizontally && matchesVertically;\n }\n\n /**\n * Returns the minimum X position the view should show during the scroll process.\n */\n public final int getMinX() {\n return (int) (this.minX - getNoxItemMargin());\n }\n\n /**\n * Returns the maximum X position the view should show during the scroll process.\n */\n public final int getMaxX() {\n return (int) (this.maxX + getNoxItemSize() + getNoxItemMargin()\n - getShapeConfig().getViewWidth());\n }\n\n /**\n * Returns the minimum Y position the view should show during the scroll process.\n */\n public final int getMinY() {\n return (int) (this.minY - getNoxItemMargin());\n }\n\n /**\n * Returns the maximum Y position the view should show during the scroll process.\n */\n public final int getMaxY() {\n return (int) (this.maxY + getNoxItemMargin() + getNoxItemSize()\n - getShapeConfig().getViewHeight());\n }\n\n /**\n * Returns the over scroll used by the view during the fling process. By default this value will\n * be equals to the configured margin.\n */\n public int getOverSize() {\n return (int) shapeConfig.getItemMargin();\n }\n\n /**\n * Returns the ShapeConfig used to create this Shape.\n */\n public final ShapeConfig getShapeConfig() {\n return shapeConfig;\n }\n\n /**\n * Returns the number of elements the Shape is using to calculate NoxItems positions.\n */\n public int getNumberOfElements() {\n return getShapeConfig().getNumberOfElements();\n }\n\n /**\n * Returns the position of the NoxView if any of the previously configured NoxItem instances is\n * hit. If there is no any NoxItem hit this method returns -1.\n */\n public int getNoxItemHit(float x, float y) {\n int noxItemPosition = -1;\n for (int i = 0; i < getNumberOfElements(); i++) {\n float noxItemX = getXForItemAtPosition(i) + offsetX;\n float noxItemY = getYForItemAtPosition(i) + offsetY;\n float itemSize = getNoxItemSize();\n boolean matchesHorizontally = x >= noxItemX && x <= noxItemX + itemSize;\n boolean matchesVertically = y >= noxItemY && y <= noxItemY + itemSize;\n if (matchesHorizontally && matchesVertically) {\n noxItemPosition = i;\n break;\n }\n }\n return noxItemPosition;\n }\n\n /**\n * Configures the number of element the Shape is going to use to calculate NoxItems positions.\n * This method resets the previous position calculus.\n */\n public void setNumberOfElements(int numberOfElements) {\n this.shapeConfig.setNumberOfElements(numberOfElements);\n this.noxItemsXPositions = new float[numberOfElements];\n this.noxItemsYPositions = new float[numberOfElements];\n }\n\n /**\n * Configures the X position for a given NoxItem indicated with the item position. This method\n * uses two counters to calculate the Shape minimum and maximum X position used to configure the\n * Shape scroll.\n */\n protected final void setNoxItemXPosition(int position, float x) {\n noxItemsXPositions[position] = x;\n minX = (int) Math.min(x, minX);\n maxX = (int) Math.max(x, maxX);\n }\n\n /**\n * Configures the Y position for a given NoxItem indicated with the item position. This method\n * uses two counters to calculate the Shape minimum and maximum Y position used to configure the\n * Shape scroll.\n */\n protected final void setNoxItemYPosition(int position, float y) {\n noxItemsYPositions[position] = y;\n minY = (int) Math.min(y, minY);\n maxY = (int) Math.max(y, maxY);\n }\n\n /**\n * Returns the NoxItem size taking into account the scale factor.\n */\n protected float getNoxItemSize() {\n return getShapeConfig().getItemSize();\n }\n\n /**\n * Returns the NoxIte margin taking into account the scale factor.\n */\n private float getNoxItemMargin() {\n return getShapeConfig().getItemMargin();\n }\n}",
"public class ShapeConfig {\n\n private int numberOfElements;\n private final int viewWidth;\n private final int viewHeight;\n private final float itemSize;\n private final float itemMargin;\n\n public ShapeConfig(int numberOfElements, int viewWidth, int viewHeight, float itemSize,\n float itemMargin) {\n this.numberOfElements = numberOfElements;\n this.viewWidth = viewWidth;\n this.viewHeight = viewHeight;\n this.itemSize = itemSize;\n this.itemMargin = itemMargin;\n }\n\n public int getNumberOfElements() {\n return numberOfElements;\n }\n\n public int getViewWidth() {\n return viewWidth;\n }\n\n public int getViewHeight() {\n return viewHeight;\n }\n\n public float getItemSize() {\n return itemSize;\n }\n\n public float getItemMargin() {\n return itemMargin;\n }\n\n public void setNumberOfElements(int numberOfElements) {\n this.numberOfElements = numberOfElements;\n }\n}",
"public class ShapeFactory {\n\n public static final int LINEAR_SHAPE_KEY = 0;\n public static final int LINEAR_CENTERED_SHAPE_KEY = 1;\n public static final int CIRCULAR_SHAPE_KEY = 2;\n public static final int FIXED_CIRCULAR_SHAPE_KEY = 3;\n public static final int SPIRAL_SHAPE_KEY = 4;\n\n public static Shape getLinearShape(ShapeConfig shapeConfig) {\n return new LinearShape(shapeConfig);\n }\n\n public static Shape getLinearCenteredShape(ShapeConfig shapeConfig) {\n return new LinearCenteredShape(shapeConfig);\n }\n\n public static Shape getSpiralShape(ShapeConfig shapeConfig) {\n return new SpiralShape(shapeConfig);\n }\n\n public static Shape getCircularShape(ShapeConfig shapeConfig) {\n return new CircularShape(shapeConfig);\n }\n\n public static Shape getFixedCircularShape(ShapeConfig shapeConfig) {\n return new FixedCircularShape(shapeConfig);\n }\n\n public static Shape getShapeByKey(int shapeKey, ShapeConfig shapeConfig) {\n Shape shape;\n switch (shapeKey) {\n case LINEAR_SHAPE_KEY:\n shape = new LinearShape(shapeConfig);\n break;\n case LINEAR_CENTERED_SHAPE_KEY:\n shape = new LinearCenteredShape(shapeConfig);\n break;\n case CIRCULAR_SHAPE_KEY:\n shape = new CircularShape(shapeConfig);\n break;\n case FIXED_CIRCULAR_SHAPE_KEY:\n shape = new FixedCircularShape(shapeConfig);\n break;\n case SPIRAL_SHAPE_KEY:\n shape = new SpiralShape(shapeConfig);\n break;\n default:\n shape = new LinearShape(shapeConfig);\n }\n return shape;\n }\n}"
] | import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.v4.view.GestureDetectorCompat;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import com.github.pedrovgs.nox.imageloader.ImageLoader;
import com.github.pedrovgs.nox.imageloader.ImageLoaderFactory;
import com.github.pedrovgs.nox.shape.Shape;
import com.github.pedrovgs.nox.shape.ShapeConfig;
import com.github.pedrovgs.nox.shape.ShapeFactory;
import java.util.List;
import java.util.Observable;
import java.util.Observer; | /*
* Copyright (C) 2015 Pedro Vicente Gomez Sanchez.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.pedrovgs.nox;
/**
* Main library component. This custom view receives a List of Nox objects and creates a awesome
* panel full of images following different shapes. This new UI component is going to be similar to
* the Apple's watch main menu user interface.
*
* NoxItem objects are going to be used to render the user interface using the resource used
* to render inside each element and a view holder.
*
* @author Pedro Vicente Gomez Sanchez.
*/
public class NoxView extends View {
private NoxConfig noxConfig; | private Shape shape; | 2 |
chipKIT32/chipKIT-importer | src/com/microchip/mplab/nbide/embedded/arduino/wizard/ProjectSetupStep.java | [
"public abstract class ArduinoConfig {\n \n \n public static final String ROOT_PLATFORM_VENDOR = \"arduino\";\n public static final String ROOT_PLATFORM_ARCH = \"avr\";\n \n private static final Logger LOGGER = Logger.getLogger(ArduinoConfig.class.getName());\n private static ArduinoConfig INSTANCE;\n \n public static synchronized ArduinoConfig getInstance() {\n if ( INSTANCE == null ) {\n if ( Utilities.isMac() ){\n INSTANCE = new MacOSXArduinoConfig();\n } else if ( Utilities.isWindows() ) {\n INSTANCE = new Win32ArduinoConfig();\n } else {\n INSTANCE = new LinuxArduinoConfig();\n }\n }\n return INSTANCE;\n }\n \n public abstract Path getSettingsPath();\n public abstract Path getDefaultSketchPath(); \n public abstract Path findArduinoBuilderPath( Path arduinoInstallPath );\n \n // TODO: Change return type to Optional\n public Path getSketchPath() {\n return findInPreferences( line -> line.startsWith(\"sketchbook.path\") ) \n .map( Paths::get )\n .orElseGet( () -> {\n LOGGER.warning(\"Failed to find sketchbook path in the Arduino preferences file. Using default location.\");\n return getDefaultSketchPath(); \n });\n }\n \n // TODO: Change return type to Optional\n public Path findUserLibrariesPath() {\n return getSketchPath().resolve(\"libraries\");\n }\n \n // TODO: Change return type to Optional\n public Path getPackagesPath() {\n return getSettingsPath().resolve(\"packages\");\n }\n \n // TODO: Change return type to Optional\n public Path getPlatformRootPath( Platform platform ) {\n return getPackagesPath().resolve( platform.getVendor() );\n }\n \n public boolean isValidArduinoInstallPath(Path path) {\n Path p = findArduinoBuilderPath(path);\n return Files.exists(p);\n }\n\n public Optional<Version> findCurrentVersion() {\n return findHighestArduinoVersionLine().map( \n line -> new Version( line.split(\"=\")[0].substring(9, 14) ) \n );\n } \n \n public Optional<Path> findInstallPath() {\n return findHardwarePath().map( p -> p.getParent() );\n }\n \n public Optional<Path> findHardwarePath() {\n// return findInPreferences( line -> line.split(\"=\")[0].trim().endsWith(\"hardwarepath\") ).map( Paths::get );\n return findHighestArduinoVersionLine().map( line -> Paths.get( line.split(\"=\")[1] ) );\n }\n \n private Optional<String> findHighestArduinoVersionLine() {\n List<String> hardwarePathLines = filterPreferences( line -> line.split(\"=\")[0].trim().endsWith(\"hardwarepath\") ).collect( Collectors.toList() );\n Version highestVersion = new Version(\"0.0.0\");\n String highestVersionLine = null;\n \n for ( String line : hardwarePathLines ) {\n // e.g: last.ide.1.8.2.hardwarepath=...\n Version v = new Version( line.substring(9, 14) );\n if ( v.compareTo(highestVersion) > 0 ) {\n highestVersion = v;\n highestVersionLine = line;\n }\n }\n \n return Optional.ofNullable( highestVersionLine );\n }\n \n public Optional<String> findInPreferences( Predicate<String> predicate ) {\n return filterPreferences(predicate)\n .findFirst()\n .map(line -> {\n String[] tokens = line.split(\"=\");\n return (tokens.length > 1) ? tokens[1].trim() : null;\n });\n }\n \n private Stream<String> filterPreferences( Predicate<String> predicate ) {\n Path preferencesPath = getSettingsPath().resolve(\"preferences.txt\");\n LOGGER.info( \"Reading Arduino preferences from: \" + preferencesPath );\n try {\n return Files.readAllLines(preferencesPath).stream()\n .map( line -> line.trim() )\n .filter( line -> !line.startsWith(\"#\") )\n .filter( predicate );\n } catch (IOException ex) {\n LOGGER.log(Level.SEVERE, \"Failed to read the preferences.txt file\", ex);\n return Stream.empty();\n }\n }\n \n public Optional <Path> getDefaultArduinoPlatformPath() {\n return findInPreferences( line -> line.split(\"=\")[0].trim().endsWith(\"hardwarepath\") )\n .map( hardwarePath -> Paths.get( hardwarePath, ROOT_PLATFORM_VENDOR, ROOT_PLATFORM_ARCH ) );\n }\n\n public Optional<Path> findToolsPath() {\n return findHardwarePath().map( hardwarePath -> hardwarePath.resolve(\"tools\").resolve(ROOT_PLATFORM_ARCH) );\n }\n \n // TODO: Change return type to Optional\n public Path findToolsBuilderPath(Path arduinoInstallPath) {\n return arduinoInstallPath.resolve(\"tools-builder\");\n }\n\n // TODO: Change return type to Optional\n public Path findBuiltInLibrariesPath(Path arduinoInstallPath) {\n return arduinoInstallPath.resolve(\"libraries\");\n }\n \n public boolean isCurrentVersionValid(Version minimumValidVersion) {\n if ( minimumValidVersion == null ) throw new IllegalArgumentException(\"minimumValidVersion cannot be null\");\n return findCurrentVersion().map( v -> v.compareTo( minimumValidVersion ) >= 0 ).get();\n }\n \n}",
"public class Platform extends ArduinoDataSource {\n\n private static final Logger LOGGER = Logger.getLogger(Platform.class.getName());\n\n public static final String PLATFORM_FILENAME = \"platform.txt\";\n public static final String BOARDS_FILENAME = \"boards.txt\";\n public static final String VARIANTS_DIRNAME = \"variants\";\n\n private final String vendor;\n private final String architecture;\n private final Path rootPath;\n\n private final Map<String, String> boardNamesToIdsLookup = new HashMap<>();\n\n public Platform(Platform parent, String vendor, String architecture, Path rootPath) throws IOException {\n super(parent);\n this.vendor = vendor;\n this.architecture = architecture;\n this.rootPath = rootPath;\n this.data = parseDataFile(PLATFORM_FILENAME);\n }\n\n public Platform getParent() {\n return (Platform) parent;\n }\n\n public String getArchitecture() {\n return architecture;\n }\n\n public String getVendor() {\n return vendor;\n }\n\n public boolean isPIC32() {\n return (architecture != null) ? architecture.toLowerCase().equals(\"pic32\") : false;\n }\n\n public boolean isAVR() {\n return (architecture != null) ? architecture.toLowerCase().equals(\"avr\") : false;\n }\n\n public boolean isSAMD() {\n return (architecture != null) ? architecture.toLowerCase().equals(\"samd\") : false;\n }\n\n public Optional<String> getDisplayName() {\n return getValue(\"name\");\n }\n\n public Path getRootPath() {\n return rootPath;\n }\n\n public Path getBoardsFilePath() {\n return rootPath.resolve(BOARDS_FILENAME);\n }\n\n public Path getPlatformFilePath() {\n return rootPath.resolve(PLATFORM_FILENAME);\n }\n\n public Map<String, String> getBoardNamesToIDsLookup() {\n if (boardNamesToIdsLookup.isEmpty()) {\n try (Stream<String> lines = Files.lines(rootPath.resolve(BOARDS_FILENAME))) {\n return lines\n .map(line -> line.trim())\n .filter(line -> !line.isEmpty() && !line.startsWith(\"#\") && !line.startsWith(\"menu.\"))\n .map(line -> {\n int splitIndex = line.indexOf(\"=\");\n String key = line.substring(0, splitIndex).trim();\n String value = line.substring(splitIndex + 1);\n String[] keyParts = key.split(\"\\\\.\");\n if (key.endsWith(\".name\") && keyParts.length == 2) {\n return new String[]{value.trim(),keyParts[0]};\n } else {\n return null;\n }\n })\n .filter(Objects::nonNull)\n .collect(Collectors.toMap(\n tokens -> tokens[0],\n tokens -> tokens.length > 1 ? tokens[1] : \"\",\n (val1, val2) -> val2\n ));\n } catch (IOException ex) {\n Exceptions.printStackTrace(ex);\n return Collections.EMPTY_MAP;\n }\n } else {\n return Collections.unmodifiableMap(boardNamesToIdsLookup);\n }\n }\n\n public Set<String> getBoardIDs() {\n return getBoardNamesToIDsLookup().keySet();\n }\n\n public Optional<Board> getBoard(String boardId) {\n Set<BoardOption> allAvailableOptions = new HashSet<>();\n Map<String, String> boardData = new HashMap<>();\n\n try (Stream<String> lines = Files.lines(rootPath.resolve(BOARDS_FILENAME))) {\n lines\n .map(line -> line.trim())\n .filter(line -> !line.isEmpty() && !line.startsWith(\"#\"))\n .forEach(line -> {\n String[] keyValue = line.split(\"=\");\n String key = keyValue[0];\n String value = keyValue.length > 1 ? keyValue[1] : \"\";\n if (key.startsWith(\"menu.\")) {\n allAvailableOptions.add(new BoardOption(key, value));\n } else if (key.startsWith(boardId)) {\n int firstDotIndex = key.indexOf(\".\");\n String boardValueId = key.substring(firstDotIndex + 1);\n boardData.put(boardValueId, value);\n }\n });\n } catch (IOException ex) {\n Exceptions.printStackTrace(ex);\n return Optional.empty();\n }\n\n Map<BoardOption,Set<String>> boardOptions = new HashMap<>();\n boardData.keySet().forEach(key -> {\n allAvailableOptions.forEach((BoardOption opt) -> {\n if (key.contains(opt.getId())) {\n Set<String> optionValues = boardOptions.computeIfAbsent(opt, k -> new HashSet<>());\n String shortKey = key.substring(opt.getId().length()+1);\n String[] shortKeyParts = shortKey.split(\"\\\\.\");\n if ( shortKeyParts.length == 1 ) {\n String optionValue = shortKey;\n optionValues.add(optionValue);\n }\n }\n });\n });\n\n return Optional.of(new Board(this, boardId, boardData, boardOptions));\n }\n\n @Override\n public String toString() {\n return \"Platform{ vendor=\" + vendor + \", architecture=\" + architecture + \", rootPath=\" + rootPath + '}';\n }\n\n @Override\n public int hashCode() {\n int hash = 3;\n hash = 37 * hash + Objects.hashCode(this.vendor);\n hash = 37 * hash + Objects.hashCode(this.architecture);\n hash = 37 * hash + Objects.hashCode(this.rootPath);\n return hash;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n if (obj == null) {\n return false;\n }\n if (getClass() != obj.getClass()) {\n return false;\n }\n final Platform other = (Platform) obj;\n if (!Objects.equals(this.vendor, other.vendor)) {\n return false;\n }\n if (!Objects.equals(this.architecture, other.architecture)) {\n return false;\n }\n if (!Objects.equals(this.rootPath, other.rootPath)) {\n return false;\n }\n return true;\n }\n\n // ***************************************\n // ********** PRIVATE METHODS ************\n // *************************************** \n private Map<String, String> parseDataFile(String filename) throws IOException {\n try (Stream<String> lines = Files.lines(rootPath.resolve(filename))) {\n return lines\n .map(line -> line.trim())\n .filter(line -> !line.isEmpty() && !line.startsWith(\"#\"))\n .map(line -> {\n int splitIndex = line.indexOf(\"=\");\n return new String[]{line.substring(0, splitIndex), line.substring(splitIndex + 1)};\n })\n .collect(Collectors.toMap(\n tokens -> tokens[0],\n tokens -> tokens.length > 1 ? tokens[1] : \"\",\n (val1, val2) -> val2\n ));\n }\n }\n\n}",
"public enum ImportWizardProperty {\n\n ARDUINO_DIR(\"arduinoDir\"),\n ARDUINO_PLATFORM(\"platform\"),\n ARDUINO_PLATFORM_DIR(\"platformCoreDir\"),\n BOARD_NAME(\"boardName\"),\n BOARD(\"board\"),\n BOARD_CONFIGURATION(\"boardConfiguration\"),\n LAST_SOURCE_PROJECT_LOCATION(\"lastSourceProjectLocation\"),\n LAST_ARDUINO_PLATFORM(\"lastPlatform\"),\n LAST_ARDUINO_PLATFORM_LOCATION(\"lastPlatformLocation\"),\n LAST_ARDUINO_LOCATION(\"lastArduinoLocation\"),\n COPY_CORE_FILES(\"copyCoreFiles\");\n\n private final String key;\n\n private ImportWizardProperty(String key) {\n this.key = key;\n }\n\n public String key() {\n return key;\n }\n}",
"public final class Board extends ArduinoDataSource {\n\n\n public static final PathMatcher SOURCE_FILE_MATCHER = FileSystems.getDefault().getPathMatcher(\"glob:*.{c,cpp,S}\"); \n public static final String VARIANTS_DIRNAME = \"variants\";\n \n private static final Logger LOGGER = Logger.getLogger(Board.class.getName());\n \n private final String boardId;\n private final Map <BoardOption,Set<String>> options;\n \n public Board(Platform platform, String boardId, Map<String,String> data, Map<BoardOption,Set<String>> options) {\n super(platform, data);\n this.boardId = boardId;\n this.options = options;\n putValue(\"build.arch\", platform.getArchitecture().toUpperCase());\n String ldScript = data.get(\"ldscript\");\n if ( ldScript != null ) {\n String ldScriptDebug = ldScript.substring( 0, ldScript.lastIndexOf(\".\") ) + \"-debug.ld\";\n putValue(\"ldscript-debug\", ldScriptDebug);\n }\n }\n\n @Override\n public String toString() { \n return \"Board {boardId=\" + boardId + \", options=\" + options.keySet() + '}';\n }\n \n @Override\n public int hashCode() {\n int hash = 5;\n hash = 43 * hash + Objects.hashCode(this.boardId);\n return hash;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n if (obj == null) {\n return false;\n }\n if (getClass() != obj.getClass()) {\n return false;\n }\n final Board other = (Board) obj;\n return Objects.equals(this.boardId, other.boardId);\n }\n\n public Platform getPlatform() {\n return (Platform) parent;\n }\n \n public String getBoardId() {\n return boardId;\n }\n \n public String getArchitecture() {\n return getPlatform().getArchitecture();\n }\n \n public boolean isPIC32() {\n return getPlatform().isPIC32();\n }\n \n public boolean isAVR() {\n return getPlatform().isAVR();\n }\n \n public boolean isSAMD() {\n return getPlatform().isSAMD();\n }\n \n @Override\n public Optional<String> getValue( String dataKey, ArduinoDataSource context, Map <String,String> auxData ) {\n String value = auxData != null ? auxData.get(dataKey) : null;\n if ( value == null ) value = data.get( dataKey );\n if ( value != null ) {\n value = resolveTokens(value, context, auxData);\n return Optional.of(value);\n } else {\n return parent.getValue(dataKey, context, auxData).map( v -> resolveTokens(v, context, auxData) );\n }\n }\n \n public List <Path> getCoreDirPaths() {\n List <Path> ret = new ArrayList<>();\n getValue(\"build.core.path\").ifPresent( val -> ret.add( Paths.get( val ) ) );\n getValue(\"build.variant.path\").ifPresent( val -> ret.add( Paths.get( val ) ) );\n return ret;\n }\n \n public Path getCoreDirectoryPath() {\n Optional<String> coreOpt = getValue(\"build.core\");\n if ( coreOpt.isPresent() ) {\n String coreValue = coreOpt.get();\n Path coresDirPath;\n // TODO: Improve core parsing\n if ( coreValue.equals(\"arduino:arduino\") ) {\n coresDirPath = ArduinoConfig.getInstance().getDefaultArduinoPlatformPath().get().resolve(\"cores\").resolve(\"arduino\");\n } else {\n coresDirPath = getPlatform().getRootPath().resolve(\"cores\").resolve(coreValue);\n } \n if ( Files.exists(coresDirPath) ) {\n return coresDirPath;\n } else {\n LOGGER.log(Level.SEVERE, \"Failed to find any core directory under: {0}\", coresDirPath);\n return null;\n }\n } else {\n LOGGER.log(Level.SEVERE, \"Failed to find Arduino core directory for: {0}\", boardId);\n } \n return null;\n }\n\n public Collection<BoardOption> getOptions() {\n return options.keySet();\n }\n \n public Map<String,String> getAvailableOptionValuesAndLabels( BoardOption option ) {\n Map <String,String> ret = new HashMap<>(); \n options.get(option).forEach( value -> { \n String dataKey = option.getId() + \".\" + value;\n getValue(dataKey).ifPresent( label -> {\n ret.put( value, label );\n });\n });\n return ret;\n }\n \n public boolean hasOptions() {\n return !options.isEmpty();\n }\n \n}",
"public final class BoardConfiguration extends ArduinoDataSource {\n\n private static final Logger LOGGER = Logger.getLogger(BoardConfiguration.class.getName());\n\n private static final String VARIANTS_DIRNAME = \"variants\";\n \n private static final String KEY_FQBN = \"fqbn\";\n private static final String KEY_BUILD_EXTRA_FLAGS = \"build.extra_flags\";\n\n private final Board board;\n private final Map<BoardOption, String> boardOptionsToValuesLookup;\n private final Map<String, String> boardOptionIdsToValuesLookup;\n\n public BoardConfiguration(Board board) {\n this(board, Collections.EMPTY_MAP);\n }\n\n public BoardConfiguration(Board board, Map<BoardOption, String> boardOptionsToValuesLookup) {\n super(board); \n assert board != null;\n this.board = board;\n this.boardOptionsToValuesLookup = boardOptionsToValuesLookup;\n this.boardOptionIdsToValuesLookup = boardOptionsToValuesLookup.entrySet()\n .stream()\n .collect(\n Collectors.toMap(\n e -> e.getKey().getId(),\n e -> e.getValue()\n )\n );\n putValue( KEY_FQBN, createFQBN() );\n putValue( KEY_BUILD_EXTRA_FLAGS, getValue(KEY_BUILD_EXTRA_FLAGS).map( flags -> flags + \" -D__CTYPE_NEWLIB -mnewlib-libc\").orElse(\"\") );\n }\n\n public String getFqbn() {\n return getValue(KEY_FQBN).get(); // Risky, but we know we've put it there in the constructor\n }\n\n @Override\n public String toString() {\n return \"BoardConfiguration {boardId=\" + board.getBoardId() + \"}\";\n }\n\n public Board getBoard() {\n return board;\n }\n\n public String getBoardId() {\n return board.getBoardId();\n }\n\n public Platform getPlatform() {\n return board.getPlatform();\n }\n\n public Optional<String> getDeviceLinkerScriptFilename() {\n return getValue(\"ldscript\");\n }\n\n public Optional<String> getDeviceDebugLinkerScriptFilename() {\n return getValue(\"ldscript-debug\");\n }\n\n public Optional<String> getCommonLinkerScriptFilename() {\n return getValue(\"ldcommon\");\n }\n\n public boolean hasOption(String optionId) {\n return boardOptionIdsToValuesLookup.containsKey(optionId);\n }\n\n public Optional<String> getOptionValue(String optionId) {\n return Optional.ofNullable(boardOptionIdsToValuesLookup.get(optionId));\n }\n \n public Optional<String> getOptionValueLabel(String optionId) {\n return getOptionValue(optionId).flatMap( optionValue -> {\n String dataKey = optionId + \".\" + optionValue;\n return board.getValue(dataKey);\n });\n }\n\n @Override\n public Optional<String> getValue(String key, ArduinoDataSource context, Map<String, String> runtimeData) {\n String boardConfigData = data.get(key);\n if (boardConfigData != null) {\n return Optional.of(boardConfigData);\n } else {\n return Optional.ofNullable(boardOptionsToValuesLookup.entrySet().stream().map(e -> {\n String optionId = e.getKey().getId();\n String optionValue = e.getValue();\n String dataKey = optionId + \".\" + optionValue + \".\" + key;\n return board.getValue(dataKey, this, runtimeData).orElse(null);\n })\n .filter(Objects::nonNull)\n .findAny()\n // Fallback to board:\n .orElse(board.getValue(key, this, runtimeData).orElse(null)));\n }\n }\n\n public List<Path> getCoreDirPaths() {\n List<Path> ret = new ArrayList<>();\n getValue(\"build.core.path\").ifPresent(val -> ret.add(Paths.get(val)));\n getValue(\"build.variant.path\").ifPresent(val -> ret.add(Paths.get(val)));\n return ret;\n }\n\n public Path getCoreDirectoryPath() {\n return board.getCoreDirectoryPath();\n }\n\n public Path getVariantPath() {\n try {\n Optional<String> opt = getValue(\"build.variant\");\n Path variantsDirPath = getPlatform().getRootPath().resolve(VARIANTS_DIRNAME);\n if (opt.isPresent()) {\n Path variantPath = variantsDirPath.resolve(opt.get());\n // If the path does not exist, it might just be because of the letter casing in the variant name \n // so go through all directories and compare their lower-case names with lower-case variant name:\n if (!Files.exists(variantPath)) {\n String lowerCaseDirName = variantPath.getFileName().toString().toLowerCase();\n Optional<Path> findAny = Files.list(variantsDirPath).filter(p -> p.getFileName().toString().toLowerCase().equals(lowerCaseDirName)).findAny();\n if (findAny.isPresent()) {\n variantPath = findAny.get();\n } else {\n throw new IllegalArgumentException(\"Did not find any variant directory for board \\\"\" + board.getBoardId() + \"\\\"\");\n }\n }\n return variantPath;\n } else {\n throw new IllegalArgumentException(\"Did not find any variant directory for board \\\"\" + board.getBoardId() + \"\\\"\");\n }\n } catch (IOException ex) {\n throw new RuntimeException(ex);\n }\n }\n\n public List<Path> getCoreFilePaths() throws IOException {\n Path variantPath = getVariantPath();\n Path corePath = getCoreDirectoryPath();\n\n // Find source files in variant directory:\n List<Path> variantFilePaths = new ArrayList<>();\n if (variantPath != null) {\n variantFilePaths = Files.list(variantPath)\n .filter(filePath -> SOURCE_FILE_MATCHER.matches(filePath.getFileName()))\n .collect(Collectors.toList());\n }\n\n // Create a list of source file names from the variant directory that will be used to filter core source files:\n List<String> variantFileNames = variantFilePaths.stream().map(p -> p.getFileName().toString()).collect(Collectors.toList());\n\n // Find source files in core directory but only those that have not been overriden in the variant directory:\n List<Path> coreFilePaths = Files.list(corePath)\n .filter(p -> SOURCE_FILE_MATCHER.matches(p.getFileName()))\n .filter(p -> !variantFileNames.contains(p.getFileName().toString()))\n .collect(Collectors.toList());\n\n // Add variant and core source file paths:\n List<Path> allCoreFilePaths = new ArrayList<>();\n allCoreFilePaths.addAll(variantFilePaths);\n allCoreFilePaths.addAll(coreFilePaths);\n\n return allCoreFilePaths;\n }\n\n //***************************************\n //********** PRIVATE METHODS ************\n //*************************************** \n private String createFQBN() {\n // E.g: arduino:avr:pro:cpu=8MHzatmega328\n String base = getPlatform().getVendor() + \":\" + getPlatform().getArchitecture() + \":\" + board.getBoardId();\n return getOptionValue(BoardOption.OPTION_CPU).map( cpuValue -> {\n String cpuPart = (cpuValue != null ? \":cpu=\" + cpuValue : \"\");\n return base + cpuPart;\n }).orElse( base );\n }\n\n}",
"public final class PlatformFactory {\n\n public static final String BOARDS_FILENAME = \"boards.txt\";\n public static final String PLATFORM_FILENAME = \"platform.txt\";\n\n private static final Logger LOGGER = Logger.getLogger(PlatformFactory.class.getName());\n\n private final List<Platform> allPlatforms = new ArrayList<>();\n\n public List<Platform> getAllPlatforms(Path arduinoSettingsPath) throws IOException {\n if (allPlatforms.isEmpty()) {\n\n Path settingsPath = validateArduinoSettingsPath(arduinoSettingsPath);\n\n // Find all paths containing a \"platform.txt\" file\n LOGGER.log(Level.INFO, \"Searching for platform files in {0}\", settingsPath);\n FileFinder finder = new FileFinder(PLATFORM_FILENAME);\n Files.walkFileTree(settingsPath, finder);\n List<Path> platformPaths = finder.getMatchingPaths();\n\n Platform rootPlatform = createRootPlatform();\n if ( rootPlatform == null ) {\n throw new RuntimeException(\"Failed to load the root platform!\");\n }\n\n platformPaths.stream().map(path -> createPlatformFromFile(rootPlatform, path)).forEach(allPlatforms::add);\n \n // Add the root platform but only if there is no platform in the user directory with the same vendor/arch:\n if ( !allPlatforms.stream().anyMatch( \n platform -> ROOT_PLATFORM_VENDOR.equalsIgnoreCase(platform.getVendor()) && ROOT_PLATFORM_ARCH.equalsIgnoreCase(platform.getArchitecture())\n )) {\n allPlatforms.add( rootPlatform );\n }\n }\n\n return Collections.unmodifiableList(allPlatforms);\n }\n\n // TODO: Optimize single platform creation so that it is not necessary to create all platforms\n public Platform createPlatform(Path arduinoSettingsPath, String vendor, String architecture) throws IOException {\n if (allPlatforms.isEmpty()) {\n getAllPlatforms(arduinoSettingsPath);\n }\n for (Platform platform : allPlatforms) {\n if (vendor.equalsIgnoreCase(platform.getVendor()) && architecture.equalsIgnoreCase(platform.getArchitecture())) {\n return platform;\n }\n }\n return null;\n }\n\n public Platform createPlatformFromRootDirectory(Path platformRootPath) throws IOException {\n Path platformFilePath = platformRootPath.resolve(PLATFORM_FILENAME);\n Platform rootPlatform = createRootPlatform();\n return createPlatformFromFile(rootPlatform, platformFilePath);\n }\n\n public boolean isValidPlatformRootPath(Path rootPath) {\n return rootPath != null && Files.exists(rootPath.resolve(PLATFORM_FILENAME));\n }\n\n private static Platform createPlatformFromFile(Platform rootPlatform, Path platformFilePath) {\n // Pattern: /home/user/.arduino15/packages/{vendor}/hardware/{architecture}/x.x.x/platform.txt\n int hardwareIndex = -1;\n for (int i = platformFilePath.getNameCount() - 1; i >= 0; i--) {\n if (\"hardware\".equalsIgnoreCase(platformFilePath.getName(i).toString())) {\n hardwareIndex = i;\n break;\n }\n }\n String vendor = platformFilePath.getName(hardwareIndex - 1).toString();\n String architecture = platformFilePath.getName(hardwareIndex + 1).toString();\n\n try {\n// if (architecture.equalsIgnoreCase(\"pic32\")) {\n return new PIC32Platform(rootPlatform, vendor, platformFilePath.getParent());\n// } else {\n// return new Platform(rootPlatform, vendor, architecture, platformFilePath.getParent());\n// }\n } catch (IOException ex) {\n LOGGER.log(Level.SEVERE, String.format(\"Failed to create a platform for %s / %s \", vendor, architecture), ex);\n return null;\n }\n\n }\n\n private static Platform createRootPlatform() throws IOException {\n Path arduinoPlatformPath = ArduinoConfig.getInstance().getDefaultArduinoPlatformPath().get();\n return new Platform(null, ROOT_PLATFORM_VENDOR, ROOT_PLATFORM_ARCH, arduinoPlatformPath);\n }\n\n private static Path validateArduinoSettingsPath(Path settingsPath) throws FileNotFoundException {\n if (!Files.exists(settingsPath)) {\n LOGGER.severe(\"Failed to find the Arduino settings directory!\");\n throw new FileNotFoundException(\"Failed to find the Arduino settings directory!\");\n }\n return settingsPath;\n }\n\n}",
"public class ArduinoProjectFileFilter extends FileFilter {\n\n @Override\n public boolean accept(File f) {\n return f.isDirectory() || f.getName().toLowerCase().endsWith(\".ino\");\n }\n\n @Override\n public String getDescription() {\n // TODO: Move file type name to Bundle\n return \"Arduino Project Files\";\n }\n\n}"
] | import com.microchip.crownking.opt.Version;
import com.microchip.mplab.mdbcore.MessageMediator.ActionList;
import com.microchip.mplab.mdbcore.MessageMediator.DialogBoxType;
import com.microchip.mplab.mdbcore.MessageMediator.Message;
import com.microchip.mplab.mdbcore.MessageMediator.MessageMediator;
import com.microchip.mplab.nbide.embedded.api.ui.TypeAheadComboBox;
import com.microchip.mplab.nbide.embedded.arduino.importer.ArduinoConfig;
import com.microchip.mplab.nbide.embedded.arduino.importer.Platform;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import javax.swing.JFileChooser;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.netbeans.api.project.Project;
import org.netbeans.api.project.ProjectManager;
import org.netbeans.spi.project.ui.support.ProjectChooser;
import org.openide.WizardDescriptor;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.util.HelpCtx;
import org.openide.util.Lookup;
import org.openide.util.NbBundle;
import org.openide.util.NbPreferences;
import com.microchip.mplab.nbide.embedded.makeproject.ui.wizards.SelectProjectInfoPanel;
import javax.swing.JTextField;
import static com.microchip.mplab.nbide.embedded.makeproject.api.wizards.WizardProperty.*;
import static com.microchip.mplab.nbide.embedded.arduino.wizard.ImportWizardProperty.*;
import static com.microchip.mplab.nbide.embedded.arduino.importer.Requirements.MINIMUM_ARDUINO_VERSION;
import com.microchip.mplab.nbide.embedded.arduino.importer.Board;
import com.microchip.mplab.nbide.embedded.arduino.importer.BoardConfiguration;
import com.microchip.mplab.nbide.embedded.arduino.importer.PlatformFactory;
import com.microchip.mplab.nbide.embedded.arduino.utils.ArduinoProjectFileFilter;
import java.awt.event.FocusEvent;
import java.awt.event.ItemEvent;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.filechooser.FileFilter;
import org.openide.util.Exceptions; |
// Set the error message to null if there is no warning message to display
if (wizardDescriptor.getProperty(WizardDescriptor.PROP_WARNING_MESSAGE) == null) {
wizardDescriptor.putProperty(WizardDescriptor.PROP_ERROR_MESSAGE, null);
}
return true;
}
@Override
public final void addChangeListener(ChangeListener l) {
synchronized (listeners) {
listeners.add(l);
}
}
@Override
public final void removeChangeListener(ChangeListener l) {
synchronized (listeners) {
listeners.remove(l);// NOI18N
}
}
@Override
public void readSettings(WizardDescriptor settings) {
wizardDescriptor = settings;
// Source Project Location
File lastSourceProjectLocation = (File) wizardDescriptor.getProperty(SOURCE_PROJECT_DIR.key());
if (lastSourceProjectLocation == null) {
String loc = NbPreferences.forModule(SelectProjectInfoPanel.class).get(LAST_SOURCE_PROJECT_LOCATION.key(), null);
if (loc == null) {
loc = System.getProperty("user.home");
}
lastSourceProjectLocation = new File(loc);
}
view.sourceProjectLocationField.setText(lastSourceProjectLocation.getAbsolutePath());
// Target Project Location
File lastTargetProjectLocation = (File) wizardDescriptor.getProperty(PROJECT_LOCATION.key());
if (lastTargetProjectLocation == null) {
String loc = NbPreferences.forModule(SelectProjectInfoPanel.class).get(LAST_PROJECT_LOCATION.key(), null);
if (loc == null) {
loc = System.getProperty("netbeans.projects.dir");
}
if (loc == null) {
loc = System.getProperty("user.home");
}
lastTargetProjectLocation = new File(loc);
}
view.targetProjectLocationField.setText(lastTargetProjectLocation.getAbsolutePath());
// Platform Location
File platformCoreDir = (File) wizardDescriptor.getProperty(ARDUINO_PLATFORM_DIR.key());
if (platformCoreDir == null) {
String lastPlatformCoreLocation = NbPreferences.forModule(SelectProjectInfoPanel.class).get(LAST_ARDUINO_PLATFORM_LOCATION.key(), null);
if ( lastPlatformCoreLocation != null && Files.exists( Paths.get(lastPlatformCoreLocation) ) ) {
platformCoreDir = new File(lastPlatformCoreLocation);
}
}
if (platformCoreDir != null) {
view.platformLocationField.setText( platformCoreDir.getAbsolutePath() );
resolvePlatformFromPath();
}
// Platform
if (currentPlatform == null) {
try {
List<Platform> allPlatforms = new PlatformFactory().getAllPlatforms( arduinoConfig.getSettingsPath() );
currentPlatform = allPlatforms.stream().filter(p -> p.getVendor().contains("chipKIT") ).findFirst().orElse(null);
if ( currentPlatform != null ) {
view.platformLocationField.setText( currentPlatform.getRootPath().toString() );
}
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
}
}
// Target Device:
String boardName = (String) wizardDescriptor.getProperty(BOARD_NAME.key());
loadBoardsToCombo();
if (boardName == null) {
boardName = NbPreferences.forModule(SelectProjectInfoPanel.class).get(BOARD_NAME.key(), null);
}
if (boardName != null) {
if ( boardIdLookup.containsKey(boardName) ) {
view.boardCombo.setSelectedItem(boardName);
updateBoard();
} else {
boardName = null;
}
}
// Copy all dependencies:
Object copyDependencies = wizardDescriptor.getProperty(COPY_CORE_FILES.key());
view.copyDependenciesCheckBox.setSelected( copyDependencies != null ? (boolean) copyDependencies : true);
// Target Project Directory:
setTargetProjectDirectoryField();
}
@Override
public void storeSettings(WizardDescriptor settings) {
String projectName = readLocationStringFromField( view.projectNameField );
String sourceProjectDir = readLocationStringFromField( view.sourceProjectLocationField );
String platformDir = readLocationStringFromField(view.platformLocationField );
String boardName = readSelectedValueFromComboBox(view.boardCombo);
String targetLocation = readLocationStringFromField( view.targetProjectLocationField );
String targetDir = readLocationStringFromField( view.projectDirectoryField );
boolean copyCoreFiles = view.copyDependenciesCheckBox.isSelected();
settings.putProperty(SOURCE_PROJECT_DIR.key(), new File(sourceProjectDir));
settings.putProperty(ARDUINO_DIR.key(), arduinoConfig.findInstallPath().get().toFile() );
settings.putProperty(ARDUINO_PLATFORM.key(), currentPlatform );
settings.putProperty(ARDUINO_PLATFORM_DIR.key(), new File(platformDir));
settings.putProperty(BOARD_NAME.key(), boardName);
settings.putProperty(BOARD.key(), board);
if ( !board.hasOptions() ) {
deviceAssistant.storeSettings(settings); | settings.putProperty(BOARD_CONFIGURATION.key(), new BoardConfiguration(board)); | 4 |
richkmeli/Richkware-Manager-Server | src/main/java/it/richkmeli/rms/data/LoadDatabase.java | [
"@Component\npublic class ConfigurationDatabaseManager {\n private static ConfigurationRepository configurationRepository;\n\n @Autowired\n public ConfigurationDatabaseManager(ConfigurationRepository configurationRepository) {\n this.configurationRepository = configurationRepository;\n }\n\n public static ConfigurationDatabaseManager getInstance() {\n return new ConfigurationDatabaseManager(configurationRepository);\n }\n\n public String getValue(String key) {\n return configurationRepository.findById(key).map(Configuration::getValue).orElse(null);\n }\n\n public Configuration saveValue(String key, String value) {\n Configuration configuration = new Configuration(key,value);\n return saveValue(configuration);\n }\n\n public Configuration saveValue(Configuration configuration) {\n return configurationRepository.save(configuration);\n }\n\n public List<Configuration> getAllConfigurations() {\n return configurationRepository.findAll();\n }\n\n\n}",
"public enum ConfigurationEnum {\n MAPBOX_ACCESS_TOKEN(\"REPLACE_WITH_API_TOKEN\"),\n DEFAULT_CONFIGURATION_2(\"dafault_value_2\"),\n DEFAULT_CONFIGURATION_3(\"dafault_value_3\");\n\n\n private String key;\n private String defaultValue;\n\n ConfigurationEnum(String defaultValue) {\n this.key = this.name();\n this.defaultValue = defaultValue;\n }\n\n ConfigurationEnum(String key, String defaultValue) {\n this.key = key;\n this.defaultValue = defaultValue;\n }\n\n public String getKey() {\n return key;\n }\n\n public String getDefaultValue() {\n return defaultValue;\n }\n\n}",
"public class ConfigurationManager {\n private static final int REFRESH_CONFIGURATIONS_TIMEOUT = 60;\n private static List<Configuration> configurations;\n private static Date timeWhenUpdate;\n\n private static void init() {\n if (configurations == null) {\n // load configuration in RAM from DB\n ConfigurationDatabaseManager configurationDatabaseManager = ConfigurationDatabaseManager.getInstance();\n configurations = configurationDatabaseManager.getAllConfigurations();\n timeWhenUpdate = getTimeWhenUpdate();\n\n if (configurations == null || configurations.size() < ConfigurationEnum.values().length) {\n Logger.info(\"DB is empty or is missing some entries, load default values to DB\");\n for (ConfigurationEnum configurationEnum : ConfigurationEnum.values()) {\n // check if the DB contains a specific entry\n if (configurations.contains(configurationEnum.getKey())) {\n Configuration dbConfiguration = configurations.get(configurations.indexOf(configurationEnum.getKey()));\n // check differences about the entry value\n if (dbConfiguration.getValue().equalsIgnoreCase(configurationEnum.getDefaultValue())) {\n // same value, OK\n } else {\n // different value, keep value of DB to avoid restore to default setting\n }\n } else {\n // DB doesn't contain the entry, same default value to DB\n Configuration defaultConfiguration = new Configuration(configurationEnum.getKey(), configurationEnum.getDefaultValue());\n configurationDatabaseManager.saveValue(defaultConfiguration);\n }\n }\n // upload default values also in RAM\n configurations = configurationDatabaseManager.getAllConfigurations();\n } else if (configurations.size() > ConfigurationEnum.values().length) {\n // not possible get a key present in DB and not present in ConfigurationEnum. (init is call when DB return null)\n Logger.error(\"DB contains more keys than application need, the entries present only in the DB have to be deleted or inserted in the application\");\n } else {\n // not possible get a key present in DB and not present in ConfigurationEnum. (init is call when DB return null)\n Logger.info(\"DB and ConfigurationEnum have the same size\");\n }\n } else {\n // configuration contains already configurations\n if (getCurrentTime().compareTo(timeWhenUpdate) > 0) {\n // refresh RAM with DB\n configurations = null;\n init();\n } else {\n // timeout not elapsed\n }\n }\n }\n\n private static Date getCurrentTime() {\n return Date.from(Clock.systemUTC().instant());\n }\n\n private static Date getTimeWhenUpdate() {\n return Date.from(Clock.systemUTC().instant().plusSeconds(REFRESH_CONFIGURATIONS_TIMEOUT));\n }\n\n public static String getValueWithCacheSystem(ConfigurationEnum configurationEnum) {\n init();\n for (Configuration s : configurations) {\n if (configurationEnum.getKey().equalsIgnoreCase(s.getKey())) {\n return s.getValue();\n }\n }\n return null;\n }\n\n public static String getValue(ConfigurationEnum configurationEnum) {\n String value = ConfigurationDatabaseManager.getInstance().getValue(configurationEnum.getKey());\n if (value == null) {\n // initialization of the database\n init();\n value = getValue(configurationEnum);\n }\n return value;\n }\n\n\n}",
"@Component\npublic class DeviceDatabaseSpringManager implements DeviceDatabaseModel {\n private static DeviceRepository deviceRepository;\n private static LocationRepository locationRepository;\n private static DeviceInfoRepository deviceInfoRepository;\n\n @Autowired\n public DeviceDatabaseSpringManager(DeviceRepository deviceRepository, LocationRepository locationRepository, DeviceInfoRepository deviceInfoRepository) {\n this.deviceRepository = deviceRepository;\n this.locationRepository = locationRepository;\n this.deviceInfoRepository = deviceInfoRepository;\n }\n\n public static DeviceDatabaseSpringManager getInstance() {\n return new DeviceDatabaseSpringManager(deviceRepository, locationRepository, deviceInfoRepository);\n }\n\n @Override\n public List<Device> getAllDevices() throws AuthDatabaseException {\n return deviceRepository.findAll();\n }\n\n @Override\n public List<Device> getUserDevices(String user) throws AuthDatabaseException {\n return deviceRepository.findDevicesByAssociatedUser_Email(user);\n }\n\n @Override\n public Device addDevice(Device device) throws AuthDatabaseException {\n return deviceRepository.save(device);\n }\n\n @Override\n public Device editDevice(Device device) throws AuthDatabaseException {\n\n return deviceRepository.save(device);\n }\n\n @Override\n public void removeDevice(String name) throws AuthDatabaseException {\n Device device = deviceRepository.findDeviceByName(name);\n if(device != null) {\n deviceRepository.delete(device);\n }\n }\n\n @Override\n public Device getDevice(String name) throws AuthDatabaseException {\n return deviceRepository.findDeviceByName(name);\n }\n\n @Override\n public String getEncryptionKey(String name) throws AuthDatabaseException {\n Device device = deviceRepository.findDeviceByName(name);\n if (device != null) {\n return device.getEncryptionKey();\n } else {\n return null;\n }\n }\n\n @Override\n public boolean editCommands(String deviceName, String commands) throws AuthDatabaseException {\n Device device = deviceRepository.findDeviceByName(deviceName);\n if (device != null) {\n device.setCommands(commands);\n deviceRepository.save(device);\n return true;\n } else {\n return false;\n }\n }\n\n @Override\n public String getCommands(String deviceName) throws AuthDatabaseException {\n Device device = deviceRepository.findDeviceByName(deviceName);\n if (device != null) {\n return device.getCommands();\n } else {\n return \"\";\n }\n }\n\n @Override\n public boolean setCommandsOutput(String deviceName, String commandsOutput) throws AuthDatabaseException {\n Device device = deviceRepository.findDeviceByName(deviceName);\n if (device != null) {\n device.setCommandsOutput(commandsOutput);\n deviceRepository.save(device);\n return true;\n } else {\n return false;\n }\n }\n\n @Override\n public String getCommandsOutput(String deviceName) throws AuthDatabaseException {\n Device device = deviceRepository.findDeviceByName(deviceName);\n if (device != null) {\n return device.getCommandsOutput();\n } else {\n return \"\";\n }\n }\n}",
"@Entity\npublic class Device {\n @Id\n @NotNull\n @Length(max = 64)\n private String name;\n @NotNull\n @Length(max = 25)\n private String ip;\n @Length(max = 10)\n private String serverPort;\n @Length(max = 25)\n private String lastConnection;\n @Length(max = 32)\n private String encryptionKey;\n @ManyToOne(fetch = FetchType.LAZY)\n @JsonBackReference\n @JoinColumn(name=\"user_email\")\n private User associatedUser;\n @Length(max = 1000)\n private String commands;\n @Length(max = 1000)\n private String commandsOutput;\n @Length(max = 64)\n private String installationId;\n @OneToOne(mappedBy = \"device\", fetch = FetchType.LAZY, cascade = {CascadeType.ALL}/*, orphanRemoval = true*/)\n @PrimaryKeyJoinColumn\n @JsonBackReference\n private Location location;\n @OneToOne(mappedBy = \"device\", fetch = FetchType.LAZY, cascade = {CascadeType.ALL}/*, orphanRemoval = true*/)\n @PrimaryKeyJoinColumn\n @JsonBackReference\n private DeviceInfo deviceInfo;\n\n public Device() {\n }\n\n public Device(String name, String ip, String serverPort, String lastConnection, String encryptionKey, User associatedUser, String commands, String commandsOutput, String installationId, Location location, DeviceInfo deviceInfo) {\n this.name = name;\n this.ip = ip;\n this.serverPort = serverPort;\n this.lastConnection = lastConnection;\n this.encryptionKey = encryptionKey;\n this.associatedUser = associatedUser;\n this.commands = commands;\n this.commandsOutput = commandsOutput;\n this.installationId = installationId;\n this.location = location;\n if (this.location != null) {\n this.location.setId(name);\n this.location.setDevice(this);\n }\n this.deviceInfo = deviceInfo;\n if (this.deviceInfo != null) {\n this.deviceInfo.setId(name);\n this.deviceInfo.setDevice(this);\n }\n }\n\n public String getInstallationId() {\n return installationId;\n }\n\n public void setInstallationId(String installationId) {\n this.installationId = installationId;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getIp() {\n return ip;\n }\n\n public void setIp(String ip) {\n this.ip = ip;\n }\n\n public String getServerPort() {\n return serverPort;\n }\n\n public void setServerPort(String serverPort) {\n this.serverPort = serverPort;\n }\n\n public String getLastConnection() {\n return lastConnection;\n }\n\n public void setLastConnection(String lastConnection) {\n this.lastConnection = lastConnection;\n }\n\n public String getEncryptionKey() {\n return encryptionKey;\n }\n\n public void setEncryptionKey(String encryptionKey) {\n this.encryptionKey = encryptionKey;\n }\n\n public User getAssociatedUser() {\n return associatedUser;\n }\n\n public void setAssociatedUser(User associatedUser) {\n this.associatedUser = associatedUser;\n }\n\n public String getCommands() {\n return commands;\n }\n\n public void setCommands(String commands) {\n this.commands = commands;\n }\n\n public String getCommandsOutput() {\n return commandsOutput;\n }\n\n public void setCommandsOutput(String commandsOutput) {\n this.commandsOutput = commandsOutput;\n }\n\n public Location getLocation() {\n return location;\n }\n\n public void setLocation(Location location) {\n this.location = location;\n }\n\n public DeviceInfo getDeviceInfo() {\n return deviceInfo;\n }\n\n public void setDeviceInfo(DeviceInfo deviceInfo) {\n this.deviceInfo = deviceInfo;\n }\n\n // called by the serialization, location is not serialized due to JsonBackReference\n public String getLocationAsPosition() {\n return GeoLocation.getPositionFromCoordinates(location.getLongitude(), location.getLatitude(), location.getAltitude());\n }\n\n // called by the serialization, location is not serialized due to JsonBackReference\n public String getAssociatedUserEmail() {\n return associatedUser.getEmail();\n }\n\n // called by the serialization, location is not serialized due to JsonBackReference\n public String getDeviceInfoDevName() {\n return deviceInfo.getDevName();\n }\n\n @Override\n public String toString() {\n String output = \"\";\n output = \"{\" + getName() + \", \"\n + getIp() + \", \"\n + getServerPort() + \", \"\n + getLastConnection() + \", \"\n + getEncryptionKey() + \", \"\n + getAssociatedUser() + \", \"\n + getCommands() + \", \"\n + getCommandsOutput() + \", \"\n + getInstallationId() + \", \"\n + getLocation() + \", \"\n + getDeviceInfo()\n + \"}\";\n\n return output;\n }\n}",
"@Component\npublic class RmcDatabaseSpringManager implements RmcDatabaseModel {\n private static RmcRepository rmcRepository;\n\n public static RmcDatabaseSpringManager getInstance() {\n return new RmcDatabaseSpringManager(rmcRepository);\n }\n\n @Autowired\n public RmcDatabaseSpringManager(RmcRepository rmcRepository){\n this.rmcRepository = rmcRepository;\n }\n\n @Override\n public Rmc addRMC(Rmc client) throws AuthDatabaseException {\n return rmcRepository.save(client);\n }\n\n @Override\n public Rmc editRMC(Rmc client) throws AuthDatabaseException {\n return rmcRepository.save(client);\n }\n\n @Override\n public void removeRMCs(String associatedUser) throws AuthDatabaseException {\n rmcRepository.deleteAllByAssociatedUser_Email(associatedUser);\n }\n\n @Override\n public void removeRMC(String rmcId) throws AuthDatabaseException {\n rmcRepository.deleteRmcByRmcId(rmcId);\n }\n\n @Override\n public void removeRmcUserPair(Rmc client) throws AuthDatabaseException {\n rmcRepository.deleteRmcByRmcIdAndAssociatedUser_Email(client.getRmcId(),client.getAssociatedUser().getEmail());\n }\n\n @Override\n public boolean checkRmcUserPair(Rmc client) throws AuthDatabaseException {\n return rmcRepository.existsRmcByRmcIdAndAssociatedUser_Email(client.getRmcId(),client.getAssociatedUser().getEmail());\n }\n\n @Override\n public boolean checkRmc(String rmcID) throws AuthDatabaseException {\n return rmcRepository.existsRmcByRmcId(rmcID);\n }\n\n @Override\n public List<Rmc> getRMCs(String associatedUser) throws AuthDatabaseException {\n return rmcRepository.findAllByAssociatedUser_Email(associatedUser);\n }\n\n @Override\n public List<Rmc> getAssociatedUsers(String rmcId) throws AuthDatabaseException {\n return rmcRepository.findAllByRmcId(rmcId);\n }\n\n @Override\n public List<Rmc> getAllRMCs() throws AuthDatabaseException {\n return rmcRepository.findAll();\n }\n\n @Override\n public List<Rmc> getUnassociatedRmcs(String rmcID) throws AuthDatabaseException {\n return rmcRepository.findAllByAssociatedUserIsNull();\n }\n}",
"@Entity\n@IdClass(RmcId.class)\npublic class Rmc {\n @Id\n @ManyToOne (fetch = FetchType.LAZY)\n private User associatedUser;\n @Id\n @Length(max = 68)\n private String rmcId;\n\n public Rmc() {\n }\n\n public Rmc(User associatedUser, String rmcId) {\n this.associatedUser = associatedUser;\n this.rmcId = rmcId;\n }\n\n public User getAssociatedUser() {\n return associatedUser;\n }\n\n public void setAssociatedUser(User associatedUser) {\n this.associatedUser = associatedUser;\n }\n\n public String getRmcId() {\n return rmcId;\n }\n\n public void setRmcId(String rmcId) {\n this.rmcId = rmcId;\n }\n}",
"@Component\npublic class AuthDatabaseSpringManager implements AuthDatabaseModel {\n private static UserRepository userRepository;\n\n @Autowired\n public AuthDatabaseSpringManager(UserRepository userRepository) throws AuthDatabaseException {\n this.userRepository = userRepository;\n }\n\n public static AuthDatabaseSpringManager getInstance() throws AuthDatabaseException {\n return new AuthDatabaseSpringManager(userRepository);\n }\n\n// public it.richkmeli.jframework.auth.model.User findUserByEmail(String email) throws AuthDatabaseException {\n// User user = userRepository.findUserByEmail(email);\n// try {\n// return new it.richkmeli.jframework.auth.model.User(user.getEmail(), user.getPassword(), user.getAdmin());\n// } catch (ModelException e) {\n// throw new AuthDatabaseException(e);\n// }\n// }\n\n public User findUserByEmail(String email) throws AuthDatabaseException {\n return userRepository.findUserByEmail(email);\n }\n\n @Override\n public List<it.richkmeli.jframework.auth.model.User> getAllUsers() throws AuthDatabaseException {\n List<User> users = userRepository.findAll();\n List<it.richkmeli.jframework.auth.model.User> users1 = new ArrayList<>();\n for (User u : users) {\n try {\n users1.add(new it.richkmeli.jframework.auth.model.User(u.getEmail(), u.getPassword(), u.getAdmin()));\n } catch (ModelException e) {\n throw new AuthDatabaseException(e);\n }\n }\n return users1;\n }\n\n @Override\n public boolean addUser(it.richkmeli.jframework.auth.model.User user) throws AuthDatabaseException {\n try {\n userRepository.save(new User(\n user.getEmail(),\n Crypto.hashPassword(user.getPassword(), false),\n user.getAdmin()));\n return true;\n } catch (ModelException e) {\n throw new AuthDatabaseException(e);\n }\n }\n\n public User addUser(User user) throws AuthDatabaseException {\n try {\n return userRepository.save(new User(\n user.getEmail(),\n Crypto.hashPassword(user.getPassword(), false),\n user.getAdmin()));\n } catch (ModelException e) {\n throw new AuthDatabaseException(e);\n }\n }\n\n @Override\n public boolean removeUser(String s) throws AuthDatabaseException, ModelException {\n User user = findUserByEmail(s);\n if(user != null) {\n userRepository.delete(user);\n return true;\n }\n return false;\n }\n\n @Override\n public boolean isUserPresent(String s) throws AuthDatabaseException, ModelException {\n return userRepository.existsUserByEmail(s);\n }\n\n @Override\n public boolean editPassword(String email, String password) throws AuthDatabaseException, ModelException {\n Optional<User> user = userRepository.findById(email);\n if (user.isPresent()) {\n User user1 = user.get();\n user1.setPassword(Crypto.hashPassword(password, false));\n userRepository.save(user1);\n return true;\n } else {\n return false;\n }\n }\n\n @Override\n public boolean editAdmin(String email, Boolean aBoolean) throws AuthDatabaseException, ModelException {\n Optional<User> user = userRepository.findById(email);\n if (user.isPresent()) {\n User user1 = user.get();\n user1.setAdmin(aBoolean);\n userRepository.save(user1);\n return true;\n } else {\n return false;\n }\n }\n\n @Override\n public boolean checkPassword(String email, String password) throws AuthDatabaseException, ModelException {\n User user = userRepository.findUserByEmail(email);\n if (user != null) {\n Crypto.verifyPassword(user.getPassword(), password);\n return true;\n } else {\n return false;\n }\n }\n\n @Override\n public boolean isAdmin(String email) throws AuthDatabaseException, ModelException {\n User user = userRepository.findUserByEmail(email);\n if (user != null) {\n return user.getAdmin();\n } else {\n return false;\n }\n }\n}",
"@Entity\npublic class User{\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n private Long id;\n @Column(unique = true)\n @NotNull\n @Length(max = 50)\n private String email;\n @NotNull\n @Length(max = 100)\n private String password;\n @NotNull\n private Boolean admin;\n\n @OneToMany(mappedBy = \"associatedUser\", cascade = {CascadeType.REMOVE}, fetch = FetchType.LAZY)\n // OR if you want in json object also the device list when it isn't load at that time\n //@OneToMany(mappedBy = \"associatedUser\", cascade={CascadeType.REMOVE}, fetch = FetchType.EAGER)\n @JsonManagedReference\n private Set<Device> devices;\n\n @OneToMany(mappedBy = \"associatedUser\", cascade = {CascadeType.REMOVE}, fetch = FetchType.LAZY)\n @JsonManagedReference\n private Set<Rmc> rmcs;\n\n public User() {\n }\n\n public User(String email, String password) throws ModelException {\n this(email, password, false);\n }\n\n public User(@Length(max = 50) String email, @NotNull @Length(max = 100) String password, @NotNull Boolean admin) throws ModelException {\n checkUserIntegrity(email, password, admin);\n this.email = email;\n this.password = password;\n this.admin = admin;\n }\n\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n public String getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n public Boolean getAdmin() {\n return admin;\n }\n\n public void setAdmin(Boolean admin) {\n this.admin = admin;\n }\n\n public Set<Device> getDevices() {\n return devices;\n }\n\n public void setDevices(Set<Device> devices) {\n this.devices = devices;\n }\n\n public Set<Rmc> getRmcs() {\n return rmcs;\n }\n\n public void setRmcs(Set<Rmc> rmcs) {\n this.rmcs = rmcs;\n }\n\n public static void checkUserIntegrity(String email, String password, Boolean admin) throws ModelException {\n try {\n RegexManager.checkEmailIntegrity(email);\n } catch (RegexException e) {\n throw new ModelException(\"Email is not valid\");\n }\n // ...\n }\n\n @Override\n public String toString() {\n String output = \"\";\n output = \"{\" + getEmail() + \", \"\n + getPassword() + \", \"\n + getAdmin()\n + \"}\";\n\n return output;\n }\n}"
] | import it.richkmeli.jframework.util.RandomStringGenerator;
import it.richkmeli.rms.data.entity.configuration.ConfigurationDatabaseManager;
import it.richkmeli.rms.data.entity.configuration.ConfigurationEnum;
import it.richkmeli.rms.data.entity.configuration.ConfigurationManager;
import it.richkmeli.rms.data.entity.device.DeviceDatabaseSpringManager;
import it.richkmeli.rms.data.entity.device.model.Device;
import it.richkmeli.rms.data.entity.rmc.RmcDatabaseSpringManager;
import it.richkmeli.rms.data.entity.rmc.model.Rmc;
import it.richkmeli.rms.data.entity.user.AuthDatabaseSpringManager;
import it.richkmeli.rms.data.entity.user.model.User;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; | package it.richkmeli.rms.data;
// Annotating a class with the @Configuration annotation indicates
// that the class will be used by JavaConfig as a source of bean definitions.
@Configuration
class LoadDatabase {
@Bean | CommandLineRunner initDatabase(AuthDatabaseSpringManager authDatabaseSpringManager, DeviceDatabaseSpringManager deviceDatabaseSpringManager, RmcDatabaseSpringManager rmcDatabaseSpringManager, ConfigurationDatabaseManager configurationDatabaseManager) { | 5 |
theblackwidower/KanaQuiz | app/src/main/java/com/noprestige/kanaquiz/options/QuestionSelectionDetail.java | [
"public class KanaQuestion extends Question\n{\n private final String kana;\n private final String defaultRomaji;\n private final Map<RomanizationSystem, String> altRomaji;\n\n KanaQuestion(String kana, String romaji)\n {\n this(kana, romaji, null);\n }\n\n KanaQuestion(String kana, String romaji, Map<RomanizationSystem, String> altRomaji)\n {\n this.kana = kana.trim();\n defaultRomaji = romaji.trim();\n this.altRomaji = altRomaji;\n }\n\n @Override\n public String getQuestionText()\n {\n return kana;\n }\n\n @Override\n boolean checkAnswer(String response)\n {\n if (defaultRomaji.trim().equalsIgnoreCase(response.trim()))\n return true;\n if (altRomaji != null)\n for (String correctAnswer : altRomaji.values())\n if (correctAnswer.trim().equalsIgnoreCase(response.trim()))\n return true;\n\n return false;\n }\n\n @Override\n public String fetchCorrectAnswer()\n {\n return fetchRomaji();\n }\n\n enum RomanizationSystem\n {\n HEPBURN,\n NIHON,\n KUNREI,\n UNKNOWN\n }\n\n String fetchRomaji()\n {\n if (OptionsControl.compareStrings(R.string.prefid_romanize_system, R.string.prefid_romanize_system_default))\n return defaultRomaji;\n else if (OptionsControl\n .compareStrings(R.string.prefid_romanize_system, R.string.prefid_romanize_system_hepburn))\n return fetchRomaji(RomanizationSystem.HEPBURN);\n else if (OptionsControl.compareStrings(R.string.prefid_romanize_system, R.string.prefid_romanize_system_nihon))\n return fetchRomaji(RomanizationSystem.NIHON);\n else if (OptionsControl.compareStrings(R.string.prefid_romanize_system, R.string.prefid_romanize_system_kunrei))\n return fetchRomaji(RomanizationSystem.KUNREI);\n else\n return defaultRomaji;\n }\n\n String fetchRomaji(RomanizationSystem system)\n {\n String romaji = (((system == null) || (altRomaji == null)) ? null : altRomaji.get(system));\n return (romaji == null) ? defaultRomaji : romaji;\n }\n\n @Override\n public String getDatabaseKey()\n {\n return kana;\n }\n\n @Override\n public ReferenceCell generateReference(Context context)\n {\n ReferenceCell cell = super.generateReference(context);\n if (isDigraph())\n cell.setSubjectSize(context.getResources().getDimension(R.dimen.diacriticReferenceSubjectSize));\n return cell;\n }\n\n public boolean isDigraph()\n {\n return kana.length() > 1;\n }\n\n public boolean isDiacritic()\n {\n for (int i = 0; i < kana.length(); i++)\n if (isDiacritic(Character.codePointAt(kana, i)))\n return true;\n return false;\n }\n\n @Override\n QuestionType getType()\n {\n return QuestionType.KANA;\n }\n}",
"public class KanjiQuestion extends Question\n{\n public static final String MEANING_DELIMITER = \"/\";\n\n final String kanji;\n final String meaning;\n final String kunYomi;\n final String onYomi;\n\n KanjiQuestion(String kanji, String meaning, String kunYomi, String onYomi)\n {\n this.kanji = kanji;\n this.meaning = meaning;\n this.kunYomi = kunYomi;\n this.onYomi = onYomi;\n }\n\n KanjiSoundQuestion getKunYomiQuestion()\n {\n return new KanjiSoundQuestion(this, QuestionType.KUN_YOMI);\n }\n\n KanjiSoundQuestion getOnYomiQuestion()\n {\n return new KanjiSoundQuestion(this, QuestionType.ON_YOMI);\n }\n\n @Override\n public String getQuestionText()\n {\n return kanji;\n }\n\n @Override\n boolean checkAnswer(String response)\n {\n if (meaning.trim().equalsIgnoreCase(response.trim()))\n return true;\n if (meaning.contains(MEANING_DELIMITER))\n for (String subAnswer : meaning.split(MEANING_DELIMITER))\n if (subAnswer.trim().equalsIgnoreCase(response.trim()))\n return true;\n\n return false;\n }\n\n @Override\n public String fetchCorrectAnswer()\n {\n return meaning;\n }\n\n @Override\n public String getDatabaseKey()\n {\n return kanji;\n }\n\n @Override\n public ReferenceCell generateReference(Context context)\n {\n ReferenceCell cell = super.generateReference(context);\n cell.setSubjectSize(context.getResources().getDimension(R.dimen.kanjiReferenceSubjectSize));\n cell.setDescriptionSize(context.getResources().getDimension(R.dimen.kanjiReferenceDescriptionSize));\n return cell;\n }\n\n @Override\n QuestionType getType()\n {\n return QuestionType.KANJI;\n }\n}",
"public abstract class Question\n{\n public static final Question[] EMPTY_QUESTION_ARRAY = new Question[0];\n\n public abstract String getQuestionText();\n\n abstract boolean checkAnswer(String response);\n\n public abstract String fetchCorrectAnswer();\n\n public abstract String getDatabaseKey();\n\n abstract QuestionType getType();\n\n public ReferenceCell generateReference(Context context)\n {\n ReferenceCell cell = new ReferenceCell(context);\n cell.setSubject(getQuestionText());\n cell.setDescription(fetchCorrectAnswer());\n return cell;\n }\n\n\n public static boolean isDiacritic(int charCode)\n {\n if ((charCode < 0x3041) || (charCode > 0x30FF))\n return false; //not kana anyway\n else if (((charCode >= 0x30F7) && (charCode <= 0x30FA)) || //special katakana diacritics\n ((charCode >= 0x3099) && (charCode <= 0x309C))) //single diacritic characters\n return true;\n\n charCode %= 0x60; //can now run the calculations once for both hiragana and katakana\n\n if (((charCode >= 0x40) && (charCode <= 0x4B)) || //early vowels\n ((charCode >= 0x0A) && (charCode <= 0x0E)) || //N-set\n ((charCode >= 0x1E) && (charCode <= 0x33))) //M, Y, R, W-sets and N\n return false;\n\n else if ((charCode >= 0x4C) || (charCode <= 0x03))\n return ((charCode % 2) == 0); //K and S-sets, and first few T-set chars\n\n else if (charCode <= 0x09) // && charCode >= 0x04\n return ((charCode % 2) == 1); //last few T-set chars\n\n else if (charCode <= 0x1D) // && charCode >= 0x0F\n return ((charCode % 3) != 0); //H-set with two types of diacritics\n\n else\n return ((charCode == 0x34) || (charCode == 0x3E));\n //two special characters at the end of the block, which I'm counting.\n }\n\n enum KanaSystem\n {\n HIRAGANA,\n KATAKANA,\n DIACRITIC_MARK,\n BOTH_KANA,\n NO_KANA\n }\n\n public static KanaSystem whatKanaSystem(int charCode)\n {\n if ((charCode < 0x3041) || (charCode > 0x30FF))\n return KanaSystem.NO_KANA; //not kana anyway\n else if ((charCode <= 0x3096) || ((charCode >= 0x309D) && (charCode <= 0x309F)))\n return KanaSystem.HIRAGANA;\n else if (((charCode >= 0x30A1) && (charCode <= 0x30FA)) || (charCode >= 0x30FD))\n return KanaSystem.KATAKANA;\n else if ((charCode >= 0x3099) && (charCode <= 0x309C))\n return KanaSystem.DIACRITIC_MARK;\n else if (charCode == 0x30A0) // Double hyphen\n return KanaSystem.BOTH_KANA;\n else if (charCode == 0x30FC) // Prolonged sound mark\n return KanaSystem.BOTH_KANA;\n else if (charCode == 0x30FB) // Middle Dot\n return KanaSystem.KATAKANA;\n else\n return KanaSystem.NO_KANA; //possibly a reserved character in the block\n }\n\n public static KanaSystem whatKanaSystem(CharSequence kana)\n {\n int hiraganaCount = 0;\n int katakanaCount = 0;\n int diacriticMarkCount = 0;\n int bothKanaCount = 0;\n int noKanaCount = 0;\n\n for (int i = 0; i < kana.length(); i++)\n switch (whatKanaSystem(kana.charAt(i)))\n {\n case HIRAGANA:\n hiraganaCount++;\n break;\n case KATAKANA:\n katakanaCount++;\n break;\n case DIACRITIC_MARK:\n diacriticMarkCount++;\n break;\n case BOTH_KANA:\n bothKanaCount++;\n break;\n case NO_KANA:\n noKanaCount++;\n }\n\n if (noKanaCount > 0)\n return KanaSystem.NO_KANA;\n else if ((hiraganaCount > 0) || (katakanaCount > 0))\n if (hiraganaCount <= 0)\n return KanaSystem.KATAKANA;\n else if (katakanaCount <= 0)\n return KanaSystem.HIRAGANA;\n else\n return KanaSystem.BOTH_KANA;\n else if (diacriticMarkCount > 0)\n return KanaSystem.DIACRITIC_MARK;\n else if (bothKanaCount > 0)\n return KanaSystem.BOTH_KANA;\n else\n return null;\n }\n}",
"public class WordQuestion extends Question\n{\n private final String romaji;\n private final String kana;\n private final String kanji;\n private final String answer;\n private final String[] altAnswers;\n\n public WordQuestion(String romaji, String answer, String kana, String kanji, String[] altAnswers)\n {\n this.romaji = romaji.trim();\n this.answer = answer.trim();\n this.kana = (kana != null) ? kana.trim() : null;\n this.kanji = (kanji != null) ? kanji.trim() : null;\n this.altAnswers = altAnswers;\n }\n\n enum QuestionTextType\n {\n ROMAJI,\n KANA,\n KANJI\n }\n\n @Override\n public String getQuestionText()\n {\n if (OptionsControl.compareStrings(R.string.prefid_vocab_display, R.string.prefid_vocab_display_romaji))\n return fetchText(QuestionTextType.ROMAJI);\n else if (OptionsControl.compareStrings(R.string.prefid_vocab_display, R.string.prefid_vocab_display_kana))\n return fetchText(QuestionTextType.KANA);\n else if (OptionsControl.compareStrings(R.string.prefid_vocab_display, R.string.prefid_vocab_display_kanji))\n return fetchText(QuestionTextType.KANJI);\n else\n return fetchText(QuestionTextType.KANA);\n }\n\n @SuppressWarnings(\"fallthrough\")\n private String fetchText(QuestionTextType type)\n {\n switch (type)\n {\n case KANJI:\n if (kanji != null)\n return kanji;\n case KANA:\n if (kana != null)\n return kana;\n case ROMAJI:\n default:\n return romaji;\n }\n }\n\n @Override\n boolean checkAnswer(String response)\n {\n if (answer.trim().equalsIgnoreCase(response.trim()))\n return true;\n else if (altAnswers != null)\n for (String answer : altAnswers)\n if (answer.trim().equalsIgnoreCase(response.trim()))\n return true;\n if (answer.contains(MEANING_DELIMITER))\n for (String subAnswer : answer.split(MEANING_DELIMITER))\n if (subAnswer.trim().equalsIgnoreCase(response.trim()))\n return true;\n return false;\n }\n\n @Override\n public String fetchCorrectAnswer()\n {\n return answer;\n }\n\n @Override\n public String getDatabaseKey()\n {\n return romaji;\n }\n\n @Override\n public ReferenceCell generateReference(Context context)\n {\n ReferenceCell cell = super.generateReference(context);\n cell.setSubjectSize(context.getResources().getDimension(R.dimen.vocabReferenceSubjectSize));\n return cell;\n }\n\n @Override\n QuestionType getType()\n {\n return QuestionType.VOCABULARY;\n }\n}",
"public static final String SUBPREFERENCE_DELIMITER = \"~\";"
] | import static com.noprestige.kanaquiz.questions.QuestionManagement.SUBPREFERENCE_DELIMITER;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import com.noprestige.kanaquiz.R;
import com.noprestige.kanaquiz.questions.KanaQuestion;
import com.noprestige.kanaquiz.questions.KanjiQuestion;
import com.noprestige.kanaquiz.questions.Question;
import com.noprestige.kanaquiz.questions.WordQuestion;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.DialogFragment; | /*
* Copyright 2021 T Duke Perry
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.noprestige.kanaquiz.options;
public class QuestionSelectionDetail extends DialogFragment
{
private static final String ARG_PREFID = "prefId";
private static final String ARG_QUESTION_NAMES = "questionNames";
private static final String ARG_QUESTION_PREFIDS = "questionPrefIds";
private boolean[] isCheckedSet;
private QuestionSelectionItem parent;
public static QuestionSelectionDetail newInstance(String prefId, Question[] questions)
{
Bundle args = new Bundle();
QuestionSelectionDetail dialog = new QuestionSelectionDetail();
args.putString(ARG_PREFID, prefId);
String[] questionNames = new String[questions.length];
String[] questionPrefIds = new String[questions.length];
for (int i = 0; i < questions.length; i++)
{
if (questions[i].getClass().equals(KanaQuestion.class) ||
questions[i].getClass().equals(KanjiQuestion.class))
questionNames[i] = questions[i].getQuestionText() + " - " + questions[i].fetchCorrectAnswer(); | else if (questions[i].getClass().equals(WordQuestion.class)) | 3 |
yyxhdy/ManyEAs | src/jmetal/problems/Tanaka.java | [
"public abstract class Problem implements Serializable {\n\n\t/**\n\t * Defines the default precision of binary-coded variables\n\t */\n\tprivate final static int DEFAULT_PRECISSION = 16;\n\n\t/**\n\t * Stores the number of variables of the problem\n\t */\n\tprotected int numberOfVariables_;\n\n\t/**\n\t * Stores the number of objectives of the problem\n\t */\n\tprotected int numberOfObjectives_;\n\n\t/**\n\t * Stores the number of constraints of the problem\n\t */\n\tprotected int numberOfConstraints_;\n\n\t/**\n\t * Stores the problem name\n\t */\n\tprotected String problemName_;\n\n\t/**\n\t * Stores the type of the solutions of the problem\n\t */\n\tprotected SolutionType solutionType_;\n\n\t/**\n\t * Stores the lower bound values for each encodings.variable (only if\n\t * needed)\n\t */\n\tprotected double[] lowerLimit_;\n\n\t/**\n\t * Stores the upper bound values for each encodings.variable (only if\n\t * needed)\n\t */\n\tprotected double[] upperLimit_;\n\n\t/**\n\t * Stores the number of bits used by binary-coded variables (e.g.,\n\t * BinaryReal variables). By default, they are initialized to\n\t * DEFAULT_PRECISION)\n\t */\n\tprivate int[] precision_;\n\n\t/**\n\t * Stores the length of each encodings.variable when applicable (e.g.,\n\t * Binary and Permutation variables)\n\t */\n\tprotected int[] length_;\n\n\t/**\n\t * Stores the type of each encodings.variable\n\t */\n\t// public Class [] variableType_;\n\n\t/**\n\t * Constructor.\n\t */\n\tpublic Problem() {\n\t\tsolutionType_ = null;\n\t} // Problem\n\n\t/**\n\t * Constructor.\n\t */\n\tpublic Problem(SolutionType solutionType) {\n\t\tsolutionType_ = solutionType;\n\t} // Problem\n\n\t/**\n\t * Gets the number of decision variables of the problem.\n\t * \n\t * @return the number of decision variables.\n\t */\n\tpublic int getNumberOfVariables() {\n\t\treturn numberOfVariables_;\n\t} // getNumberOfVariables\n\n\t/**\n\t * Sets the number of decision variables of the problem.\n\t */\n\tpublic void setNumberOfVariables(int numberOfVariables) {\n\t\tnumberOfVariables_ = numberOfVariables;\n\t} // getNumberOfVariables\n\n\t/**\n\t * Gets the the number of objectives of the problem.\n\t * \n\t * @return the number of objectives.\n\t */\n\tpublic int getNumberOfObjectives() {\n\t\treturn numberOfObjectives_;\n\t} // getNumberOfObjectives\n\n\t/**\n\t * Gets the lower bound of the ith encodings.variable of the problem.\n\t * \n\t * @param i\n\t * The index of the encodings.variable.\n\t * @return The lower bound.\n\t */\n\tpublic double getLowerLimit(int i) {\n\t\treturn lowerLimit_[i];\n\t} // getLowerLimit\n\n\t/**\n\t * Gets the upper bound of the ith encodings.variable of the problem.\n\t * \n\t * @param i\n\t * The index of the encodings.variable.\n\t * @return The upper bound.\n\t */\n\tpublic double getUpperLimit(int i) {\n\t\treturn upperLimit_[i];\n\t} // getUpperLimit\n\n\t/**\n\t * Evaluates a <code>Solution</code> object.\n\t * \n\t * @param solution\n\t * The <code>Solution</code> to evaluate.\n\t */\n\tpublic abstract void evaluate(Solution solution) throws JMException;\n\n\t/**\n\t * Gets the number of side constraints in the problem.\n\t * \n\t * @return the number of constraints.\n\t */\n\tpublic int getNumberOfConstraints() {\n\t\treturn numberOfConstraints_;\n\t} // getNumberOfConstraints\n\n\t/**\n\t * Evaluates the overall constraint violation of a <code>Solution</code>\n\t * object.\n\t * \n\t * @param solution\n\t * The <code>Solution</code> to evaluate.\n\t */\n\tpublic void evaluateConstraints(Solution solution) throws JMException {\n\t\t// The default behavior is to do nothing. Only constrained problems have\n\t\t// to\n\t\t// re-define this method\n\t} // evaluateConstraints\n\n\t/**\n\t * Returns the number of bits that must be used to encode binary-real\n\t * variables\n\t * \n\t * @return the number of bits.\n\t */\n\tpublic int getPrecision(int var) {\n\t\treturn precision_[var];\n\t} // getPrecision\n\n\t/**\n\t * Returns array containing the number of bits that must be used to encode\n\t * binary-real variables.\n\t * \n\t * @return the number of bits.\n\t */\n\tpublic int[] getPrecision() {\n\t\treturn precision_;\n\t} // getPrecision\n\n\t/**\n\t * Sets the array containing the number of bits that must be used to encode\n\t * binary-real variables.\n\t * \n\t * @param precision\n\t * The array\n\t */\n\tpublic void setPrecision(int[] precision) {\n\t\tprecision_ = precision;\n\t} // getPrecision\n\n\t/**\n\t * Returns the length of the encodings.variable.\n\t * \n\t * @return the encodings.variable length.\n\t */\n\tpublic int getLength(int var) {\n\t\tif (length_ == null)\n\t\t\treturn DEFAULT_PRECISSION;\n\t\treturn length_[var];\n\t} // getLength\n\n\t/**\n\t * Sets the type of the variables of the problem.\n\t * \n\t * @param type\n\t * The type of the variables\n\t */\n\tpublic void setSolutionType(SolutionType type) {\n\t\tsolutionType_ = type;\n\t} // setSolutionType\n\n\t/**\n\t * Returns the type of the variables of the problem.\n\t * \n\t * @return type of the variables of the problem.\n\t */\n\tpublic SolutionType getSolutionType() {\n\t\treturn solutionType_;\n\t} // getSolutionType\n\n\t/**\n\t * Returns the problem name\n\t * \n\t * @return The problem name\n\t */\n\tpublic String getName() {\n\t\treturn problemName_;\n\t}\n\n\t/**\n\t * Returns the number of bits of the solutions of the problem\n\t * \n\t * @return The number of bits solutions of the problem\n\t */\n\tpublic int getNumberOfBits() {\n\t\tint result = 0;\n\t\tfor (int var = 0; var < numberOfVariables_; var++) {\n\t\t\tresult += getLength(var);\n\t\t}\n\t\treturn result;\n\t} // getNumberOfBits();\n} // Problem",
"public class Solution implements Serializable {\n\t/**\n\t * Stores the problem\n\t */\n\tprivate Problem problem_;\n\n\t/**\n\t * Stores the type of the encodings.variable\n\t */\n\tprivate SolutionType type_;\n\n\t/**\n\t * Stores the decision variables of the solution.\n\t */\n\tprivate Variable[] variable_;\n\n\t/**\n\t * Stores the objectives values of the solution.\n\t */\n\tprivate final double[] objective_;\n\n\t/**\n\t * Stores the number of objective values of the solution\n\t */\n\tprivate int numberOfObjectives_;\n\n\t/**\n\t * Stores the so called fitness value. Used in some metaheuristics\n\t */\n\tprivate double fitness_;\n\n\t/**\n\t * Used in algorithm AbYSS, this field is intended to be used to know when a\n\t * <code>Solution</code> is marked.\n\t */\n\tprivate boolean marked_;\n\n\t/**\n\t * Stores the so called rank of the solution. Used in NSGA-II\n\t */\n\tprivate int rank_;\n\n\t/**\n\t * Stores the overall constraint violation of the solution.\n\t */\n\tprivate double overallConstraintViolation_;\n\n\t/**\n\t * Stores the number of constraints violated by the solution.\n\t */\n\tprivate int numberOfViolatedConstraints_;\n\n\t/**\n\t * This field is intended to be used to know the location of a solution into\n\t * a <code>SolutionSet</code>. Used in MOCell\n\t */\n\tprivate int location_;\n\n\t/**\n\t * Stores the distance to his k-nearest neighbor into a\n\t * <code>SolutionSet</code>. Used in SPEA2.\n\t */\n\tprivate double kDistance_;\n\n\t/**\n\t * Stores the crowding distance of the the solution in a\n\t * <code>SolutionSet</code>. Used in NSGA-II.\n\t */\n\tprivate double crowdingDistance_;\n\n\t/**\n\t * Stores the distance between this solution and a <code>SolutionSet</code>.\n\t * Used in AbySS.\n\t */\n\tprivate double distanceToSolutionSet_;\n\t\n\t\n\t\n\tprivate int clusterID_;\n\tprivate double vDistance_;\n\n\t\n\t\n\n\n\tprivate double[] normalizedObjective_;\n\t\n\n\n\t/**\n\t * Constructor.\n\t */\n\tpublic Solution() {\n\t\tproblem_ = null;\n\t\tmarked_ = false;\n\t\toverallConstraintViolation_ = 0.0;\n\t\tnumberOfViolatedConstraints_ = 0;\n\t\ttype_ = null;\n\t\tvariable_ = null;\n\t\tobjective_ = null;\n\t\t\n\t\t\n\t} // Solution\n\n\t/**\n\t * Constructor\n\t * \n\t * @param numberOfObjectives\n\t * Number of objectives of the solution\n\t * \n\t * This constructor is used mainly to read objective values from\n\t * a file to variables of a SolutionSet to apply quality\n\t * indicators\n\t */\n\tpublic Solution(int numberOfObjectives) {\n\t\tnumberOfObjectives_ = numberOfObjectives;\n\t\tobjective_ = new double[numberOfObjectives];\n\t\t\n\t\tnormalizedObjective_ = new double[numberOfObjectives_];\n\n\t}\n\n\t/**\n\t * Constructor.\n\t * \n\t * @param problem\n\t * The problem to solve\n\t * @throws ClassNotFoundException\n\t */\n\tpublic Solution(Problem problem) throws ClassNotFoundException {\n\t\tproblem_ = problem;\n\t\ttype_ = problem.getSolutionType();\n\t\tnumberOfObjectives_ = problem.getNumberOfObjectives();\n\t\tobjective_ = new double[numberOfObjectives_];\n\n\t\tnormalizedObjective_ = new double[numberOfObjectives_];\n\t\t\n\t\t\n\t\t// Setting initial values\n\t\tfitness_ = 0.0;\n\t\tkDistance_ = 0.0;\n\t\tcrowdingDistance_ = 0.0;\n\t\tdistanceToSolutionSet_ = Double.POSITIVE_INFINITY;\n\t\t\n//\t\tr2Contribution_ = 0.0;\n\t\t// <-\n\t\t\n\n\n\t\t// variable_ = problem.solutionType_.createVariables() ;\n\t\tvariable_ = type_.createVariables();\n\t} // Solution\n\n\tstatic public Solution getNewSolution(Problem problem)\n\t\t\tthrows ClassNotFoundException {\n\t\treturn new Solution(problem);\n\t}\n\n\t/**\n\t * Constructor\n\t * \n\t * @param problem\n\t * The problem to solve\n\t */\n\tpublic Solution(Problem problem, Variable[] variables) {\n\t\tproblem_ = problem;\n\t\ttype_ = problem.getSolutionType();\n\t\tnumberOfObjectives_ = problem.getNumberOfObjectives();\n\t\tobjective_ = new double[numberOfObjectives_];\n\t\t\n\t\tnormalizedObjective_ = new double[numberOfObjectives_];\n\t\t\n\n\t\t\n\t\t// Setting initial values\n\t\tfitness_ = 0.0;\n\t\tkDistance_ = 0.0;\n\t\tcrowdingDistance_ = 0.0;\n\t\tdistanceToSolutionSet_ = Double.POSITIVE_INFINITY;\n\t\t\n//\t\tr2Contribution_ = 0.0;\n\t\t// <-\n\t\t\n\t\t\n\t\tvariable_ = variables;\n\t} // Constructor\n\n\t/**\n\t * Copy constructor.\n\t * \n\t * @param solution\n\t * Solution to copy.\n\t */\n\tpublic Solution(Solution solution) {\n\t\tproblem_ = solution.problem_;\n\t\ttype_ = solution.type_;\n\n\t\tnumberOfObjectives_ = solution.numberOfObjectives();\n\t\tobjective_ = new double[numberOfObjectives_];\n\t\t\n\t\tnormalizedObjective_ = new double[numberOfObjectives_];\n\t\t\n\n\t\t\n\t\tfor (int i = 0; i < objective_.length; i++) {\n\t\t\tobjective_[i] = solution.getObjective(i);\n\t\t\tnormalizedObjective_[i] = solution.getNormalizedObjective(i);\n\t\t} // for\n\t\t// <-\n\n\t\tvariable_ = type_.copyVariables(solution.variable_);\n\t\toverallConstraintViolation_ = solution.getOverallConstraintViolation();\n\t\tnumberOfViolatedConstraints_ = solution.getNumberOfViolatedConstraint();\n\t\tdistanceToSolutionSet_ = solution.getDistanceToSolutionSet();\n\t\tcrowdingDistance_ = solution.getCrowdingDistance();\n\t\tkDistance_ = solution.getKDistance();\n\t\tfitness_ = solution.getFitness();\n\t\tmarked_ = solution.isMarked();\n\t\trank_ = solution.getRank();\n\t\tlocation_ = solution.getLocation();\n\t\t\n\t\t\n\t} // Solution\n\n\t/**\n\t * Sets the distance between this solution and a <code>SolutionSet</code>.\n\t * The value is stored in <code>distanceToSolutionSet_</code>.\n\t * \n\t * @param distance\n\t * The distance to a solutionSet.\n\t */\n\tpublic void setDistanceToSolutionSet(double distance) {\n\t\tdistanceToSolutionSet_ = distance;\n\t} // SetDistanceToSolutionSet\n\n\t/**\n\t * Gets the distance from the solution to a <code>SolutionSet</code>. <b>\n\t * REQUIRE </b>: this method has to be invoked after calling\n\t * <code>setDistanceToPopulation</code>.\n\t * \n\t * @return the distance to a specific solutionSet.\n\t */\n\tpublic double getDistanceToSolutionSet() {\n\t\treturn distanceToSolutionSet_;\n\t} // getDistanceToSolutionSet\n\n\t/**\n\t * Sets the distance between the solution and its k-nearest neighbor in a\n\t * <code>SolutionSet</code>. The value is stored in <code>kDistance_</code>.\n\t * \n\t * @param distance\n\t * The distance to the k-nearest neighbor.\n\t */\n\tpublic void setKDistance(double distance) {\n\t\tkDistance_ = distance;\n\t} // setKDistance\n\n\t/**\n\t * Gets the distance from the solution to his k-nearest nighbor in a\n\t * <code>SolutionSet</code>. Returns the value stored in\n\t * <code>kDistance_</code>. <b> REQUIRE </b>: this method has to be invoked\n\t * after calling <code>setKDistance</code>.\n\t * \n\t * @return the distance to k-nearest neighbor.\n\t */\n\tdouble getKDistance() {\n\t\treturn kDistance_;\n\t} // getKDistance\n\n\t/**\n\t * Sets the crowding distance of a solution in a <code>SolutionSet</code>.\n\t * The value is stored in <code>crowdingDistance_</code>.\n\t * \n\t * @param distance\n\t * The crowding distance of the solution.\n\t */\n\tpublic void setCrowdingDistance(double distance) {\n\t\tcrowdingDistance_ = distance;\n\t} // setCrowdingDistance\n\n\t/**\n\t * Gets the crowding distance of the solution into a\n\t * <code>SolutionSet</code>. Returns the value stored in\n\t * <code>crowdingDistance_</code>. <b> REQUIRE </b>: this method has to be\n\t * invoked after calling <code>setCrowdingDistance</code>.\n\t * \n\t * @return the distance crowding distance of the solution.\n\t */\n\tpublic double getCrowdingDistance() {\n\t\treturn crowdingDistance_;\n\t} // getCrowdingDistance\n\n\t/**\n\t * Sets the fitness of a solution. The value is stored in\n\t * <code>fitness_</code>.\n\t * \n\t * @param fitness\n\t * The fitness of the solution.\n\t */\n\tpublic void setFitness(double fitness) {\n\t\tfitness_ = fitness;\n\t} // setFitness\n\n\t/**\n\t * Gets the fitness of the solution. Returns the value of stored in the\n\t * encodings.variable <code>fitness_</code>. <b> REQUIRE </b>: This method\n\t * has to be invoked after calling <code>setFitness()</code>.\n\t * \n\t * @return the fitness.\n\t */\n\tpublic double getFitness() {\n\t\treturn fitness_;\n\t} // getFitness\n\n\t/**\n\t * Sets the value of the i-th objective.\n\t * \n\t * @param i\n\t * The number identifying the objective.\n\t * @param value\n\t * The value to be stored.\n\t */\n\tpublic void setObjective(int i, double value) {\n\t\tobjective_[i] = value;\n\t} // setObjective\n\n\t/**\n\t * Returns the value of the i-th objective.\n\t * \n\t * @param i\n\t * The value of the objective.\n\t */\n\tpublic double getObjective(int i) {\n\t\treturn objective_[i];\n\t} // getObjective\n\n\t/**\n\t * Returns the number of objectives.\n\t * \n\t * @return The number of objectives.\n\t */\n\tpublic int numberOfObjectives() {\n\t\tif (objective_ == null)\n\t\t\treturn 0;\n\t\telse\n\t\t\treturn numberOfObjectives_;\n\t} // numberOfObjectives\n\t\n\t\n\tpublic int getNumberOfObjectives(){\n\t\tif (objective_ == null)\n\t\t\treturn 0;\n\t\telse\n\t\t\treturn numberOfObjectives_;\n\t}\n\n\t/**\n\t * Returns the number of decision variables of the solution.\n\t * \n\t * @return The number of decision variables.\n\t */\n\tpublic int numberOfVariables() {\n\t\treturn problem_.getNumberOfVariables();\n\t} // numberOfVariables\n\n\t/**\n\t * Returns a string representing the solution.\n\t * \n\t * @return The string.\n\t */\n\tpublic String toString() {\n\t\tString aux = \"\";\n\t\tfor (int i = 0; i < this.numberOfObjectives_; i++)\n\t\t\taux = aux + this.getObjective(i) + \" \";\n\n\t\treturn aux;\n\t} // toString\n\n\t/**\n\t * Returns the decision variables of the solution.\n\t * \n\t * @return the <code>DecisionVariables</code> object representing the\n\t * decision variables of the solution.\n\t */\n\tpublic Variable[] getDecisionVariables() {\n\t\treturn variable_;\n\t} // getDecisionVariables\n\n\t/**\n\t * Sets the decision variables for the solution.\n\t * \n\t * @param variables\n\t * The <code>DecisionVariables</code> object representing the\n\t * decision variables of the solution.\n\t */\n\tpublic void setDecisionVariables(Variable[] variables) {\n\t\tvariable_ = variables;\n\t} // setDecisionVariables\n\n\t/**\n\t * Indicates if the solution is marked.\n\t * \n\t * @return true if the method <code>marked</code> has been called and, after\n\t * that, the method <code>unmarked</code> hasn't been called. False\n\t * in other case.\n\t */\n\tpublic boolean isMarked() {\n\t\treturn this.marked_;\n\t} // isMarked\n\n\t/**\n\t * Establishes the solution as marked.\n\t */\n\tpublic void marked() {\n\t\tthis.marked_ = true;\n\t} // marked\n\n\t/**\n\t * Established the solution as unmarked.\n\t */\n\tpublic void unMarked() {\n\t\tthis.marked_ = false;\n\t} // unMarked\n\n\t/**\n\t * Sets the rank of a solution.\n\t * \n\t * @param value\n\t * The rank of the solution.\n\t */\n\tpublic void setRank(int value) {\n\t\tthis.rank_ = value;\n\t} // setRank\n\n\t/**\n\t * Gets the rank of the solution. <b> REQUIRE </b>: This method has to be\n\t * invoked after calling <code>setRank()</code>.\n\t * \n\t * @return the rank of the solution.\n\t */\n\tpublic int getRank() {\n\t\treturn this.rank_;\n\t} // getRank\n\n\n\t\n\tpublic void setNormalizedObjective(int i, double value) {\n\t\tnormalizedObjective_[i] = value;\n\t}\n\n\tpublic double getNormalizedObjective(int i) {\n\t\treturn normalizedObjective_[i];\n\t}\n\t\n\n\t\n\t/**\n\t * Sets the overall constraints violated by the solution.\n\t * \n\t * @param value\n\t * The overall constraints violated by the solution.\n\t */\n\tpublic void setOverallConstraintViolation(double value) {\n\t\tthis.overallConstraintViolation_ = value;\n\t} // setOverallConstraintViolation\n\n\t/**\n\t * Gets the overall constraint violated by the solution. <b> REQUIRE </b>:\n\t * This method has to be invoked after calling\n\t * <code>overallConstraintViolation</code>.\n\t * \n\t * @return the overall constraint violation by the solution.\n\t */\n\tpublic double getOverallConstraintViolation() {\n\t\treturn this.overallConstraintViolation_;\n\t} // getOverallConstraintViolation\n\n\t/**\n\t * Sets the number of constraints violated by the solution.\n\t * \n\t * @param value\n\t * The number of constraints violated by the solution.\n\t */\n\tpublic void setNumberOfViolatedConstraint(int value) {\n\t\tthis.numberOfViolatedConstraints_ = value;\n\t} // setNumberOfViolatedConstraint\n\n\t/**\n\t * Gets the number of constraint violated by the solution. <b> REQUIRE </b>:\n\t * This method has to be invoked after calling\n\t * <code>setNumberOfViolatedConstraint</code>.\n\t * \n\t * @return the number of constraints violated by the solution.\n\t */\n\tpublic int getNumberOfViolatedConstraint() {\n\t\treturn this.numberOfViolatedConstraints_;\n\t} // getNumberOfViolatedConstraint\n\n\t/**\n\t * Sets the location of the solution into a solutionSet.\n\t * \n\t * @param location\n\t * The location of the solution.\n\t */\n\tpublic void setLocation(int location) {\n\t\tthis.location_ = location;\n\t} // setLocation\n\n\t/**\n\t * Gets the location of this solution in a <code>SolutionSet</code>. <b>\n\t * REQUIRE </b>: This method has to be invoked after calling\n\t * <code>setLocation</code>.\n\t * \n\t * @return the location of the solution into a solutionSet\n\t */\n\tpublic int getLocation() {\n\t\treturn this.location_;\n\t} // getLocation\n\t\n\t\n\t\n\tpublic void setClusterID(int id){\n\t\tthis.clusterID_ = id;\n\t}\n\t\n\tpublic int getClusterID(){\n\t\treturn this.clusterID_;\n\t}\n\t\n\t\n\tpublic void setVDistance(double val){\n\t\tthis.vDistance_ = val;\n\t}\n\t\n\tpublic double getVDistance(){\n\t\treturn this.vDistance_;\n\t}\n\t\n\n\t\n\n\t/**\n\t * Sets the type of the encodings.variable.\n\t * \n\t * @param type\n\t * The type of the encodings.variable.\n\t */\n\t// public void setType(String type) {\n\t// type_ = Class.forName(\"\") ;\n\t// } // setType\n\n\t/**\n\t * Sets the type of the encodings.variable.\n\t * \n\t * @param type\n\t * The type of the encodings.variable.\n\t */\n\tpublic void setType(SolutionType type) {\n\t\ttype_ = type;\n\t} // setType\n\n\t/**\n\t * Gets the type of the encodings.variable\n\t * \n\t * @return the type of the encodings.variable\n\t */\n\tpublic SolutionType getType() {\n\t\treturn type_;\n\t} // getType\n\n\t/**\n\t * Returns the aggregative value of the solution\n\t * \n\t * @return The aggregative value.\n\t */\n\tpublic double getAggregativeValue() {\n\t\tdouble value = 0.0;\n\t\tfor (int i = 0; i < numberOfObjectives(); i++) {\n\t\t\tvalue += getObjective(i);\n\t\t}\n\t\treturn value;\n\t} // getAggregativeValue\n\t\n\n\n\t/**\n\t * Returns the number of bits of the chromosome in case of using a binary\n\t * representation\n\t * \n\t * @return The number of bits if the case of binary variables, 0 otherwise\n\t * This method had a bug which was fixed by Rafael Olaechea\n\t */\n\tpublic int getNumberOfBits() {\n\t\tint bits = 0;\n\n\t\tfor (int i = 0; i < variable_.length; i++)\n\t\t\tif ((variable_[i].getVariableType() == jmetal.encodings.variable.Binary.class)\n\t\t\t\t\t|| (variable_[i].getVariableType() == jmetal.encodings.variable.BinaryReal.class))\n\n\t\t\t\tbits += ((Binary) (variable_[i])).getNumberOfBits();\n\n\t\treturn bits;\n\t} // getNumberOfBits\n\t\n\tpublic Problem getProblem(){\n\t\treturn problem_;\n\t}\n} // Solution",
"public abstract class Variable implements Serializable {\n\n /** \n * Creates an exact copy of a <code>Variable</code> object.\n * @return the copy of the object.\n */\n public abstract Variable deepCopy();\n\n /**\n * Gets the double value representating the encodings.variable.\n * It is used in subclasses of <code>Variable</code> (i.e. <code>Real</code> \n * and <code>Int</code>).\n * As not all objects belonging to a subclass of <code>Variable</code> have a \n * double value, a call to this method it is considered a fatal error by \n * default, and the program is terminated. Those classes requiring this method \n * must redefine it.\n */\n public double getValue() throws JMException {\n Class cls = java.lang.String.class;\n String name = cls.getName(); \n Configuration.logger_.severe(\"Class \" + name + \" does not implement \" +\n \"method getValue\");\n throw new JMException(\"Exception in \" + name + \".getValue()\") ;\n } // getValue\n \n /**\n * Sets a double value to a encodings.variable in subclasses of <code>Variable</code>.\n * As not all objects belonging to a subclass of <code>Variable</code> have a \n * double value, a call to this method it is considered a fatal error by \n * default, and the program is terminated. Those classes requiring this method \n * must redefine it.\n */\n public void setValue(double value) throws JMException {\n Class cls = java.lang.String.class;\n String name = cls.getName(); \n Configuration.logger_.severe(\"Class \" + name + \" does not implement \" +\n \"method setValue\");\n throw new JMException(\"Exception in \" + name + \".setValue()\") ;\n } // setValue\n\n /**\n * Gets the lower bound value of a encodings.variable. As not all\n * objects belonging to a subclass of <code>Variable</code> have a lower bound,\n * a call to this method is considered a fatal error by default,\n * and the program is terminated.\n * Those classes requiring this method must redefine it.\n */\n public double getLowerBound() throws JMException { \n Class cls = java.lang.String.class;\n String name = cls.getName(); \n Configuration.logger_.severe(\"Class \" + name + \n \" does not implement method getLowerBound()\");\n throw new JMException(\"Exception in \" + name + \".getLowerBound()\") ;\n } // getLowerBound\n \n /**\n * Gets the upper bound value of a encodings.variable. As not all\n * objects belonging to a subclass of <code>Variable</code> have an upper \n * bound, a call to this method is considered a fatal error by default, and the \n * program is terminated. Those classes requiring this method must redefine it.\n */\n public double getUpperBound() throws JMException {\n Class cls = java.lang.String.class;\n String name = cls.getName(); \n Configuration.logger_.severe(\"Class \" + name + \n \" does not implement method getUpperBound()\");\n throw new JMException(\"Exception in \" + name + \".getUpperBound()\") ;\n } // getUpperBound\n \n /**\n * Sets the lower bound for a encodings.variable. As not all objects belonging to a\n * subclass of <code>Variable</code> have a lower bound, a call to this method \n * is considered a fatal error by default and the program is terminated.\n * Those classes requiring this method must to redefine it.\n */\n public void setLowerBound(double lowerBound) throws JMException {\n Class cls = java.lang.String.class;\n String name = cls.getName(); \n Configuration.logger_.severe(\"Class \" + name + \n \" does not implement method setLowerBound()\");\n throw new JMException(\"Exception in \" + name + \".setLowerBound()\") ;\n } // setLowerBound\n \n /**\n * Sets the upper bound for a encodings.variable. As not all objects belonging to a\n * subclass of <code>Variable</code> have an upper bound, a call to this method\n * is considered a fatal error by default, and the program is terminated. \n * Those classes requiring this method must redefine it.\n */\n public void setUpperBound(double upperBound) throws JMException {\n Class cls = java.lang.String.class;\n String name = cls.getName(); \n Configuration.logger_.severe(\"Class \" + name + \n \" does not implement method setUpperBound()\");\n throw new JMException(\"Exception in \" + name + \".setUpperBound()\") ;\n } // setUpperBound\n\n /**\n * Gets the type of the encodings.variable. The types are defined in class Problem.\n * @return The type of the encodings.variable\n */\n \n public Class getVariableType() {\n return this.getClass() ;\n } // getVariableType\n} // Variable",
"public class BinaryRealSolutionType extends SolutionType {\n\n\t/**\n\t * Constructor\n\t * \n\t * @param problem\n\t * Problem to solve\n\t */\n\tpublic BinaryRealSolutionType(Problem problem) {\n\t\tsuper(problem);\n\t} // Constructor\n\n\t/**\n\t * Creates the variables of the solution\n\t */\n\tpublic Variable[] createVariables() {\n\t\tVariable[] variables = new Variable[problem_.getNumberOfVariables()];\n\n\t\tfor (int var = 0; var < problem_.getNumberOfVariables(); var++) {\n\t\t\tif (problem_.getPrecision() == null) {\n\t\t\t\tint[] precision = new int[problem_.getNumberOfVariables()];\n\t\t\t\tfor (int i = 0; i < problem_.getNumberOfVariables(); i++)\n\t\t\t\t\tprecision[i] = jmetal.encodings.variable.BinaryReal.DEFAULT_PRECISION;\n\t\t\t\tproblem_.setPrecision(precision);\n\t\t\t} // if\n\t\t\tvariables[var] = new BinaryReal(problem_.getPrecision(var),\n\t\t\t\t\tproblem_.getLowerLimit(var), problem_.getUpperLimit(var));\n\t\t} // for\n\t\treturn variables;\n\t} // createVariables\n} // BinaryRealSolutionType",
"public class RealSolutionType extends SolutionType {\n\n\t/**\n\t * Constructor\n\t * @param problem Problem to solve\n\t */\n\tpublic RealSolutionType(Problem problem) {\n\t\tsuper(problem) ;\n\t} // Constructor\n\n\t/**\n\t * Creates the variables of the solution\n\t */\n\tpublic Variable[] createVariables() {\n\t\tVariable[] variables = new Variable[problem_.getNumberOfVariables()];\n\n\t\tfor (int var = 0; var < problem_.getNumberOfVariables(); var++)\n\t\t\tvariables[var] = new Real(problem_.getLowerLimit(var),\n\t\t\t\t\tproblem_.getUpperLimit(var)); \n\n\t\treturn variables ;\n\t} // createVariables\n} // RealSolutionType",
"public class JMException extends Exception implements Serializable {\n \n /**\n * Constructor\n * @param Error message\n */\n public JMException (String message){\n super(message); \n } // JmetalException\n}"
] | import jmetal.core.Problem;
import jmetal.core.Solution;
import jmetal.core.Variable;
import jmetal.encodings.solutionType.BinaryRealSolutionType;
import jmetal.encodings.solutionType.RealSolutionType;
import jmetal.util.JMException; | // Tanaka.java
//
// Author:
// Antonio J. Nebro <antonio@lcc.uma.es>
// Juan J. Durillo <durillo@lcc.uma.es>
//
// Copyright (c) 2011 Antonio J. Nebro, Juan J. Durillo
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package jmetal.problems;
/**
* Class representing problem Tanaka
*/
public class Tanaka extends Problem{
/**
* Constructor.
* Creates a default instance of the problem Tanaka
* @param solutionType The solution type must "Real" or "BinaryReal".
*/
public Tanaka(String solutionType) {
numberOfVariables_ = 2;
numberOfObjectives_ = 2;
numberOfConstraints_= 2;
problemName_ = "Tanaka";
upperLimit_ = new double[numberOfVariables_];
lowerLimit_ = new double[numberOfVariables_];
for (int var = 0; var < numberOfVariables_; var++){
lowerLimit_[var] = 10e-5;
upperLimit_[var] = Math.PI;
} // for
if (solutionType.compareTo("BinaryReal") == 0)
solutionType_ = new BinaryRealSolutionType(this) ;
else if (solutionType.compareTo("Real") == 0)
solutionType_ = new RealSolutionType(this) ;
else {
System.out.println("Error: solution type " + solutionType + " invalid") ;
System.exit(-1) ;
}
}
/**
* Evaluates a solution
* @param solution The solution to evaluate
* @throws JMException
*/ | public void evaluate(Solution solution) throws JMException { | 1 |
wolispace/soft-pixel-dungeon | src/com/shatteredpixel/shatteredpixeldungeon/windows/WndBag.java | [
"public class Assets {\n\n\tpublic static final String ARCS_BG\t\t= \"arcs1.png\";\n\tpublic static final String ARCS_FG\t\t= \"arcs2.png\";\n\tpublic static final String DASHBOARD\t= \"dashboard.png\";\n\t\n\tpublic static final String BANNERS\t= \"banners.png\";\n\tpublic static final String BADGES\t= \"badges.png\";\n\tpublic static final String AMULET\t= \"amulet.png\";\n\t\n\tpublic static final String CHROME\t= \"chrome.png\";\n\tpublic static final String ICONS\t= \"icons.png\";\n\tpublic static final String STATUS\t= \"status_pane.png\";\n\tpublic static final String HP_BAR\t= \"hp_bar.png\";\n\tpublic static final String XP_BAR\t= \"exp_bar.png\";\n\tpublic static final String TOOLBAR\t= \"toolbar.png\";\n\t\n\tpublic static final String WARRIOR\t= \"warrior.png\";\n\tpublic static final String MAGE\t\t= \"mage.png\";\n\tpublic static final String ROGUE\t= \"rogue.png\";\n\tpublic static final String HUNTRESS\t= \"ranger.png\";\n\tpublic static final String AVATARS\t= \"avatars.png\";\n public static final String PET\t\t= \"pet.png\";\n\t\n\tpublic static final String SURFACE\t= \"surface.png\";\n\t\n\tpublic static final String FIREBALL\t\t= \"fireball.png\";\n\tpublic static final String SPECKS\t\t= \"specks.png\";\n\tpublic static final String EFFECTS\t\t= \"effects.png\";\n\t\n\tpublic static final String RAT\t\t= \"rat.png\";\n\tpublic static final String GNOLL\t= \"gnoll.png\";\n\tpublic static final String CRAB\t\t= \"crab.png\";\n\tpublic static final String GOO\t\t= \"goo.png\";\n\tpublic static final String SWARM\t= \"swarm.png\";\n\tpublic static final String SKELETON\t= \"skeleton.png\";\n\tpublic static final String SHAMAN\t= \"shaman.png\";\n\tpublic static final String THIEF\t= \"thief.png\";\n\tpublic static final String TENGU\t= \"tengu.png\";\n\tpublic static final String SHEEP\t= \"sheep.png\";\n\tpublic static final String KEEPER\t= \"shopkeeper.png\";\n\tpublic static final String BAT\t\t= \"bat.png\";\n\tpublic static final String BRUTE\t= \"brute.png\";\n\tpublic static final String SPINNER\t= \"spinner.png\";\n\tpublic static final String DM300\t= \"dm300.png\";\n\tpublic static final String WRAITH\t= \"wraith.png\";\n\tpublic static final String ELEMENTAL= \"elemental.png\";\n\tpublic static final String MONK\t\t= \"monk.png\";\n\tpublic static final String WARLOCK\t= \"warlock.png\";\n\tpublic static final String GOLEM\t= \"golem.png\";\n\tpublic static final String UNDEAD\t= \"undead.png\";\n\tpublic static final String KING\t\t= \"king.png\";\n\tpublic static final String STATUE\t= \"statue.png\";\n\tpublic static final String PIRANHA\t= \"piranha.png\";\n\tpublic static final String EYE\t\t= \"eye.png\";\n\tpublic static final String SUCCUBUS\t= \"succubus.png\";\n\tpublic static final String SCORPIO\t= \"scorpio.png\";\n\tpublic static final String ROTTING\t= \"rotting_fist.png\";\n\tpublic static final String BURNING\t= \"burning_fist.png\";\n\tpublic static final String YOG\t\t= \"yog.png\";\n\tpublic static final String LARVA\t= \"larva.png\";\n\tpublic static final String GHOST\t= \"ghost.png\";\n\tpublic static final String MAKER\t= \"wandmaker.png\";\n\tpublic static final String TROLL\t= \"blacksmith.png\";\n\tpublic static final String IMP\t\t= \"demon.png\";\n\tpublic static final String RATKING\t= \"ratking.png\";\n\t\n\tpublic static final String ITEMS\t= \"items.png\";\n\tpublic static final String PLANTS\t= \"plants.png\";\n\t\n\tpublic static final String TILES_SEWERS\t= \"tiles0.png\";\n\tpublic static final String TILES_PRISON\t= \"tiles1.png\";\n\tpublic static final String TILES_CAVES\t= \"tiles2.png\";\n\tpublic static final String TILES_CITY\t= \"tiles3.png\";\n\tpublic static final String TILES_HALLS\t= \"tiles4.png\";\n\t\n\tpublic static final String WATER_SEWERS\t= \"water0.png\";\n\tpublic static final String WATER_PRISON\t= \"water1.png\";\n\tpublic static final String WATER_CAVES\t= \"water2.png\";\n\tpublic static final String WATER_CITY\t= \"water3.png\";\n\tpublic static final String WATER_HALLS\t= \"water4.png\";\n\t\n\tpublic static final String BUFFS_SMALL\t= \"buffs.png\";\n\tpublic static final String BUFFS_LARGE\t= \"large_buffs.png\";\n\tpublic static final String SPELL_ICONS\t= \"spell_icons.png\";\n\t\n\tpublic static final String FONTS1X\t= \"font1x.png\";\n\tpublic static final String FONTS15X\t= \"font15x.png\";\n\tpublic static final String FONTS2X\t= \"font2x.png\";\n\tpublic static final String FONTS25X\t= \"font25x.png\";\n\tpublic static final String FONTS3X\t= \"font3x.png\";\n\t\n\tpublic static final String THEME\t= \"theme.mp3\";\n\tpublic static final String TUNE\t\t= \"game.mp3\";\n\tpublic static final String HAPPY\t= \"surface.mp3\";\n\t\n\tpublic static final String SND_CLICK\t= \"snd_click.mp3\";\n\tpublic static final String SND_BADGE\t= \"snd_badge.mp3\";\n\tpublic static final String SND_GOLD\t\t= \"snd_gold.mp3\";\n\t\n\tpublic static final String SND_OPEN\t\t= \"snd_door_open.mp3\";\n\tpublic static final String SND_UNLOCK\t= \"snd_unlock.mp3\";\n\tpublic static final String SND_ITEM\t\t= \"snd_item.mp3\";\n\tpublic static final String SND_DEWDROP\t= \"snd_dewdrop.mp3\";\n\tpublic static final String SND_HIT\t\t= \"snd_hit.mp3\";\n\tpublic static final String SND_MISS\t\t= \"snd_miss.mp3\";\n\tpublic static final String SND_STEP\t\t= \"snd_step.mp3\";\n\tpublic static final String SND_WATER\t= \"snd_water.mp3\";\n\tpublic static final String SND_DESCEND\t= \"snd_descend.mp3\";\n\tpublic static final String SND_EAT\t\t= \"snd_eat.mp3\";\n\tpublic static final String SND_READ\t\t= \"snd_read.mp3\";\n\tpublic static final String SND_LULLABY\t= \"snd_lullaby.mp3\";\n\tpublic static final String SND_DRINK\t= \"snd_drink.mp3\";\n\tpublic static final String SND_SHATTER\t= \"snd_shatter.mp3\";\n\tpublic static final String SND_ZAP\t\t= \"snd_zap.mp3\";\n\tpublic static final String SND_LIGHTNING= \"snd_lightning.mp3\";\n\tpublic static final String SND_LEVELUP\t= \"snd_levelup.mp3\";\n\tpublic static final String SND_DEATH\t= \"snd_death.mp3\";\n\tpublic static final String SND_CHALLENGE= \"snd_challenge.mp3\";\n\tpublic static final String SND_CURSED\t= \"snd_cursed.mp3\";\n\tpublic static final String SND_TRAP\t\t= \"snd_trap.mp3\";\n\tpublic static final String SND_EVOKE\t= \"snd_evoke.mp3\";\n\tpublic static final String SND_TOMB\t\t= \"snd_tomb.mp3\";\n\tpublic static final String SND_ALERT\t= \"snd_alert.mp3\";\n\tpublic static final String SND_MELD\t\t= \"snd_meld.mp3\";\n\tpublic static final String SND_BOSS\t\t= \"snd_boss.mp3\";\n\tpublic static final String SND_BLAST\t= \"snd_blast.mp3\";\n\tpublic static final String SND_PLANT\t= \"snd_plant.mp3\";\n\tpublic static final String SND_RAY\t\t= \"snd_ray.mp3\";\n\tpublic static final String SND_BEACON\t= \"snd_beacon.mp3\";\n\tpublic static final String SND_TELEPORT\t= \"snd_teleport.mp3\";\n\tpublic static final String SND_CHARMS\t= \"snd_charms.mp3\";\n\tpublic static final String SND_MASTERY\t= \"snd_mastery.mp3\";\n\tpublic static final String SND_PUFF\t\t= \"snd_puff.mp3\";\n\tpublic static final String SND_ROCKS\t= \"snd_rocks.mp3\";\n\tpublic static final String SND_BURNING\t= \"snd_burning.mp3\";\n\tpublic static final String SND_FALLING\t= \"snd_falling.mp3\";\n\tpublic static final String SND_GHOST\t= \"snd_ghost.mp3\";\n\tpublic static final String SND_SECRET\t= \"snd_secret.mp3\";\n\tpublic static final String SND_BONES\t= \"snd_bones.mp3\";\n}",
"public class Hero extends Char {\n\t\n\tprivate static final String TXT_LEAVE = \"One does not simply leave Pixel Dungeon.\";\n\t\n\tprivate static final String TXT_LEVEL_UP = \"level up!\";\n\tprivate static final String TXT_NEW_LEVEL = \n\t\t\"Welcome to level %d! Now you are healthier and more focused. \" +\n\t\t\"It's easier for you to hit enemies and dodge their attacks.\";\n\t\n\tpublic static final String TXT_YOU_NOW_HAVE\t= \"You now have %s\";\n\t\n\tprivate static final String TXT_SOMETHING_ELSE\t= \"There is something else here\";\n\tprivate static final String TXT_LOCKED_CHEST\t= \"This chest is locked and you don't have matching key\";\n\tprivate static final String TXT_LOCKED_DOOR\t\t= \"You don't have a matching key\";\n\tprivate static final String TXT_NOTICED_SMTH\t= \"You noticed something\";\n\t\n\tprivate static final String TXT_WAIT\t= \"...\";\n\tprivate static final String TXT_SEARCH\t= \"search\";\n\t\n\tpublic static final int STARTING_STR = 10;\n\t\n\tprivate static final float TIME_TO_REST\t\t= 1f;\n\tprivate static final float TIME_TO_SEARCH\t= 2f;\n\t\n\tpublic HeroClass heroClass = HeroClass.ROGUE;\n\tpublic HeroSubClass subClass = HeroSubClass.NONE;\n\t\n\tprivate int attackSkill = 10;\n\tprivate int defenseSkill = 5;\n\n\tpublic boolean ready = false;\n private boolean damageInterrupt = true;\n public HeroAction curAction = null;\n\tpublic HeroAction lastAction = null;\n\n\tprivate Char enemy;\n\t\n\tpublic Armor.Glyph killerGlyph = null;\n\t\n\tprivate Item theKey;\n\t\n\tpublic boolean restoreHealth = false;\n\n public MissileWeapon rangedWeapon = null;\n\tpublic Belongings belongings;\n\t\n\tpublic int STR;\n\tpublic boolean weakened = false;\n\t\n\tpublic float awareness;\n\t\n\tpublic int lvl = 1;\n\tpublic int exp = 0;\n\t\n\tprivate ArrayList<Mob> visibleEnemies; \n\t\n\tpublic Hero() {\n\t\tsuper();\n\t\tname = \"you\";\n\t\t\n\t\tHP = HT = 20;\n\t\tSTR = STARTING_STR;\n\t\tawareness = 0.1f;\n\t\t\n\t\tbelongings = new Belongings( this );\n\t\t\n\t\tvisibleEnemies = new ArrayList<Mob>();\n\t}\n\n\tpublic int STR() {\n int STR = this.STR;\n\n for (Buff buff : buffs(RingOfMight.Might.class)) {\n STR += ((RingOfMight.Might)buff).level;\n }\n\n\t\treturn weakened ? STR - 2 : STR;\n\t}\n\n\tprivate static final String ATTACK\t\t= \"attackSkill\";\n\tprivate static final String DEFENSE\t\t= \"defenseSkill\";\n\tprivate static final String STRENGTH\t= \"STR\";\n\tprivate static final String LEVEL\t\t= \"lvl\";\n\tprivate static final String EXPERIENCE\t= \"exp\";\n\t\n\t@Override\n\tpublic void storeInBundle( Bundle bundle ) {\n\n\t\tsuper.storeInBundle( bundle );\n\t\t\n\t\theroClass.storeInBundle( bundle );\n\t\tsubClass.storeInBundle( bundle );\n\t\t\n\t\tbundle.put( ATTACK, attackSkill );\n\t\tbundle.put( DEFENSE, defenseSkill );\n\t\t\n\t\tbundle.put( STRENGTH, STR );\n\t\t\n\t\tbundle.put( LEVEL, lvl );\n\t\tbundle.put( EXPERIENCE, exp );\n\t\t\n\t\tbelongings.storeInBundle( bundle );\n\t}\n\t\n\t@Override\n\tpublic void restoreFromBundle( Bundle bundle ) {\n\t\tsuper.restoreFromBundle( bundle );\n\t\t\n\t\theroClass = HeroClass.restoreInBundle( bundle );\n\t\tsubClass = HeroSubClass.restoreInBundle( bundle );\n\t\t\n\t\tattackSkill = bundle.getInt( ATTACK );\n\t\tdefenseSkill = bundle.getInt( DEFENSE );\n\t\t\n\t\tSTR = bundle.getInt( STRENGTH );\n\t\tupdateAwareness();\n\t\t\n\t\tlvl = bundle.getInt( LEVEL );\n\t\texp = bundle.getInt( EXPERIENCE );\n\t\t\n\t\tbelongings.restoreFromBundle( bundle );\n\t}\n\t\n\tpublic static void preview( GamesInProgress.Info info, Bundle bundle ) {\n\t\tinfo.level = bundle.getInt( LEVEL );\n\t}\n\t\n\tpublic String className() {\n\t\treturn subClass == null || subClass == HeroSubClass.NONE ? heroClass.title() : subClass.title();\n\t}\n\n\tpublic String givenName(){\n\t\treturn name.equals(\"you\") ? className() : name;\n\t}\n\t\n\tpublic void live() {\n\t\tBuff.affect( this, Regeneration.class );\t\n\t\tBuff.affect( this, Hunger.class );\n\t}\n\t\n\tpublic int tier() {\n\t\treturn belongings.armor == null ? 0 : belongings.armor.tier;\n\t}\n\n public boolean shoot( Char enemy, MissileWeapon wep ) {\n\n rangedWeapon = wep;\n boolean result = attack( enemy );\n Invisibility.dispel();\n rangedWeapon = null;\n\n return result;\n }\n\t\n\t@Override\n\tpublic int attackSkill( Char target ) {\n float accuracy = 1;\n if (rangedWeapon != null && Level.distance( pos, target.pos ) == 1) {\n accuracy *= 0.5f;\n }\n\n KindOfWeapon wep = rangedWeapon != null ? rangedWeapon : belongings.weapon;\n if (wep != null) {\n return (int)(attackSkill * accuracy * wep.acuracyFactor( this ));\n } else {\n return (int)(attackSkill * accuracy);\n }\n\t}\n\t\n\t@Override\n\tpublic int defenseSkill( Char enemy ) {\n\t\t\n\t\tint bonus = 0;\n\t\tfor (Buff buff : buffs( RingOfEvasion.Evasion.class )) {\n\t\t\tbonus += ((RingOfEvasion.Evasion)buff).effectiveLevel;\n\t\t}\n\n\t\tfloat evasion = (float)Math.pow( 1.15, bonus );\n\t\tif (paralysed) {\n\t\t\tevasion /= 2;\n\t\t}\n\t\t\n\t\tint aEnc = belongings.armor != null ? belongings.armor.STR - STR() : 9 - STR();\n\t\t\n\t\tif (aEnc > 0) {\n\t\t\treturn (int)(defenseSkill * evasion / Math.pow( 1.5, aEnc ));\n\t\t} else {\n\t\t\t\n\t\t\tif (heroClass == HeroClass.ROGUE) {\n\t\t\t\treturn (int)((defenseSkill - aEnc) * evasion);\n\t\t\t} else {\n\t\t\t\treturn (int)(defenseSkill * evasion);\n\t\t\t}\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic int dr() {\n\t\tint dr = belongings.armor != null ? Math.max( belongings.armor.DR, 0 ) : 0;\n\t\tBarkskin barkskin = buff( Barkskin.class );\n\t\tif (barkskin != null) {\n\t\t\tdr += barkskin.level();\n\t\t}\n\t\treturn dr;\n\t}\n\t\n\t@Override\n\tpublic int damageRoll() {\n KindOfWeapon wep = rangedWeapon != null ? rangedWeapon : belongings.weapon;\n\t\tint dmg;\n int bonus = 0;\n for (Buff buff : buffs( RingOfForce.Force.class )) {\n bonus += ((RingOfForce.Force)buff).level;\n }\n\n\t\tif (wep != null) {\n\t\t\tdmg = wep.damageRoll( this ) + bonus;\n\t\t} else {\n\t\t\tint str = STR() - 8;\n\t\t\tdmg = bonus == 0 ?\n\t\t\t\t\tstr > 1 ? Random.NormalIntRange( 1, str ) : 1\n\t\t\t\t\t: bonus > 0 ?\n\t\t\t\t\t\t\tstr > 0 ? Random.NormalIntRange( str/2+bonus, (int)(str*0.5f*bonus) + str*2 ) : 1\n\t\t\t\t\t\t\t: 0;\n\t\t}\n\t\tif (dmg < 0) dmg = 0;\n\t\treturn buff( Fury.class ) != null ? (int)(dmg * 1.5f) : dmg;\n\t}\n\t\n\t@Override\n\tpublic float speed() {\n\n float speed = super.speed();\n\n int hasteLevel = 0;\n for (Buff buff : buffs( RingOfHaste.Haste.class )) {\n hasteLevel += ((RingOfHaste.Haste)buff).level;\n }\n\n if (hasteLevel != 0)\n speed *= Math.pow(1.2, hasteLevel);\n\t\t\n\t\tint aEnc = belongings.armor != null ? belongings.armor.STR - STR() : 0;\n\t\tif (aEnc > 0) {\n\t\t\t\n\t\t\treturn (float)(speed * Math.pow( 1.3, -aEnc ));\n\t\t\t\n\t\t} else {\n\n\t\t\treturn ((HeroSprite)sprite).sprint( subClass == HeroSubClass.FREERUNNER && !isStarving() ) ?\n\t\t\t\t\tinvisible > 0 ?\n\t\t\t\t\t\t\t4f * speed :\n\t\t\t\t\t\t\t1.5f * speed :\n\t\t\t\t\tspeed;\n\t\t\t\n\t\t}\n\t}\n\t\n\tpublic float attackDelay() {\n KindOfWeapon wep = rangedWeapon != null ? rangedWeapon : belongings.weapon;\n\t\tif (wep != null) {\n\t\t\t\n\t\t\treturn wep.speedFactor( this );\n\t\t\t\t\t\t\n\t\t} else {\n //Normally putting furor speed on unarmed attacks would be unnecessary\n //But there's going to be that one guy who gets a furor+force ring combo\n //This is for that one guy, you shall get your fists of fury!\n int bonus = 0;\n for (Buff buff : buffs(RingOfFuror.Furor.class)) {\n bonus += ((RingOfFuror.Furor)buff).level;\n }\n\t\t\treturn (float)(0.25 + (1 - 0.25)*Math.pow(0.8, bonus));\n\t\t}\n\t}\n\n @Override\n public void spend( float time ) {\n TimekeepersHourglass.timeFreeze buff = buff(TimekeepersHourglass.timeFreeze.class);\n if (!(buff != null && buff.processTime(time)))\n super.spend( time );\n };\n\t\n\tpublic void spendAndNext( float time ) {\n\t\tbusy();\n\t\tspend( time );\n\t\tnext();\n\t}\n\t\n\t@Override\n\tpublic boolean act() {\n\t\t\n\t\tsuper.act();\n\t\t\n\t\tif (paralysed) {\n\t\t\t\n\t\t\tcurAction = null;\n\t\t\t\n\t\t\tspendAndNext( TICK );\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tcheckVisibleMobs();\n\n\t\t\n\t\tif (curAction == null) {\n\t\t\t\n\t\t\tif (restoreHealth) {\n\t\t\t\tif (isStarving() || HP >= HT) {\n\t\t\t\t\trestoreHealth = false;\n\t\t\t\t} else {\n\t\t\t\t\tspend( TIME_TO_REST ); next();\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tready();\n return false;\n\t\t\t\n\t\t} else {\n\t\t\t\n\t\t\trestoreHealth = false;\n\t\t\t\n\t\t\tready = false;\n\t\t\t\n\t\t\tif (curAction instanceof HeroAction.Move) {\n\t\t\t\t\n\t\t\t\treturn actMove( (HeroAction.Move)curAction );\n\t\t\t\t\n\t\t\t} else \n\t\t\tif (curAction instanceof HeroAction.Interact) {\n\n return actInteract( (HeroAction.Interact)curAction );\n\t\t\t\t\n\t\t\t} else \n\t\t\tif (curAction instanceof HeroAction.Buy) {\n\n return actBuy( (HeroAction.Buy)curAction );\n\t\t\t\t\n\t\t\t}else \n\t\t\tif (curAction instanceof HeroAction.PickUp) {\n\n return actPickUp( (HeroAction.PickUp)curAction );\n\t\t\t\t\n\t\t\t} else \n\t\t\tif (curAction instanceof HeroAction.OpenChest) {\n\n return actOpenChest( (HeroAction.OpenChest)curAction );\n\t\t\t\t\n\t\t\t} else \n\t\t\tif (curAction instanceof HeroAction.Unlock) {\n\n return actUnlock((HeroAction.Unlock) curAction);\n\t\t\t\t\n\t\t\t} else \n\t\t\tif (curAction instanceof HeroAction.Descend) {\n\n return actDescend( (HeroAction.Descend)curAction );\n\t\t\t\t\n\t\t\t} else\n\t\t\tif (curAction instanceof HeroAction.Ascend) {\n\n return actAscend( (HeroAction.Ascend)curAction );\n\t\t\t\t\n\t\t\t} else\n\t\t\tif (curAction instanceof HeroAction.Attack) {\n\n return actAttack( (HeroAction.Attack)curAction );\n\t\t\t\t\n\t\t\t} else\n\t\t\tif (curAction instanceof HeroAction.Cook) {\n\n return actCook( (HeroAction.Cook)curAction );\n\t\t\t\t\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn false;\n\t}\n\t\n\tpublic void busy() {\n\t\tready = false;\n\t}\n\t\n\tprivate void ready() {\n\t\tsprite.idle();\n\t\tcurAction = null;\n damageInterrupt = true;\n\t\tready = true;\n\n AttackIndicator.updateState();\n\t\t\n\t\tGameScene.ready();\n\t}\n\t\n\tpublic void interrupt() {\n\t\tif (curAction != null && curAction.dst != pos) {\n\t\t\tlastAction = curAction;\n\t\t}\n\t\tcurAction = null;\n\t}\n\t\n\tpublic void resume() {\n\t\tcurAction = lastAction;\n\t\tlastAction = null;\n damageInterrupt = false;\n\t\tact();\n\t}\n\t\n\tprivate boolean actMove( HeroAction.Move action ) {\n\n\t\tif (getCloser( action.dst )) {\n\n return true;\n\n\t\t} else {\n\t\t\tif (Dungeon.level.map[pos] == Terrain.SIGN) {\n\t\t\t\tGameScene.show( new WndMessage( Dungeon.tip() ) );\n\t\t\t}\n\t\t\tready();\n return false;\n\t\t}\n\t}\n\t\n\tprivate boolean actInteract( HeroAction.Interact action ) {\n\t\t\n\t\tNPC npc = action.npc;\n\n\t\tif (Level.adjacent( pos, npc.pos )) {\n\t\t\t\n\t\t\tready();\n\t\t\tsprite.turnTo( pos, npc.pos );\n\t\t\tnpc.interact();\n return false;\n\t\t\t\n\t\t} else {\n\t\t\t\n\t\t\tif (Level.fieldOfView[npc.pos] && getCloser( npc.pos )) {\n\n return true;\n\n\t\t\t} else {\n\t\t\t\tready();\n return false;\n\t\t\t}\n\t\t\t\n\t\t}\n\t}\n\t\n\tprivate boolean actBuy( HeroAction.Buy action ) {\n\t\tint dst = action.dst;\n\t\tif (pos == dst || Level.adjacent( pos, dst )) {\n\n\t\t\tready();\n\t\t\t\n\t\t\tHeap heap = Dungeon.level.heaps.get( dst );\n\t\t\tif (heap != null && heap.type == Type.FOR_SALE && heap.size() == 1) {\n\t\t\t\tGameScene.show( new WndTradeItem( heap, true ) );\n\t\t\t}\n\n return false;\n\n\t\t} else if (getCloser( dst )) {\n\n return true;\n\n\t\t} else {\n\t\t\tready();\n return false;\n\t\t}\n\t}\n\n\tprivate boolean actCook( HeroAction.Cook action ) {\n\t\tint dst = action.dst;\n\t\tif (Dungeon.visible[dst]) {\n\n\t\t\tready();\n\t\t\tAlchemyPot.operate( this, dst );\n return false;\n\n\t\t} else if (getCloser( dst )) {\n\n return true;\n\n\t\t} else {\n\t\t\tready();\n return false;\n\t\t}\n\t}\n\n\tprivate boolean actPickUp( HeroAction.PickUp action ) {\n\t\tint dst = action.dst;\n\t\tif (pos == dst) {\n\t\t\t\n\t\t\tHeap heap = Dungeon.level.heaps.get( pos );\n\t\t\tif (heap != null) {\t\t\t\t\n\t\t\t\tItem item = heap.pickUp();\n\t\t\t\tif (item.doPickUp( this )) {\n\t\t\t\t\t\n\t\t\t\t\tif (item instanceof Dewdrop\n || item instanceof TimekeepersHourglass.sandBag\n || item instanceof DriedRose.Petal) {\n\t\t\t\t\t\t\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\tif ((item instanceof ScrollOfUpgrade && ((ScrollOfUpgrade)item).isKnown()) ||\n\t\t\t\t\t\t\t(item instanceof PotionOfStrength && ((PotionOfStrength)item).isKnown())) {\n\t\t\t\t\t\t\tGLog.p( TXT_YOU_NOW_HAVE, item.name() );\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tGLog.i( TXT_YOU_NOW_HAVE, item.name() );\n\t\t\t\t\t\t}\n\n //Alright, if anyone complains about not knowing the vial doesn't revive\n //after this... I'm done, I'm just done.\n if (item instanceof DewVial) {\n GLog.w(\"Its revival power seems to have faded.\");\n }\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif (!heap.isEmpty()) {\n\t\t\t\t\t\tGLog.i( TXT_SOMETHING_ELSE );\n\t\t\t\t\t}\n\t\t\t\t\tcurAction = null;\n\t\t\t\t} else {\n\t\t\t\t\tDungeon.level.drop( item, pos ).sprite.drop();\n\t\t\t\t\tready();\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tready();\n }\n\n return false;\n\n } else if (getCloser( dst )) {\n\n return true;\n\n } else {\n ready();\n return false;\n\t\t}\n\t}\n\t\n\tprivate boolean actOpenChest( HeroAction.OpenChest action ) {\n\t\tint dst = action.dst;\n\t\tif (Level.adjacent( pos, dst ) || pos == dst) {\n\t\t\t\n\t\t\tHeap heap = Dungeon.level.heaps.get( dst );\n\t\t\tif (heap != null && \n\t\t\t\t(heap.type == Type.CHEST || heap.type == Type.TOMB || heap.type == Type.SKELETON ||\n heap.type == Type.REMAINS || heap.type == Type.LOCKED_CHEST || heap.type == Type.CRYSTAL_CHEST)) {\n\t\t\t\t\n\t\t\t\ttheKey = null;\n\t\t\t\t\n\t\t\t\tif (heap.type == Type.LOCKED_CHEST || heap.type == Type.CRYSTAL_CHEST) {\n\n\t\t\t\t\ttheKey = belongings.getKey( GoldenKey.class, Dungeon.depth );\n\t\t\t\t\t\n\t\t\t\t\tif (theKey == null) {\n\t\t\t\t\t\tGLog.w( TXT_LOCKED_CHEST );\n\t\t\t\t\t\tready();\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tswitch (heap.type) {\n\t\t\t\tcase TOMB:\n\t\t\t\t\tSample.INSTANCE.play( Assets.SND_TOMB );\n\t\t\t\t\tCamera.main.shake( 1, 0.5f );\n\t\t\t\t\tbreak;\n\t\t\t\tcase SKELETON:\n case REMAINS:\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tSample.INSTANCE.play( Assets.SND_UNLOCK );\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tspend( Key.TIME_TO_UNLOCK );\n\t\t\t\tsprite.operate( dst );\n\t\t\t\t\n\t\t\t} else {\n\t\t\t\tready();\n }\n\n return false;\n\n } else if (getCloser( dst )) {\n\n return true;\n\n } else {\n ready();\n return false;\n }\n\t}\n\t\n\tprivate boolean actUnlock( HeroAction.Unlock action ) {\n\t\tint doorCell = action.dst;\n\t\tif (Level.adjacent( pos, doorCell )) {\n\t\t\t\n\t\t\ttheKey = null;\n\t\t\tint door = Dungeon.level.map[doorCell];\n\t\t\t\n\t\t\tif (door == Terrain.LOCKED_DOOR) {\n\t\t\t\t\n\t\t\t\ttheKey = belongings.getKey( IronKey.class, Dungeon.depth );\n\t\t\t\t\n\t\t\t} else if (door == Terrain.LOCKED_EXIT) {\n\t\t\t\t\n\t\t\t\ttheKey = belongings.getKey( SkeletonKey.class, Dungeon.depth );\n\t\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\tif (theKey != null) {\n\t\t\t\t\n\t\t\t\tspend( Key.TIME_TO_UNLOCK );\n\t\t\t\tsprite.operate( doorCell );\n\t\t\t\t\n\t\t\t\tSample.INSTANCE.play( Assets.SND_UNLOCK );\n\t\t\t\t\n\t\t\t} else {\n\t\t\t\tGLog.w( TXT_LOCKED_DOOR );\n\t\t\t\tready();\n }\n\n return false;\n\n } else if (getCloser( doorCell )) {\n\n return true;\n\n } else {\n ready();\n return false;\n }\n\t}\n\t\n\tprivate boolean actDescend( HeroAction.Descend action ) {\n\t\tint stairs = action.dst;\n\t\tif (pos == stairs && pos == Dungeon.level.exit) {\n\t\t\t\n\t\t\tcurAction = null;\n\t\t\t\n\t\t\tHunger hunger = buff( Hunger.class );\n\t\t\tif (hunger != null && !hunger.isStarving()) {\n\t\t\t\thunger.satisfy( -Hunger.STARVING / 10 );\n\t\t\t}\n\n\t\t\tBuff buff = buff(TimekeepersHourglass.timeFreeze.class);\n\t\t\tif (buff != null) buff.detach();\n\n for (Mob mob : Dungeon.level.mobs.toArray( new Mob[0] ))\n if (mob instanceof DriedRose.GhostHero) mob.destroy();\n\t\t\t\n\t\t\tInterlevelScene.mode = InterlevelScene.Mode.DESCEND;\n Game.switchScene( InterlevelScene.class );\n\n return false;\n\n } else if (getCloser( stairs )) {\n\n return true;\n\n } else {\n ready();\n return false;\n }\n\t}\n\t\n\tprivate boolean actAscend( HeroAction.Ascend action ) {\n\t\tint stairs = action.dst;\n\t\tif (pos == stairs && pos == Dungeon.level.entrance) {\n\t\t\t\n\t\t\tif (Dungeon.depth == 1) {\n\t\t\t\t\n\t\t\t\tif (belongings.getItem( Amulet.class ) == null) {\n\t\t\t\t\tGameScene.show( new WndMessage( TXT_LEAVE ) );\n\t\t\t\t\tready();\n\t\t\t\t} else {\n Dungeon.win( ResultDescriptions.WIN );\n\t\t\t\t\tDungeon.deleteGame( Dungeon.hero.heroClass, true );\n\t\t\t\t\tGame.switchScene( SurfaceScene.class );\n\t\t\t\t}\n\t\t\t\t\n\t\t\t} else {\n\t\t\t\t\n\t\t\t\tcurAction = null;\n\t\t\t\t\n\t\t\t\tHunger hunger = buff( Hunger.class );\n\t\t\t\tif (hunger != null && !hunger.isStarving()) {\n\t\t\t\t\thunger.satisfy( -Hunger.STARVING / 10 );\n\t\t\t\t}\n\n\t\t\t\tBuff buff = buff(TimekeepersHourglass.timeFreeze.class);\n\t\t\t\tif (buff != null) buff.detach();\n\n for (Mob mob : Dungeon.level.mobs.toArray( new Mob[0] ))\n if (mob instanceof DriedRose.GhostHero) mob.destroy();\n\n\t\t\t\tInterlevelScene.mode = InterlevelScene.Mode.ASCEND;\n\t\t\t\tGame.switchScene( InterlevelScene.class );\n }\n\n return false;\n\n } else if (getCloser( stairs )) {\n\n return true;\n\n } else {\n ready();\n return false;\n }\n\t}\n\t\n\tprivate boolean actAttack( HeroAction.Attack action ) {\n\n\t\tenemy = action.target;\n\n\t\tif (Level.adjacent( pos, enemy.pos ) && enemy.isAlive() && !pacified) {\n\t\t\t\n\t\t\tspend( attackDelay() );\n sprite.attack( enemy.pos );\n\n return false;\n\n } else {\n\n if (Level.fieldOfView[enemy.pos] && getCloser( enemy.pos )) {\n\n return true;\n\n } else {\n ready();\n return false;\n }\n\n }\n\t}\n\t\n\tpublic void rest( boolean tillHealthy ) {\n\t\tspendAndNext( TIME_TO_REST );\n\t\tif (!tillHealthy) {\n\t\t\tsprite.showStatus( CharSprite.DEFAULT, TXT_WAIT );\n\t\t}\n\t\trestoreHealth = tillHealthy;\n\t}\n\t\n\t@Override\n\tpublic int attackProc( Char enemy, int damage ) {\n KindOfWeapon wep = rangedWeapon != null ? rangedWeapon : belongings.weapon;\n\n\t\tif (wep != null) wep.proc( this, enemy, damage );\n\t\t\t\n\t\tswitch (subClass) {\n\t\tcase GLADIATOR:\n\t\t\tif (wep instanceof MeleeWeapon || wep == null) {\n\t\t\t\tdamage += Buff.affect( this, Combo.class ).hit( enemy, damage );\n\t\t\t}\n\t\t\tbreak;\n\t\tcase BATTLEMAGE:\n\t\t\tif (wep instanceof Wand) {\n\t\t\t\tWand wand = (Wand)wep;\n\t\t\t\tif (wand.curCharges < wand.maxCharges && damage > 0) {\n\n\t\t\t\t\twand.curCharges++;\n\t\t\t\t\tif (Dungeon.quickslot.contains(wand)) {\n\t\t\t\t\t\tQuickSlotButton.refresh();\n\t\t\t\t\t}\n\n\t\t\t\t\tScrollOfRecharging.charge( this );\n\t\t\t\t}\n\t\t\t\tdamage += wand.curCharges;\n\t\t\t}\n\t\tcase SNIPER:\n\t\t\tif (rangedWeapon != null) {\n\t\t\t\tBuff.prolong( enemy, SnipersMark.class, attackDelay() * 1.1f );\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t}\n\n\t\t\n\t\treturn damage;\n\t}\n\t\n\t@Override\n\tpublic int defenseProc( Char enemy, int damage ) {\n\t\t\n\t\tCapeOfThorns.Thorns thorns = buff( CapeOfThorns.Thorns.class );\n\t\tif (thorns != null) {\n\t\t\tdamage = thorns.proc(damage, enemy);\n\t\t}\n\t\t\n\t\tEarthroot.Armor armor = buff( Earthroot.Armor.class );\n\t\tif (armor != null) {\n\t\t\tdamage = armor.absorb( damage );\n\t\t}\n\n Sungrass.Health health = buff( Sungrass.Health.class );\n if (health != null) {\n health.absorb( damage );\n }\n\t\t\n\t\tif (belongings.armor != null) {\n\t\t\tdamage = belongings.armor.proc( enemy, this, damage );\n\t\t}\n\t\t\n\t\treturn damage;\n\t}\n\t\n\t@Override\n\tpublic void damage( int dmg, Object src ) {\n\t\tif (buff(TimekeepersHourglass.timeStasis.class) != null)\n\t\t\treturn;\n\n\t\trestoreHealth = false;\n\n\t\tif (!(src instanceof Hunger || src instanceof Viscosity.DeferedDamage) && damageInterrupt)\n \tinterrupt();\n\n if (this.buff(Drowsy.class) != null){\n Buff.detach(this, Drowsy.class);\n GLog.w(\"The pain helps you resist the urge to sleep.\");\n }\n\n int tenacity = 0;\n for (Buff buff : buffs(RingOfTenacity.Tenacity.class)) {\n tenacity += ((RingOfTenacity.Tenacity)buff).level;\n }\n if (tenacity != 0) //(HT - HP)/HT = heroes current % missing health.\n dmg = (int)Math.ceil((float)dmg * Math.pow(0.9, tenacity*((float)(HT - HP)/HT)));\n\n\t\tsuper.damage( dmg, src );\n\t\t\n\t\tif (subClass == HeroSubClass.BERSERKER && 0 < HP && HP <= HT * Fury.LEVEL) {\n\t\t\tBuff.affect( this, Fury.class );\n\t\t}\n\t}\n\t\n\tprivate void checkVisibleMobs() {\n\t\tArrayList<Mob> visible = new ArrayList<Mob>();\n\n\t\tboolean newMob = false;\n\t\t\n\t\tfor (Mob m : Dungeon.level.mobs) {\n\t\t\tif (Level.fieldOfView[ m.pos ] && m.hostile) {\n\t\t\t\tvisible.add( m );\n\t\t\t\tif (!visibleEnemies.contains( m )) {\n\t\t\t\t\tnewMob = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (newMob) {\n\t\t\tinterrupt();\n\t\t\trestoreHealth = false;\n\t\t}\n\t\t\n\t\tvisibleEnemies = visible;\n\t}\n\t\n\tpublic int visibleEnemies() {\n\t\treturn visibleEnemies.size();\n\t}\n\t\n\tpublic Mob visibleEnemy( int index ) {\n\t\treturn visibleEnemies.get(index % visibleEnemies.size());\n\t}\n\t\n\tprivate boolean getCloser( final int target ) {\n\t\t\n\t\tif (rooted) {\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tint step = -1;\n\t\t\n\t\tif (Level.adjacent( pos, target )) {\n\t\t\t\n\t\t\tif (Actor.findChar( target ) == null) {\n\t\t\t\tif (Level.pit[target] && !flying && !Chasm.jumpConfirmed) {\n\t\t\t\t\tChasm.heroJump( this );\n\t\t\t\t\tinterrupt();\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tif (Level.passable[target] || Level.avoid[target]) {\n\t\t\t\t\tstep = target;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t} else {\n\t\t\n\t\t\tint len = Level.LENGTH;\n\t\t\tboolean[] p = Level.passable;\n\t\t\tboolean[] v = Dungeon.level.visited;\n\t\t\tboolean[] m = Dungeon.level.mapped;\n\t\t\tboolean[] passable = new boolean[len];\n\t\t\tfor (int i=0; i < len; i++) {\n\t\t\t\tpassable[i] = p[i] && (v[i] || m[i]);\n\t\t\t}\n\t\t\t\n\t\t\tstep = Dungeon.findPath( this, pos, target, passable, Level.fieldOfView );\n\t\t}\n\t\t\n\t\tif (step != -1) {\n\n int oldPos = pos;\n move(step);\n sprite.move(oldPos, pos);\n\t\t\tspend( 1 / speed() );\n\t\t\t\n\t\t\treturn true;\n\n\t\t} else {\n\n\t\t\treturn false;\n\t\t\t\n\t\t}\n\n\t}\n\t\n\tpublic boolean handle( int cell ) {\n\t\t\n\t\tif (cell == -1) {\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tChar ch;\n\t\tHeap heap;\n\t\t\n\t\tif (Dungeon.level.map[cell] == Terrain.ALCHEMY && cell != pos) {\n\t\t\t\n\t\t\tcurAction = new HeroAction.Cook( cell );\n\t\t\t\n\t\t} else\n\t\tif (Level.fieldOfView[cell] && (ch = Actor.findChar( cell )) instanceof Mob) {\n\t\t\t\n\t\t\tif (ch instanceof NPC) {\n\t\t\t\tcurAction = new HeroAction.Interact( (NPC)ch );\n\t\t\t} else {\n\t\t\t\tcurAction = new HeroAction.Attack( ch );\n\t\t\t}\n\t\t\t\n\t\t} else if ((heap = Dungeon.level.heaps.get( cell )) != null) {\n\n\t\t\tswitch (heap.type) {\n\t\t\tcase HEAP:\n\t\t\t\tcurAction = new HeroAction.PickUp( cell );\n\t\t\t\tbreak;\n\t\t\tcase FOR_SALE:\n\t\t\t\tcurAction = heap.size() == 1 && heap.peek().price() > 0 ? \n\t\t\t\t\tnew HeroAction.Buy( cell ) : \n\t\t\t\t\tnew HeroAction.PickUp( cell );\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tcurAction = new HeroAction.OpenChest( cell );\n\t\t\t}\n\t\t\t\n\t\t} else if (Dungeon.level.map[cell] == Terrain.LOCKED_DOOR || Dungeon.level.map[cell] == Terrain.LOCKED_EXIT) {\n\t\t\t\n\t\t\tcurAction = new HeroAction.Unlock( cell );\n\t\t\t\n\t\t} else if (cell == Dungeon.level.exit) {\n\t\t\t\n\t\t\tcurAction = new HeroAction.Descend( cell );\n\t\t\t\n\t\t} else if (cell == Dungeon.level.entrance) {\n\t\t\t\n\t\t\tcurAction = new HeroAction.Ascend( cell );\n\t\t\t\n\t\t} else {\n\t\t\t\n\t\t\tcurAction = new HeroAction.Move( cell );\n\t\t\tlastAction = null;\n\t\t\t\n\t\t}\n\n\t\treturn act();\n\t}\n\t\n\tpublic void earnExp( int exp ) {\n\t\t\n\t\tthis.exp += exp;\n\t\t\n\t\tboolean levelUp = false;\n\t\twhile (this.exp >= maxExp()) {\n\t\t\tthis.exp -= maxExp();\n\t\t\tlvl++;\n\t\t\t\n\t\t\tHT += 5;\n\t\t\tHP += 5;\t\t\t\n\t\t\tattackSkill++;\n\t\t\tdefenseSkill++;\n\t\t\t\n\t\t\tif (lvl < 10) {\n\t\t\t\tupdateAwareness();\n\t\t\t}\n\t\t\t\n\t\t\tlevelUp = true;\n\t\t}\n\t\t\n\t\tif (levelUp) {\n\t\t\t\n\t\t\tGLog.p( TXT_NEW_LEVEL, lvl );\n\t\t\tsprite.showStatus( CharSprite.POSITIVE, TXT_LEVEL_UP );\n\t\t\tSample.INSTANCE.play( Assets.SND_LEVELUP );\n\t\t\t\n\t\t\tBadges.validateLevelReached();\n\t\t}\n\t\t\n\t\tif (subClass == HeroSubClass.WARLOCK) {\n\t\t\t\n\t\t\tint value = Math.min( HT - HP, 1 + (Dungeon.depth - 1) / 5 );\n\t\t\tif (value > 0) {\n\t\t\t\tHP += value;\n\t\t\t\tsprite.emitter().burst( Speck.factory( Speck.HEALING ), 1 );\n\t\t\t}\n\t\t\t\n\t\t\t((Hunger)buff( Hunger.class )).satisfy( 10 );\n\t\t}\n\t}\n\t\n\tpublic int maxExp() {\n\t\treturn 5 + lvl * 5;\n\t}\n\t\n\tvoid updateAwareness() {\n\t\tawareness = (float)(1 - Math.pow( \n\t\t\t(heroClass == HeroClass.ROGUE ? 0.85 : 0.90), \n\t\t\t(1 + Math.min( lvl, 9 )) * 0.5 \n\t\t));\n\t}\n\t\n\tpublic boolean isStarving() {\n\t\treturn buff(Hunger.class) != null && ((Hunger)buff( Hunger.class )).isStarving();\n\t}\n\t\n\t@Override\n\tpublic void add( Buff buff ) {\n\n\t\tif (buff(TimekeepersHourglass.timeStasis.class) != null)\n\t\t\treturn;\n\n\t\tsuper.add( buff );\n\t\t\n\t\tif (sprite != null) {\n\t\t\tif (buff instanceof Burning) {\n\t\t\t\tGLog.w( \"You catch fire!\" );\n\t\t\t\tinterrupt();\n\t\t\t} else if (buff instanceof Paralysis) {\n\t\t\t\tGLog.w( \"You are paralysed!\" );\n\t\t\t\tinterrupt();\n\t\t\t} else if (buff instanceof Poison) {\n\t\t\t\tGLog.w( \"You are poisoned!\" );\n\t\t\t\tinterrupt();\n\t\t\t} else if (buff instanceof Ooze) {\n\t\t\t\tGLog.w( \"Caustic ooze eats your flesh. Wash it away!\" );\n\t\t\t} else if (buff instanceof Roots) {\n\t\t\t\tGLog.w( \"You can't move!\" );\n\t\t\t} else if (buff instanceof Weakness) {\n\t\t\t\tGLog.w( \"You feel weakened!\" );\n\t\t\t} else if (buff instanceof Blindness) {\n\t\t\t\tGLog.w( \"You are blinded!\" );\n\t\t\t} else if (buff instanceof Fury) {\n\t\t\t\tGLog.w( \"You become furious!\" );\n\t\t\t\tsprite.showStatus( CharSprite.POSITIVE, \"furious\" );\n\t\t\t} else if (buff instanceof Charm) {\n\t\t\t\tGLog.w( \"You are charmed!\" );\n\t\t\t} else if (buff instanceof Cripple) {\n\t\t\t\tGLog.w( \"You are crippled!\" );\n\t\t\t} else if (buff instanceof Bleeding) {\n\t\t\t\tGLog.w( \"You are bleeding!\" );\n\t\t\t} else if (buff instanceof RingOfMight.Might){\n if (((RingOfMight.Might)buff).level > 0) {\n HT += ((RingOfMight.Might) buff).level * 5;\n }\n } else if (buff instanceof Vertigo) {\n GLog.w(\"Everything is spinning around you!\");\n interrupt();\n }\n\t\t\t\n\t\t\telse if (buff instanceof Light) {\n\t\t\t\tsprite.add( CharSprite.State.ILLUMINATED );\n\t\t\t}\n\t\t}\n\t\t\n\t\tBuffIndicator.refreshHero();\n\t}\n\t\n\t@Override\n\tpublic void remove( Buff buff ) {\n\t\tsuper.remove( buff );\n\t\t\n\t\tif (buff instanceof Light) {\n\t\t\tsprite.remove( CharSprite.State.ILLUMINATED );\n\t\t} else if (buff instanceof RingOfMight.Might){\n if (((RingOfMight.Might)buff).level > 0){\n HT -= ((RingOfMight.Might) buff).level * 5;\n HP = Math.min(HT, HP);\n }\n }\n\t\t\n\t\tBuffIndicator.refreshHero();\n\t}\n\t\n\t@Override\n\tpublic int stealth() {\n\t\tint stealth = super.stealth();\n\t\tfor (Buff buff : buffs( RingOfEvasion.Evasion.class )) {\n\t\t\tstealth += ((RingOfEvasion.Evasion)buff).effectiveLevel;\n\t\t}\n\t\treturn stealth;\n\t}\n\t\n\t@Override\n\tpublic void die( Object cause ) {\n\t\t\n\t\tcurAction = null;\n\n Ankh ankh = null;\n\n //look for ankhs in player inventory, prioritize ones which are blessed.\n for (Item item : belongings){\n if (item instanceof Ankh) {\n if (ankh == null || ((Ankh) item).isBlessed()) {\n ankh = (Ankh) item;\n }\n }\n }\n\n if (ankh != null && ankh.isBlessed()) {\n this.HP = HT;\n\n new Flare(8, 32).color(0xFFFF66, true).show(sprite, 2f);\n CellEmitter.get(this.pos).start(Speck.factory(Speck.LIGHT), 0.2f, 3);\n\n ankh.detach(belongings.backpack);\n\n Sample.INSTANCE.play( Assets.SND_TELEPORT );\n GLog.w( ankh.TXT_REVIVE );\n Statistics.ankhsUsed++;\n\n return;\n }\n\t\t\n\t\tActor.fixTime();\n\t\tsuper.die( cause );\n\n\t\tif (ankh == null) {\n\t\t\t\n\t\t\treallyDie( cause );\n\t\t\t\n\t\t} else {\n\t\t\t\n\t\t\tDungeon.deleteGame( Dungeon.hero.heroClass, false );\n\t\t\tGameScene.show( new WndResurrect( ankh, cause ) );\n\t\t\t\n\t\t}\n\t}\n\t\n\tpublic static void reallyDie( Object cause ) {\n\t\t\n\t\tint length = Level.LENGTH;\n\t\tint[] map = Dungeon.level.map;\n\t\tboolean[] visited = Dungeon.level.visited;\n\t\tboolean[] discoverable = Level.discoverable;\n\t\t\n\t\tfor (int i=0; i < length; i++) {\n\t\t\t\n\t\t\tint terr = map[i];\n\t\t\t\n\t\t\tif (discoverable[i]) {\n\t\t\t\t\n\t\t\t\tvisited[i] = true;\n\t\t\t\tif ((Terrain.flags[terr] & Terrain.SECRET) != 0) {\n\t\t\t\t\tLevel.set( i, Terrain.discover( terr ) );\t\t\t\t\t\t\n\t\t\t\t\tGameScene.updateMap( i );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tBones.leave();\n\t\t\n\t\tDungeon.observe();\n\t\t\t\t\n\t\tDungeon.hero.belongings.identify();\n\t\t\n\t\tGameScene.gameOver();\n\t\t\n\t\tif (cause instanceof Hero.Doom) {\n\t\t\t((Hero.Doom)cause).onDeath();\n\t\t}\n\t\t\n\t\tDungeon.deleteGame( Dungeon.hero.heroClass, true );\n\t}\n\t\n\t@Override\n\tpublic void move( int step ) {\n\t\tsuper.move( step );\n\t\t\n\t\tif (!flying) {\n\t\t\t\n\t\t\tif (Level.water[pos]) {\n\t\t\t\tSample.INSTANCE.play( Assets.SND_WATER, 1, 1, Random.Float( 0.8f, 1.25f ) );\n\t\t\t} else {\n\t\t\t\tSample.INSTANCE.play( Assets.SND_STEP );\n\t\t\t}\n\t\t\tDungeon.level.press(pos, this);\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic void onMotionComplete() {\n\t\tDungeon.observe();\n\t\tsearch( false );\n\t\t\t\n\t\tsuper.onMotionComplete();\n\t}\n\t\n\t@Override\n\tpublic void onAttackComplete() {\n\t\t\n\t\tAttackIndicator.target(enemy);\n\t\t\n\t\tattack( enemy );\n\t\tcurAction = null;\n\t\t\n\t\tInvisibility.dispel();\n\n\t\tsuper.onAttackComplete();\n\t}\n\t\n\t@Override\n\tpublic void onOperateComplete() {\n\t\t\n\t\tif (curAction instanceof HeroAction.Unlock) {\n\t\t\t\n\t\t\tif (theKey != null) {\n\t\t\t\ttheKey.detach( belongings.backpack );\n\t\t\t\ttheKey = null;\n\t\t\t}\n\t\t\t\n\t\t\tint doorCell = ((HeroAction.Unlock)curAction).dst;\n\t\t\tint door = Dungeon.level.map[doorCell];\n\t\t\t\n\t\t\tLevel.set( doorCell, door == Terrain.LOCKED_DOOR ? Terrain.DOOR : Terrain.UNLOCKED_EXIT );\n\t\t\tGameScene.updateMap( doorCell );\n\t\t\t\n\t\t} else if (curAction instanceof HeroAction.OpenChest) {\n\t\t\t\n\t\t\tif (theKey != null) {\n\t\t\t\ttheKey.detach( belongings.backpack );\n\t\t\t\ttheKey = null;\n\t\t\t}\n\t\t\t\n\t\t\tHeap heap = Dungeon.level.heaps.get( ((HeroAction.OpenChest)curAction).dst ); \n\t\t\tif (heap.type == Type.SKELETON || heap.type == Type.REMAINS) {\n\t\t\t\tSample.INSTANCE.play( Assets.SND_BONES );\n\t\t\t}\n\t\t\theap.open( this );\n\t\t}\n\t\tcurAction = null;\n\n\t\tsuper.onOperateComplete();\n\t}\n\t\n\tpublic boolean search( boolean intentional ) {\n\t\t\n\t\tboolean smthFound = false;\n\n\t\tint positive = ShatteredPixelDungeon.softify() ? 1 : 0;\n\t\tint negative = 0;\n\n\t\tint distance = 1 + positive + negative;\n\n\t\tfloat level = intentional ? (2 * awareness - awareness * awareness) : awareness;\n\t\tif (distance <= 0) {\n\t\t\tlevel /= 2 - distance;\n\t\t\tdistance = 1;\n\t\t}\n\t\t\n\t\tint cx = pos % Level.WIDTH;\n\t\tint cy = pos / Level.WIDTH;\n\t\tint ax = cx - distance;\n\t\tif (ax < 0) {\n\t\t\tax = 0;\n\t\t}\n\t\tint bx = cx + distance;\n\t\tif (bx >= Level.WIDTH) {\n\t\t\tbx = Level.WIDTH - 1;\n\t\t}\n\t\tint ay = cy - distance;\n\t\tif (ay < 0) {\n\t\t\tay = 0;\n\t\t}\n\t\tint by = cy + distance;\n\t\tif (by >= Level.HEIGHT) {\n\t\t\tby = Level.HEIGHT - 1;\n\t\t}\n\n TalismanOfForesight.Foresight foresight = buff( TalismanOfForesight.Foresight.class );\n\n\t\t//cursed talisman of foresight makes unintentionally finding things impossible.\n\t\tif (foresight != null && foresight.isCursed()){\n\t\t\tlevel = -1;\n\t\t}\n\t\t\n\t\tfor (int y = ay; y <= by; y++) {\n\t\t\tfor (int x = ax, p = ax + y * Level.WIDTH; x <= bx; x++, p++) {\n\t\t\t\t\n\t\t\t\tif (Dungeon.visible[p]) {\n\t\t\t\t\t\n\t\t\t\t\tif (intentional) {\n\t\t\t\t\t\tsprite.parent.addToBack( new CheckedCell( p ) );\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif (Level.secret[p] && (intentional || Random.Float() < level)) {\n\t\t\t\t\t\t\n\t\t\t\t\t\tint oldValue = Dungeon.level.map[p];\n\t\t\t\t\t\t\n\t\t\t\t\t\tGameScene.discoverTile( p, oldValue );\n\t\t\t\t\t\t\n\t\t\t\t\t\tLevel.set( p, Terrain.discover( oldValue ) );\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tGameScene.updateMap( p );\n\t\t\t\t\t\t\n\t\t\t\t\t\tScrollOfMagicMapping.discover( p );\n\t\t\t\t\t\t\n\t\t\t\t\t\tsmthFound = true;\n\n if (foresight != null && !foresight.isCursed())\n foresight.charge();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\n\t\tif (intentional) {\n\t\t\tsprite.showStatus( CharSprite.DEFAULT, TXT_SEARCH );\n\t\t\tsprite.operate( pos );\n\t\t\tif (foresight != null && foresight.isCursed()){\n\t\t\t\tGLog.n(\"You can't concentrate, searching takes a while.\");\n\t\t\t\tspendAndNext(TIME_TO_SEARCH * 3);\n\t\t\t} else {\n\t\t\t\tspendAndNext(TIME_TO_SEARCH);\n\t\t\t}\n\t\t\t\n\t\t}\n\t\t\n\t\tif (smthFound) {\n\t\t\tGLog.w( TXT_NOTICED_SMTH );\n\t\t\tSample.INSTANCE.play( Assets.SND_SECRET );\n\t\t\tinterrupt();\n\t\t}\n\t\t\n\t\treturn smthFound;\n\t}\n\t\n\tpublic void resurrect( int resetLevel ) {\n\t\t\n\t\tHP = HT;\n\t\tDungeon.gold = 0;\n\t\texp = 0;\n\t\t\n\t\tbelongings.resurrect( resetLevel );\n\n\t\tlive();\n\t}\n\t\n\t@Override\n\tpublic HashSet<Class<?>> resistances() {\n\t\tRingOfElements.Resistance r = buff( RingOfElements.Resistance.class );\n\t\treturn r == null ? super.resistances() : r.resistances();\n\t}\n\t\n\t@Override\n\tpublic HashSet<Class<?>> immunities() {\n HashSet<Class<?>> immunities = new HashSet<Class<?>>();\n\t\tfor (Buff buff : buffs()){\n for (Class<?> immunity : buff.immunities)\n immunities.add(immunity);\n }\n\t\treturn immunities;\n\t}\n\t\n\tpublic static interface Doom {\n\t\tpublic void onDeath();\n\t}\n}",
"public class Gold extends Item {\n\n\tprivate static final String TXT_COLLECT\t= \"Collect gold coins to spend them later in a shop.\";\n\tprivate static final String TXT_INFO\t= \"A pile of %d gold coins. \" + TXT_COLLECT;\n\tprivate static final String TXT_INFO_1\t= \"One gold coin. \" + TXT_COLLECT;\n\tprivate static final String TXT_VALUE\t= \"%+d\";\n\t\n\t{\n\t\tname = \"gold\";\n\t\timage = ItemSpriteSheet.GOLD;\n\t\tstackable = true;\n\t}\n\t\n\tpublic Gold() {\n\t\tthis( 1 );\n\t}\n\t\n\tpublic Gold( int value ) {\n\t\tthis.quantity = value;\n\t}\n\t\n\t@Override\n\tpublic ArrayList<String> actions( Hero hero ) {\n\t\treturn new ArrayList<String>();\n\t}\n\t\n\t@Override\n\tpublic boolean doPickUp( Hero hero ) {\n\t\t\n\t\tDungeon.gold += quantity;\n\t\tStatistics.goldCollected += quantity;\n\t\tBadges.validateGoldCollected();\n\n MasterThievesArmband.Thievery thievery = hero.buff(MasterThievesArmband.Thievery.class);\n\t\tif (thievery != null)\n thievery.collect(quantity);\n\n\t\tGameScene.pickUp( this );\n\t\thero.sprite.showStatus( CharSprite.NEUTRAL, TXT_VALUE, quantity );\n\t\thero.spendAndNext( TIME_TO_PICK_UP );\n\t\t\n\t\tSample.INSTANCE.play( Assets.SND_GOLD, 1, 1, Random.Float( 0.9f, 1.1f ) );\n\t\t\n\t\treturn true;\n\t}\n\t\n\t@Override\n\tpublic boolean isUpgradable() {\n\t\treturn false;\n\t}\n\t\n\t@Override\n\tpublic boolean isIdentified() {\n\t\treturn true;\n\t}\n\t\n\t@Override\n\tpublic String info() {\n\t\tswitch (quantity) {\n\t\tcase 0:\n\t\t\treturn TXT_COLLECT;\n\t\tcase 1:\n\t\t\treturn TXT_INFO_1;\n\t\tdefault:\n\t\t\treturn Utils.format( TXT_INFO, quantity );\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic Item random() {\n\t\tquantity = Random.Int( 20 + Dungeon.depth * 10, 40 + Dungeon.depth * 20 );\n\t\treturn this;\n\t}\n\t\n\tprivate static final String VALUE\t= \"value\";\n\t\n\t@Override\n\tpublic void storeInBundle( Bundle bundle ) {\n\t\tsuper.storeInBundle( bundle );\n\t\tbundle.put( VALUE, quantity );\n\t}\n\t\n\t@Override\n\tpublic void restoreFromBundle( Bundle bundle ) {\n\t\tsuper.restoreFromBundle(bundle);\n\t\tquantity = bundle.getInt( VALUE );\n\t}\n}",
"public class Bag extends Item implements Iterable<Item> {\n\n\tpublic static final String AC_OPEN\t= \"OPEN\";\n\t\n\t{\n\t\timage = 11;\n\t\t\n\t\tdefaultAction = AC_OPEN;\n\t}\n\t\n\tpublic Char owner;\n\t\n\tpublic ArrayList<Item> items = new ArrayList<Item>();\t\n\t\n\tpublic int size = 1;\n\t\n\t@Override\n\tpublic ArrayList<String> actions( Hero hero ) {\n\t\tArrayList<String> actions = super.actions( hero );\n\t\treturn actions;\n\t}\n\t\n\t@Override\n\tpublic void execute( Hero hero, String action ) {\n\t\tif (action.equals( AC_OPEN )) {\n\t\t\t\n\t\t\tGameScene.show( new WndBag( this, null, WndBag.Mode.ALL, null ) );\n\t\t\t\n\t\t} else {\n\t\t\n\t\t\tsuper.execute( hero, action );\n\t\t\t\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic boolean collect( Bag container ) {\n\t\tif (super.collect( container )) {\t\n\t\t\t\n\t\t\towner = container.owner;\n\t\t\t\n\t\t\tfor (Item item : container.items.toArray( new Item[0] )) {\n\t\t\t\tif (grab( item )) {\n\t\t\t\t\titem.detachAll( container );\n\t\t\t\t\titem.collect( this );\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tBadges.validateAllBagsBought( this );\n\t\t\t\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n @Override\n public void onDetach( ) {\n this.owner = null;\n }\n\t\n\t@Override\n\tpublic boolean isUpgradable() {\n\t\treturn false;\n\t}\n\t\n\t@Override\n\tpublic boolean isIdentified() {\n\t\treturn true;\n\t}\n\t\n\tpublic void clear() {\n\t\titems.clear();\n\t}\n\t\n\tprivate static final String ITEMS\t= \"inventory\";\n\t\n\t@Override\n\tpublic void storeInBundle( Bundle bundle ) {\n\t\tsuper.storeInBundle( bundle );\n\t\tbundle.put( ITEMS, items );\n\t}\n\t\n\t@Override\n\tpublic void restoreFromBundle( Bundle bundle ) {\n\t\tsuper.restoreFromBundle( bundle );\n\t\tfor (Bundlable item : bundle.getCollection( ITEMS )) {\n\t\t\tif (item != null) ((Item)item).collect( this );\n\t\t};\n\t}\n\t\n\tpublic boolean contains( Item item ) {\n\t\tfor (Item i : items) {\n\t\t\tif (i == item) {\n\t\t\t\treturn true;\n\t\t\t} else if (i instanceof Bag && ((Bag)i).contains( item )) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tpublic boolean grab( Item item ) {\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic Iterator<Item> iterator() {\n\t\treturn new ItemIterator();\n\t}\n\t\n\tprivate class ItemIterator implements Iterator<Item> {\n\n\t\tprivate int index = 0;\n\t\tprivate Iterator<Item> nested = null;\n\t\t\n\t\t@Override\n\t\tpublic boolean hasNext() {\n\t\t\tif (nested != null) {\n\t\t\t\treturn nested.hasNext() || index < items.size();\n\t\t\t} else {\n\t\t\t\treturn index < items.size();\n\t\t\t}\n\t\t}\n\n\t\t@Override\n\t\tpublic Item next() {\n\t\t\tif (nested != null && nested.hasNext()) {\n\t\t\t\t\n\t\t\t\treturn nested.next();\n\t\t\t\t\n\t\t\t} else {\n\t\t\t\t\n\t\t\t\tnested = null;\n\t\t\t\t\n\t\t\t\tItem item = items.get( index++ );\n\t\t\t\tif (item instanceof Bag) {\n\t\t\t\t\tnested = ((Bag)item).iterator();\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\treturn item;\n\t\t\t}\n\t\t}\n\n\t\t@Override\n\t\tpublic void remove() {\n\t\t\tif (nested != null) {\n\t\t\t\tnested.remove();\n\t\t\t} else {\n\t\t\t\titems.remove( index );\n\t\t\t}\n\t\t}\t\n\t}\n}",
"public class MeleeWeapon extends Weapon {\n\t\n\tprivate int tier;\n\t\n\tpublic MeleeWeapon( int tier, float acu, float dly ) {\n\t\tsuper();\n\t\t\n\t\tthis.tier = tier;\n\t\t\n\t\tACU = acu;\n\t\tDLY = dly;\n\t\t\n\t\tSTR = typicalSTR();\n\t\t\n\t\tMIN = min();\n\t\tMAX = max();\n\t}\n\t\n\tprivate int min() {\n\t\treturn tier;\n\t}\n\t\n\tprivate int max() {\n\t\treturn (int)((tier * tier - tier + 10) / ACU * DLY);\n\t}\n\t\n\t@Override\n\tpublic Item upgrade() {\n\t\treturn upgrade( false );\n\t}\n\t\n\tpublic Item upgrade( boolean enchant ) {\n\t\tSTR--;\t\t\n\t\tMIN++;\n\t\tMAX += tier;\n\t\t\n\t\treturn super.upgrade( enchant );\n\t}\n\t\n\tpublic Item safeUpgrade() {\n\t\treturn upgrade( enchantment != null );\n\t}\n\t\n\t@Override\n\tpublic Item degrade() {\t\t\n\t\tSTR++;\n\t\tMIN--;\n\t\tMAX -= tier;\n\t\treturn super.degrade();\n\t}\n\t\n\tpublic int typicalSTR() {\n\t\treturn 8 + tier * 2;\n\t}\n\t\n\t@Override\n\tpublic String info() {\n\t\t\n\t\tfinal String p = \"\\n\\n\";\n\t\t\n\t\tStringBuilder info = new StringBuilder( desc() );\n\t\t\n\t\tString quality = levelKnown && level != 0 ? (level > 0 ? \"upgraded\" : \"degraded\") : \"\";\n\t\tinfo.append( p );\n\t\tinfo.append( \"This \" + name + \" is \" + Utils.indefinite( quality ) );\n\t\tinfo.append( \" tier-\" + tier + \" melee weapon. \" );\n\t\t\n\t\tif (levelKnown) {\n\t\t\tinfo.append( \"Its average damage is \" +\n Math.round((MIN + (MAX - MIN) / 2)*(imbue == Imbue.LIGHT ? 0.75f : (imbue == Imbue.HEAVY ? 1.5f : 1)))\n + \" points per hit. \" );\n\t\t} else {\n\t\t\tinfo.append( \n\t\t\t\t\"Its typical average damage is \" + (min() + (max() - min()) / 2) + \" points per hit \" +\n\t\t\t\t\"and usually it requires \" + typicalSTR() + \" points of strength. \" );\n\t\t\tif (typicalSTR() > Dungeon.hero.STR()) {\n\t\t\t\tinfo.append( \"Probably this weapon is too heavy for you. \" );\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (DLY != 1f) {\n\t\t\tinfo.append( \"This is a rather \" + (DLY < 1f ? \"fast\" : \"slow\") );\n\t\t\tif (ACU != 1f) {\n\t\t\t\tif ((ACU > 1f) == (DLY < 1f)) {\n\t\t\t\t\tinfo.append( \" and \");\n\t\t\t\t} else {\n\t\t\t\t\tinfo.append( \" but \");\n\t\t\t\t}\n\t\t\t\tinfo.append( ACU > 1f ? \"accurate\" : \"inaccurate\" );\n\t\t\t}\n\t\t\tinfo.append( \" weapon. \");\n\t\t} else if (ACU != 1f) {\n\t\t\tinfo.append( \"This is a rather \" + (ACU > 1f ? \"accurate\" : \"inaccurate\") + \" weapon. \" );\n }\n switch (imbue) {\n case LIGHT:\n info.append( \"It was balanced to be lighter. \" );\n break;\n case HEAVY:\n info.append( \"It was balanced to be heavier. \" );\n break;\n case NONE:\n }\n\t\t\n\t\tif (enchantment != null) {\n\t\t\tinfo.append( \"It is enchanted.\" );\n\t\t}\n\t\t\n\t\tif (levelKnown && Dungeon.hero.belongings.backpack.items.contains( this )) {\n\t\t\tif (STR > Dungeon.hero.STR()) {\n\t\t\t\tinfo.append( p );\n\t\t\t\tinfo.append( \n\t\t\t\t\t\"Because of your inadequate strength the accuracy and speed \" +\n\t\t\t\t\t\"of your attack with this \" + name + \" is decreased.\" );\n\t\t\t}\n\t\t\tif (STR < Dungeon.hero.STR()) {\n\t\t\t\tinfo.append( p );\n\t\t\t\tinfo.append( \n\t\t\t\t\t\"Because of your excess strength the damage \" +\n\t\t\t\t\t\"of your attack with this \" + name + \" is increased.\" );\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (isEquipped( Dungeon.hero )) {\n\t\t\tinfo.append( p );\n\t\t\tinfo.append( \"You hold the \" + name + \" at the ready\" + \n\t\t\t\t(cursed ? \", and because it is cursed, you are powerless to let go.\" : \".\") ); \n\t\t} else {\n\t\t\tif (cursedKnown && cursed) {\n\t\t\t\tinfo.append( p );\n\t\t\t\tinfo.append( \"You can feel a malevolent magic lurking within \" + name +\".\" );\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn info.toString();\n\t}\n\t\n\t@Override\n\tpublic int price() {\n\t\tint price = 20 * (1 << (tier - 1));\n\t\tif (enchantment != null) {\n\t\t\tprice *= 1.5;\n\t\t}\n\t\tif (cursed && cursedKnown) {\n\t\t\tprice /= 2;\n\t\t}\n\t\tif (levelKnown) {\n\t\t\tif (level > 0) {\n\t\t\t\tprice *= (level + 1);\n\t\t\t} else if (level < 0) {\n\t\t\t\tprice /= (1 - level);\n\t\t\t}\n\t\t}\n\t\tif (price < 1) {\n\t\t\tprice = 1;\n\t\t}\n\t\treturn price;\n\t}\n\t\n\t@Override\n\tpublic Item random() {\n\t\tsuper.random();\n\t\t\n\t\tif (Random.Int( 10 + level ) == 0) {\n\t\t\tenchant( Enchantment.random() );\n\t\t}\n\t\t\n\t\treturn this;\n\t}\n}",
"public class Boomerang extends MissileWeapon {\n\n\t{\n\t\tname = \"boomerang\";\n\t\timage = ItemSpriteSheet.BOOMERANG;\n\t\t\n\t\tSTR = 10;\n\t\t\n\t\tMIN = 1;\n\t\tMAX = 4;\n\n\t\tstackable = false;\n\n bones = false;\n\t}\n\t\n\t@Override\n\tpublic boolean isUpgradable() {\n\t\treturn true;\n\t}\n\t\n\t@Override\n\tpublic Item upgrade() {\n\t\treturn upgrade( false );\n\t}\n\t\n\t@Override\n\tpublic Item upgrade( boolean enchant ) {\n\t\tMIN += 1;\n\t\tMAX += 2;\n\t\tsuper.upgrade( enchant );\n\t\t\n\t\tupdateQuickslot();\n\t\t\n\t\treturn this;\n\t}\n\t\n\t@Override\n\tpublic Item degrade() {\n\t\tMIN -= 1;\n\t\tMAX -= 2;\n\t\treturn super.degrade();\n\t}\n\t\n\t@Override\n\tpublic Weapon enchant( Enchantment ench ) {\n\t\twhile (ench instanceof Piercing || ench instanceof Swing) {\n\t\t\tench = Enchantment.random();\n\t\t}\n\t\t\n\t\treturn super.enchant( ench );\n\t}\n\n @Override\n public void proc( Char attacker, Char defender, int damage ) {\n super.proc( attacker, defender, damage );\n if (attacker instanceof Hero && ((Hero)attacker).rangedWeapon == this) {\n circleBack( defender.pos, (Hero)attacker );\n }\n }\n\n @Override\n protected void miss( int cell ) {\n circleBack( cell, curUser );\n }\n\n private void circleBack( int from, Hero owner ) {\n\n ((MissileSprite)curUser.sprite.parent.recycle( MissileSprite.class )).\n reset( from, curUser.pos, curItem, null );\n\n if (throwEquiped) {\n owner.belongings.weapon = this;\n owner.spend( -TIME_TO_EQUIP );\n\t\t\tDungeon.quickslot.replaceSimilar(this);\n\t\t\tupdateQuickslot();\n } else\n if (!collect( curUser.belongings.backpack )) {\n Dungeon.level.drop( this, owner.pos ).sprite.drop();\n }\n }\n\n private boolean throwEquiped;\n\n @Override\n public void cast( Hero user, int dst ) {\n throwEquiped = isEquipped( user );\n super.cast( user, dst );\n }\n\t\n\t@Override\n\tpublic String desc() {\n\t\tString info =\n\t\t\t\"Thrown to the enemy this flat curved wooden missile will return to the hands of its thrower.\";\n switch (imbue) {\n case LIGHT:\n info += \"\\n\\nIt was balanced to be lighter. \";\n break;\n case HEAVY:\n info += \"\\n\\nIt was balanced to be heavier. \";\n break;\n case NONE:\n }\n return info;\n\t}\n}",
"public enum Icons {\n\n\tSKULL,\n\tBUSY,\n\tCOMPASS,\n\tINFO, \n\tPREFS,\n\tWARNING,\n\tTARGET,\n\tMASTERY,\n\tWATA,\n SHPX,\n\tWARRIOR,\n\tMAGE,\n\tROGUE,\n\tHUNTRESS,\n\tCLOSE,\n\tDEPTH,\n\tDEPTH_LG,\n\tSLEEP,\n\tALERT,\n\tBACKPACK,\n\tSEED_POUCH,\n\tSCROLL_HOLDER,\n\tWAND_HOLSTER,\n\tCHECKED,\n\tUNCHECKED,\n EXIT,\n CHALLENGE_OFF,\n CHALLENGE_ON,\n\tRESUME;\n\t\n\tpublic Image get() {\n\t\treturn get( this );\n\t}\n\t\n\tpublic static Image get( Icons type ) {\n\t\tImage icon = new Image( Assets.ICONS );\n\t\tswitch (type) {\n\t\tcase SKULL:\n\t\t\ticon.frame( icon.texture.uvRect( 0, 0, 8, 8 ) );\n\t\t\tbreak;\n\t\tcase BUSY:\n\t\t\ticon.frame( icon.texture.uvRect( 8, 0, 16, 8 ) );\n\t\t\tbreak;\n\t\tcase COMPASS:\n\t\t\ticon.frame( icon.texture.uvRect( 0, 8, 7, 13 ) );\n\t\t\tbreak;\n\t\tcase INFO:\n\t\t\ticon.frame( icon.texture.uvRect( 16, 0, 30, 14 ) );\n\t\t\tbreak;\n\t\tcase PREFS:\n\t\t\ticon.frame( icon.texture.uvRect( 30, 0, 46, 16 ) );\n\t\t\tbreak;\n\t\tcase WARNING:\n\t\t\ticon.frame( icon.texture.uvRect( 46, 0, 58, 12 ) );\n\t\t\tbreak;\n\t\tcase TARGET:\n\t\t\ticon.frame( icon.texture.uvRect( 0, 13, 16, 29 ) );\n\t\t\tbreak;\n\t\tcase MASTERY:\n\t\t\ticon.frame( icon.texture.uvRect( 16, 14, 30, 28 ) );\n\t\t\tbreak;\n\t\tcase WATA:\n\t\t\ticon.frame( icon.texture.uvRect( 30, 16, 45, 26 ) );\n\t\t\tbreak;\n case SHPX:\n icon.frame( icon.texture.uvRect( 64, 44, 80, 60 ) );\n break;\n\t\tcase WARRIOR:\n\t\t\ticon.frame( icon.texture.uvRect( 0, 29, 16, 45 ) );\n\t\t\tbreak;\n\t\tcase MAGE:\n\t\t\ticon.frame( icon.texture.uvRect( 16, 29, 32, 45 ) );\n\t\t\tbreak;\n\t\tcase ROGUE:\n\t\t\ticon.frame( icon.texture.uvRect( 32, 29, 48, 45 ) );\n\t\t\tbreak;\n\t\tcase HUNTRESS:\n\t\t\ticon.frame( icon.texture.uvRect( 48, 29, 64, 45 ) );\n\t\t\tbreak;\n\t\tcase CLOSE:\n\t\t\ticon.frame( icon.texture.uvRect( 0, 45, 13, 58 ) );\n\t\t\tbreak;\n\t\tcase DEPTH:\n\t\t\ticon.frame( icon.texture.uvRect( 45, 12, 54, 20 ) );\n\t\t\tbreak;\n\t\tcase DEPTH_LG:\n\t\t\ticon.frame( icon.texture.uvRect( 34, 46, 50, 62 ) );\n\t\t\tbreak;\n\t\tcase SLEEP:\n\t\t\ticon.frame( icon.texture.uvRect( 13, 45, 22, 53 ) );\n\t\t\tbreak;\n\t\tcase ALERT:\n\t\t\ticon.frame( icon.texture.uvRect( 22, 45, 30, 53 ) );\n\t\t\tbreak;\n\t\tcase BACKPACK:\n\t\t\ticon.frame( icon.texture.uvRect( 58, 0, 68, 10 ) );\n\t\t\tbreak;\n\t\tcase SCROLL_HOLDER:\n\t\t\ticon.frame( icon.texture.uvRect( 68, 0, 78, 10 ) );\n\t\t\tbreak;\n\t\tcase SEED_POUCH:\n\t\t\ticon.frame( icon.texture.uvRect( 78, 0, 88, 10 ) );\n\t\t\tbreak;\n\t\tcase WAND_HOLSTER:\n\t\t\ticon.frame( icon.texture.uvRect( 88, 0, 98, 10 ) );\n\t\t\tbreak;\n\t\tcase CHECKED:\n\t\t\ticon.frame( icon.texture.uvRect( 54, 12, 66, 24 ) );\n\t\t\tbreak;\n\t\tcase UNCHECKED:\n\t\t\ticon.frame( icon.texture.uvRect( 66, 12, 78, 24 ) );\n\t\t\tbreak;\n case EXIT:\n icon.frame( icon.texture.uvRect( 98, 0, 114, 16 ) );\n break;\n case CHALLENGE_OFF:\n icon.frame( icon.texture.uvRect( 78, 16, 102, 40 ) );\n break;\n case CHALLENGE_ON:\n icon.frame( icon.texture.uvRect( 102, 16, 126, 40 ) );\n break;\n\t\tcase RESUME:\n\t\t\ticon.frame( icon.texture.uvRect( 13, 53, 24, 64 ) );\n\t\t\tbreak;\n\t\t}\n\t\treturn icon;\n\t}\n\t\n\tpublic static Image get( HeroClass cl ) {\n\t\tswitch (cl) {\n\t\tcase WARRIOR:\n\t\t\treturn get( WARRIOR );\n\t\tcase MAGE:\n\t\t\treturn get( MAGE );\n\t\tcase ROGUE:\n\t\t\treturn get( ROGUE );\n\t\tcase HUNTRESS:\n\t\t\treturn get( HUNTRESS );\n\t\tdefault:\n\t\t\treturn null;\n\t\t}\n\t}\n}"
] | import android.graphics.RectF;
import com.shatteredpixel.shatteredpixeldungeon.Assets;
import com.shatteredpixel.shatteredpixeldungeon.Dungeon;
import com.shatteredpixel.shatteredpixeldungeon.actors.hero.Belongings;
import com.shatteredpixel.shatteredpixeldungeon.actors.hero.Hero;
import com.shatteredpixel.shatteredpixeldungeon.items.EquipableItem;
import com.shatteredpixel.shatteredpixeldungeon.items.Gold;
import com.shatteredpixel.shatteredpixeldungeon.items.Item;
import com.shatteredpixel.shatteredpixeldungeon.items.armor.Armor;
import com.shatteredpixel.shatteredpixeldungeon.items.bags.Bag;
import com.shatteredpixel.shatteredpixeldungeon.items.bags.ScrollHolder;
import com.shatteredpixel.shatteredpixeldungeon.items.bags.SeedPouch;
import com.shatteredpixel.shatteredpixeldungeon.items.bags.WandHolster;
import com.shatteredpixel.shatteredpixeldungeon.items.food.Food;
import com.shatteredpixel.shatteredpixeldungeon.items.potions.Potion;
import com.shatteredpixel.shatteredpixeldungeon.items.scrolls.Scroll;
import com.shatteredpixel.shatteredpixeldungeon.items.wands.Wand;
import com.shatteredpixel.shatteredpixeldungeon.items.weapon.melee.MeleeWeapon;
import com.shatteredpixel.shatteredpixeldungeon.items.weapon.missiles.Boomerang;
import com.shatteredpixel.shatteredpixeldungeon.plants.Plant.Seed;
import com.shatteredpixel.shatteredpixeldungeon.scenes.GameScene;
import com.shatteredpixel.shatteredpixeldungeon.scenes.PixelScene;
import com.shatteredpixel.shatteredpixeldungeon.sprites.ItemSpriteSheet;
import com.shatteredpixel.shatteredpixeldungeon.ui.Icons;
import com.shatteredpixel.shatteredpixeldungeon.ui.ItemSlot;
import com.shatteredpixel.shatteredpixeldungeon.ui.QuickSlotButton;
import com.shatteredpixel.shatteredpixeldungeon.utils.Utils;
import com.watabou.gltextures.TextureCache;
import com.watabou.noosa.BitmapText;
import com.watabou.noosa.ColorBlock;
import com.watabou.noosa.Image;
import com.watabou.noosa.audio.Sample; | icon.y = y + (height - icon.height) / 2 - 2 - (selected ? 0 : 1);
if (!selected && icon.y < y + CUT) {
RectF frame = icon.frame();
frame.top += (y + CUT - icon.y) / icon.texture.height;
icon.frame( frame );
icon.y = y + CUT;
}
}
private Image icon() {
if (bag instanceof SeedPouch) {
return Icons.get( Icons.SEED_POUCH );
} else if (bag instanceof ScrollHolder) {
return Icons.get( Icons.SCROLL_HOLDER );
} else if (bag instanceof WandHolster) {
return Icons.get( Icons.WAND_HOLSTER );
} else {
return Icons.get( Icons.BACKPACK );
}
}
}
private static class Placeholder extends Item {
{
name = null;
}
public Placeholder( int image ) {
this.image = image;
}
@Override
public boolean isIdentified() {
return true;
}
@Override
public boolean isEquipped( Hero hero ) {
return true;
}
}
private class ItemButton extends ItemSlot {
private static final int NORMAL = 0xFF4A4D44;
private static final int EQUIPPED = 0xFF63665B;
private Item item;
private ColorBlock bg;
public ItemButton( Item item ) {
super( item );
this.item = item;
if (item instanceof Gold) {
bg.visible = false;
}
width = height = SLOT_SIZE;
}
@Override
protected void createChildren() {
bg = new ColorBlock( SLOT_SIZE, SLOT_SIZE, NORMAL );
add( bg );
super.createChildren();
}
@Override
protected void layout() {
bg.x = x;
bg.y = y;
super.layout();
}
@Override
public void item( Item item ) {
super.item( item );
if (item != null) {
bg.texture( TextureCache.createSolid( item.isEquipped( Dungeon.hero ) ? EQUIPPED : NORMAL ) );
if (item.cursed && item.cursedKnown) {
bg.ra = +0.2f;
bg.ga = -0.1f;
} else if (!item.isIdentified()) {
bg.ra = 0.1f;
bg.ba = 0.1f;
}
if (item.name() == null) {
enable( false );
} else {
enable(
mode == Mode.FOR_SALE && (item.price() > 0) && (!item.isEquipped( Dungeon.hero ) || !item.cursed) ||
mode == Mode.UPGRADEABLE && item.isUpgradable() ||
mode == Mode.UNIDENTIFED && !item.isIdentified() ||
mode == Mode.QUICKSLOT && (item.defaultAction != null) ||
mode == Mode.WEAPON && (item instanceof MeleeWeapon || item instanceof Boomerang) ||
mode == Mode.ARMOR && (item instanceof Armor) ||
mode == Mode.WAND && (item instanceof Wand) ||
mode == Mode.SEED && (item instanceof Seed) ||
mode == Mode.FOOD && (item instanceof Food) ||
mode == Mode.POTION && (item instanceof Potion) ||
mode == Mode.SCROLL && (item instanceof Scroll) ||
mode == Mode.EQUIPMENT && (item instanceof EquipableItem) ||
mode == Mode.ALL
);
}
} else {
bg.color( NORMAL );
}
}
@Override
protected void onTouchDown() {
bg.brightness( 1.5f ); | Sample.INSTANCE.play( Assets.SND_CLICK, 0.7f, 0.7f, 1.2f ); | 0 |
handstudio/HzGrapher | sample/src/com/handstudio/android/hzgrapher/LineCompareGraphActivity.java | [
"public class GraphAnimation {\n\tpublic static final int LINEAR_ANIMATION = 1;\n\t\n\tpublic static final int CURVE_REGION_ANIMATION_1 = 2;\n\tpublic static final int CURVE_REGION_ANIMATION_2 = 3;\n\t\n\tpublic static final int DEFAULT_DURATION = 2000;\n\t\n\tprivate int animation = LINEAR_ANIMATION;\n\tprivate int duration = DEFAULT_DURATION;\n\t\n\tpublic GraphAnimation() {\n\t\t\n\t}\n\t\n\tpublic GraphAnimation(int animation, int duration) {\n\t\tsuper();\n\t\tthis.animation = animation;\n\t\tthis.duration = duration;\n\t}\n\tpublic int getAnimation() {\n\t\treturn animation;\n\t}\n\tpublic void setAnimation(int animation) {\n\t\tthis.animation = animation;\n\t}\n\tpublic int getDuration() {\n\t\treturn duration;\n\t}\n\tpublic void setDuration(int duration) {\n\t\tthis.duration = duration;\n\t}\n\t\n}",
"public class LineCompareGraphView extends SurfaceView implements Callback{\n\n\tpublic static final String TAG = \"LineComapreGraphView\";\n\tprivate SurfaceHolder mHolder;\n\tprivate DrawThread mDrawThread;\n\t\n\tprivate LineGraphVO mLineGraphVO = null;\n\t\n\t\n\t//Constructor\n\tpublic LineCompareGraphView(Context context, LineGraphVO vo) {\n\t\tsuper(context);\n\t\tmLineGraphVO = vo;\n\t\tinitView(context, vo);\n\t}\n\t\n\tprivate void initView(Context context, LineGraphVO vo) {\n\t\tErrorCode ec = ErrorDetector.checkLineCompareGraphObject(vo);\n\t\tec.printError();\n\t\t\n\t\tmHolder = getHolder();\n\t\tmHolder.addCallback(this);\n\t}\n\n\t@Override\n\tpublic void surfaceChanged(SurfaceHolder holder, int format, int width,\n\t\t\tint height) {\n\t\t\n\t}\n\n\t@Override\n\tpublic void surfaceCreated(SurfaceHolder holder) {\n\t\tif(mDrawThread == null){\n\t\t\tmDrawThread = new DrawThread(mHolder, getContext());\n\t\t\tmDrawThread.start();\n\t\t}\n\t}\n\n\t@Override\n\tpublic void surfaceDestroyed(SurfaceHolder holder) {\n\t\tif(mDrawThread != null){\n\t\t\tmDrawThread.setRunFlag(false);\n\t\t\tmDrawThread = null;\n\t\t}\n\t\t\n\t}\n\t\n\tprivate static final Object touchLock = new Object(); // touch synchronize\n\t@Override\n\tpublic boolean onTouchEvent(MotionEvent event) {\n\t\tint action = event.getAction();\n\t\t\n\t\tif(mDrawThread == null ){\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tif(action == MotionEvent.ACTION_DOWN){\n\t\t\tsynchronized (touchLock) {\n\t\t\t\tmDrawThread.isDirty = true;\n\t }\n\t\t\treturn true;\n\t\t}else if(action == MotionEvent.ACTION_MOVE){\n\t\t\tsynchronized (touchLock) {\n\t\t\t\tmDrawThread.isDirty = true;\n\t }\n\t\t\treturn true;\n\t\t}else if(action == MotionEvent.ACTION_UP){\n\t\t\tsynchronized (touchLock) {\n\t\t\t\tmDrawThread.isDirty = true;\n\t }\n\t\t\treturn true;\n\t\t}\n\t\t\n\t\treturn super.onTouchEvent(event);\n\t}\n\t\n\tclass DrawThread extends Thread{\n\t\tBitmap b = Bitmap.createBitmap(getWidth(), getHeight(), Config.ARGB_8888);\n\t\tSurfaceHolder mHolder;\n\t\tContext mCtx;\n\t\t\n\t\tboolean isRun = true;\n\t\tboolean isDirty = true;\n\t\t\n\t\tMatrix matrix = new Matrix();\n\t\t\n\t\tint height = getHeight();\n\t\tint width = getWidth();\n\t\t\n\t\t//graph length\n\t\tint xLength = width - (mLineGraphVO.getPaddingLeft() + mLineGraphVO.getPaddingRight() + mLineGraphVO.getMarginRight());\n\t\tint yLength = height - (mLineGraphVO.getPaddingBottom() + mLineGraphVO.getPaddingTop() + mLineGraphVO.getMarginTop());\n\t\t\n\t\t//chart length\n\t\tint chartXLength = width - (mLineGraphVO.getPaddingLeft() + mLineGraphVO.getPaddingRight());\n\t\tint chartYLength = height - (mLineGraphVO.getPaddingBottom() + mLineGraphVO.getPaddingTop());\n\t\t\n\t\tPaint p = new Paint();\n\t\tPaint pCircle = new Paint();\n\t\tPaint pLine = new Paint();\n\t\tPaint pBaseLine = new Paint();\n\t\tPaint pBaseLineX = new Paint();\n\t\tPaint pMarkText = new Paint();\n\t\t\n\t\t//animation\n\t\tfloat anim = 0.0f;\n\t\tboolean isAnimation = false;\n\t\tlong animStartTime = -1;\n\t\t\n\t\tWeakHashMap<Integer, Bitmap> arrIcon = new WeakHashMap<Integer, Bitmap>();\n\t\tBitmap bg = null;\n\t\tpublic DrawThread(SurfaceHolder holder, Context context) {\n\t\t\tmHolder = holder;\n\t\t\tmCtx = context;\n\t\t\t\n\t\t\tint size = mLineGraphVO.getArrGraph().size();\n\t\t\tfor (int i = 0; i < size; i++) {\n\t\t\t\tint bitmapResource = mLineGraphVO.getArrGraph().get(i).getBitmapResource();\n\t\t\t\tif(bitmapResource != -1){\n\t\t\t\t\tarrIcon.put(i, BitmapFactory.decodeResource(getResources(), bitmapResource));\n\t\t\t\t}else{\n\t\t\t\t\tif(arrIcon.get(i) != null){\n\t\t\t\t\t\tarrIcon.remove(i);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tint bgResource = mLineGraphVO.getGraphBG();\n\t\t\tif(bgResource != -1){\n\t\t\t\tBitmap tempBg = BitmapFactory.decodeResource(getResources(), bgResource);\n\t\t\t\tbg = Bitmap.createScaledBitmap(tempBg, width, height, true);\n\t\t\t\ttempBg.recycle();\n\t\t\t}\n\t\t}\n\t\t\n\t\tpublic void setRunFlag(boolean bool){\n\t\t\tisRun = bool;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic void run() {\n\t\t\tCanvas canvas = null;\n\t\t\tGraphCanvasWrapper graphCanvasWrapper = null;\n\t\t\tLog.e(TAG,\"height = \" + height);\n\t\t\tLog.e(TAG,\"width = \" + width);\n\t\t\t\n\t\t\tsetPaint();\n\t\t\tisAnimation();\n\t\t\t\n\t\t\tanimStartTime = System.currentTimeMillis();\n\t\t\t\n\t\t\twhile(isRun){\n\t\t\t\n\t\t\t\t//draw only on dirty mode\n\t\t\t\tif(!isDirty){\n\t\t\t\t\ttry {\n\t\t\t\t\t\tThread.sleep(100);\n\t\t\t\t\t} catch (InterruptedException e1) {\n\t\t\t\t\t\te1.printStackTrace();\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tcanvas = mHolder.lockCanvas();\n\t\t\t\tgraphCanvasWrapper = new GraphCanvasWrapper(canvas, width, height, mLineGraphVO.getPaddingLeft(), mLineGraphVO.getPaddingBottom());\n\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(0000);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t\tcalcTimePass();\n\t\t\t\t\n\t\t\t\tsynchronized(mHolder){\n\t\t\t\t\tsynchronized (touchLock) {\n\t\t\t\t\t\t\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t//bg color\n\t\t\t\t\t\t\tcanvas.drawColor(Color.WHITE);\n\t\t\t\t\t\t\tif(bg != null){\n\t\t\t\t\t\t\t\tcanvas.drawBitmap(bg, 0, 0, null);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t//x coord dot line\n\t\t\t\t\t\t\tdrawBaseLine(graphCanvasWrapper);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t//y coord\n\t\t\t\t\t\t\tgraphCanvasWrapper.drawLine(0, 0, 0, chartYLength, pBaseLine);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t//x coord\n\t\t\t\t\t\t\tgraphCanvasWrapper.drawLine(0, 0, chartXLength, 0, pBaseLine);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t//x, y coord mark\n\t\t\t\t\t\t\tdrawXMark(graphCanvasWrapper);\n\t\t\t\t\t\t\tdrawYMark(graphCanvasWrapper);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t//x, y coord text\n\t\t\t\t\t\t\tdrawXText(graphCanvasWrapper);\n\t\t\t\t\t\t\tdrawYText(graphCanvasWrapper);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t//Graph\n\t\t\t\t\t\t\tdrawGraphRegion(graphCanvasWrapper);\n\t\t\t\t\t\t\tdrawGraph(graphCanvasWrapper);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tdrawGraphName(canvas);\n\t\t\t\t\t\t\t\n//\t\t\t\t\t\t\tisDirty = false;\n\t\t\t\t\t\t\t\n\n\t\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\t\te.printStackTrace();\n\t\t\t\t\t\t} finally {\n\t\t\t\t\t\t\tif(graphCanvasWrapper.getCanvas() != null){\n\t\t\t\t\t\t\t\tmHolder.unlockCanvasAndPost(graphCanvasWrapper.getCanvas());\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tprivate void calcTimePass(){\n\t\t\tif(isAnimation){\n\t\t\t\tlong curTime = System.currentTimeMillis();\n\t\t\t\tlong gapTime = curTime - animStartTime;\n\t\t\t\tlong animDuration = mLineGraphVO.getAnimation().getDuration();\n\t\t\t\tif(gapTime >= animDuration){\n\t\t\t\t\tgapTime = animDuration;\n\t\t\t\t\tisDirty = false;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tanim = mLineGraphVO.getArrGraph().get(0).getCoordinateArr().length * (float)gapTime/(float)animDuration;\n//\t\t\t\tanim = anim + 0.1f;\n\t\t\t}else{\n\t\t\t\tisDirty = false;\n\t\t\t}\n\t\t\t\n//\t\t\tLog.e(TAG,\"curTime = \" + curTime + \" , animStartTime = \" + animStartTime);\n//\t\t\tLog.e(TAG,\"anim = \" + anim + \" , gapTime = \" + gapTime);\n\t\t}\n\n\t\tprivate void drawGraphName(Canvas canvas) {\n\t\t\tGraphNameBox gnb = mLineGraphVO.getGraphNameBox();\n\t\t\tif(gnb != null){\n\t\t\t\tint nameboxWidth = 0;\n\t\t\t\tint nameboxHeight = 0;\n\t\t\t\t\n\t\t\t\tint nameboxIconWidth = gnb.getNameboxIconWidth();\n\t\t\t\tint nameboxIconHeight = gnb.getNameboxIconHeight();\n\t\t\t\t\n\t\t\t\tint nameboxMarginTop = gnb.getNameboxMarginTop();\n\t\t\t\tint nameboxMarginRight = gnb.getNameboxMarginRight();\n\t\t\t\tint nameboxPadding = gnb.getNameboxPadding();\n\t\t\t\t\n\t\t\t\tint nameboxTextIconMargin = gnb.getNameboxIconMargin();\n\t\t\t\tint nameboxIconMargin = gnb.getNameboxIconMargin();\n\t\t\t\tint nameboxTextSize = gnb.getNameboxTextSize(); \n\t\t\t\t\n\t\t\t\tint maxTextWidth = 0;\n\t\t\t\tint maxTextHeight = 0;\n\t\t\t\t\n\t\t\t\tPaint nameRextPaint = new Paint();\n\t\t\t\tnameRextPaint.setFlags(Paint.ANTI_ALIAS_FLAG);\n\t\t\t\tnameRextPaint.setAntiAlias(true); //text anti alias\n\t\t\t\tnameRextPaint.setFilterBitmap(true); // bitmap anti alias\n\t\t\t\tnameRextPaint.setColor(Color.BLUE);\n\t\t\t\tnameRextPaint.setStrokeWidth(3);\n\t\t\t\tnameRextPaint.setStyle(Style.STROKE);\n\t\t\t\t\n\t\t\t\tPaint pIcon = new Paint();\n\t\t\t\tpIcon.setFlags(Paint.ANTI_ALIAS_FLAG);\n\t\t\t\tpIcon.setAntiAlias(true); //text anti alias\n\t\t\t\tpIcon.setFilterBitmap(true); // bitmap anti alias\n\t\t\t\tpIcon.setColor(Color.BLUE);\n\t\t\t\tpIcon.setStrokeWidth(3);\n\t\t\t\tpIcon.setStyle(Style.FILL_AND_STROKE);\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tPaint pNameText = new Paint();\n\t\t\t\tpNameText.setFlags(Paint.ANTI_ALIAS_FLAG);\n\t\t\t\tpNameText.setAntiAlias(true); //text anti alias\n\t\t\t\tpNameText.setTextSize(nameboxTextSize);\n\t\t\t\tpNameText.setColor(Color.BLACK); \n\t\t\t\t\n\t\t\t\t\n\t\t\t\tint graphSize = mLineGraphVO.getArrGraph().size();\n\t\t\t\tfor (int i = 0; i < graphSize; i++) {\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\tString text = mLineGraphVO.getArrGraph().get(i).getName();\n\t\t\t\t\tRect rect = new Rect();\n\t\t\t\t\tpNameText.getTextBounds(text, 0, text.length(), rect);\n\t\t\t\t\t\n\t\t\t\t\tif(rect.width() > maxTextWidth){\n\t\t\t\t\t\tmaxTextWidth = rect.width();\n\t\t\t\t\t\tmaxTextHeight = rect.height();\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tmLineGraphVO.getArrGraph().get(i).getName();\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\tmLineGraphVO.getArrGraph().get(0).getName();\n\t\t\t\tnameboxWidth = 1 * maxTextWidth + nameboxTextIconMargin + nameboxIconWidth;\n\t\t\t\tint maxCellHight = maxTextHeight;\n\t\t\t\tif(nameboxIconHeight > maxTextHeight){\n\t\t\t\t\tmaxCellHight = nameboxIconHeight;\n\t\t\t\t}\n\t\t\t\tnameboxHeight = graphSize * maxCellHight + (graphSize-1) * nameboxIconMargin;\n\t\t\t\t\n\t\t\t\tcanvas.drawRect(width - (nameboxMarginRight + nameboxWidth) - nameboxPadding*2,\n\t\t\t\t\t\tnameboxMarginTop, width - nameboxMarginRight, nameboxMarginTop + nameboxHeight + nameboxPadding*2, nameRextPaint);\n\t\t\t\t\n\t\t\t\tfor (int i = 0; i < graphSize; i++) {\n\t\t\t\t\t\n\t\t\t\t\tpIcon.setColor(mLineGraphVO.getArrGraph().get(i).getColor());\n\t\t\t\t\tcanvas.drawRect(width - (nameboxMarginRight + nameboxWidth) - nameboxPadding,\n\t\t\t\t\t\t\tnameboxMarginTop + (maxCellHight * i) + nameboxPadding + (nameboxIconMargin * i), \n\t\t\t\t\t\t\twidth - (nameboxMarginRight + maxTextWidth) - nameboxPadding - nameboxTextIconMargin, \n\t\t\t\t\t\t\tnameboxMarginTop + maxCellHight * (i+1) + nameboxPadding + nameboxIconMargin * i, pIcon);\n\t\t\t\t\t\n\t\t\t\t\tString text = mLineGraphVO.getArrGraph().get(i).getName();\n\t\t\t\t\tcanvas.drawText(text, width - (nameboxMarginRight + maxTextWidth) - nameboxPadding, \n\t\t\t\t\t\t\tnameboxMarginTop + maxTextHeight/2 + maxCellHight * i + maxCellHight/2 + nameboxPadding + nameboxIconMargin * i, pNameText);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * check graph line animation\n\t\t */\n\t\tprivate void isAnimation() {\n\t\t\tif(mLineGraphVO.getAnimation() != null){\n\t\t\t\tisAnimation = true;\n\t\t\t}else{\n\t\t\t\tisAnimation = false;\n\t\t\t}\n\t\t}\n\t\t\n\t\tprivate void drawBaseLine(GraphCanvasWrapper graphCanvas) {\n\t\t\tfor (int i = 1; mLineGraphVO.getIncrement() * i <= mLineGraphVO.getMaxValue(); i++) {\n\t\t\t\t\n\t\t\t\tfloat y = yLength * mLineGraphVO.getIncrement() * i/mLineGraphVO.getMaxValue();\n\t\t\t\t\n\t\t\t\tgraphCanvas.drawLine(0, y, chartXLength, y, pBaseLineX);\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * set graph line color\n\t\t */\n\t\tprivate void setPaint() {\n\t\t\tp = new Paint();\n\t\t\tp.setFlags(Paint.ANTI_ALIAS_FLAG);\n\t\t\tp.setAntiAlias(true); //text anti alias\n\t\t\tp.setFilterBitmap(true); // bitmap anti alias\n\t\t\tp.setColor(Color.BLUE);\n\t\t\tp.setStrokeWidth(3);\n\t\t\tp.setStyle(Style.STROKE);\n\t\t\t\n\t\t\tpCircle = new Paint();\n\t\t\tpCircle.setFlags(Paint.ANTI_ALIAS_FLAG);\n\t\t\tpCircle.setAntiAlias(true); //text anti alias\n\t\t\tpCircle.setFilterBitmap(true); // bitmap anti alias\n\t\t\tpCircle.setColor(Color.BLUE);\n\t\t\tpCircle.setStrokeWidth(3);\n\t\t\tpCircle.setStyle(Style.FILL_AND_STROKE);\n\t\t\t\n\t\t\tpLine = new Paint();\n\t\t\tpLine.setFlags(Paint.ANTI_ALIAS_FLAG);\n\t\t\tpLine.setAntiAlias(true); //text anti alias\n\t\t\tpLine.setFilterBitmap(true); // bitmap anti alias\n\t\t\tpLine.setShader(new LinearGradient(0, 300f, 0, 0f, Color.BLACK, Color.WHITE, Shader.TileMode.MIRROR));\n\t\t\t\n\t\t\tpBaseLine = new Paint();\n\t\t\tpBaseLine.setFlags(Paint.ANTI_ALIAS_FLAG);\n\t\t\tpBaseLine.setAntiAlias(true); //text anti alias\n\t\t\tpBaseLine.setFilterBitmap(true); // bitmap anti alias\n\t\t\tpBaseLine.setColor(Color.GRAY);\n\t\t\tpBaseLine.setStrokeWidth(3);\n\t\t\t\n\t\t\tpBaseLineX = new Paint();\n\t\t\tpBaseLineX.setFlags(Paint.ANTI_ALIAS_FLAG);\n\t\t\tpBaseLineX.setAntiAlias(true); //text anti alias\n\t\t\tpBaseLineX.setFilterBitmap(true); // bitmap anti alias\n\t\t\tpBaseLineX.setColor(0xffcccccc);\n\t\t\tpBaseLineX.setStrokeWidth(3);\n\t\t\tpBaseLineX.setStyle(Style.STROKE);\n\t\t\tpBaseLineX.setPathEffect(new DashPathEffect(new float[] {10,5}, 0));\n\t\t\t\n\t\t\tpMarkText = new Paint();\n\t\t\tpMarkText.setFlags(Paint.ANTI_ALIAS_FLAG);\n\t\t\tpMarkText.setAntiAlias(true); //text anti alias\n\t\t\tpMarkText.setColor(Color.BLACK); \n\t\t}\n\n\t\t/**\n\t\t * draw Graph Region\n\t\t */\n\t\tprivate void drawGraphRegion(GraphCanvasWrapper graphCanvas) {\n\t\t\t\n\t\t\tif (isAnimation){\n\t\t\t\tdrawGraphCompareRegionWithAnimation(graphCanvas);\n\t\t\t}else{\n\t\t\t\tdrawGraphCompareRegionWithoutAnimation(graphCanvas);\n\t\t\t}\n\t\t}\n\t\t\n\t\t/**\n\t\t * draw Graph\n\t\t */\n\t\tprivate void drawGraph(GraphCanvasWrapper graphCanvas) {\n\t\t\t\n\t\t\tif (isAnimation){\n\t\t\t\tdrawGraphWithAnimation(graphCanvas);\n\t\t\t}else{\n\t\t\t\tdrawGraphWithoutAnimation(graphCanvas);\n\t\t\t}\n\t\t}\n\t\t\n\t\t/**\n\t\t *\tdraw graph without animation \n\t\t */\n\t\tprivate void drawGraphWithoutAnimation(GraphCanvasWrapper graphCanvas) {\n\t\t\tfor (int i = 0; i < mLineGraphVO.getArrGraph().size(); i++) {\n\t\t\t\tGraphPath linePath = new GraphPath(width, height, mLineGraphVO.getPaddingLeft(), mLineGraphVO.getPaddingBottom());\n\t\t\t\tboolean firstSet = false;\n\t\t\t\tfloat x = 0;\n\t\t\t\tfloat y = 0;\n\t\t\t\tp.setColor(mLineGraphVO.getArrGraph().get(i).getColor());\n\t\t\t\tpCircle.setColor(mLineGraphVO.getArrGraph().get(i).getColor());\n\t\t\t\tfloat xGap = xLength/(mLineGraphVO.getArrGraph().get(i).getCoordinateArr().length-1);\n\t\t\t\t\n\t\t\t\tBitmap icon = arrIcon.get(i);\n\t\t\t\t\n\t\t\t\tfor (int j = 0; j < mLineGraphVO.getArrGraph().get(i).getCoordinateArr().length; j++) {\n\t\t\t\t\tif(j < mLineGraphVO.getArrGraph().get(i).getCoordinateArr().length){\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (!firstSet) {\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tx = xGap * j ;\n\t\t\t\t\t\t\ty = yLength * mLineGraphVO.getArrGraph().get(i).getCoordinateArr()[j]/mLineGraphVO.getMaxValue();\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tlinePath.moveTo(x, y);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tfirstSet = true;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tx = xGap * j;\n\t\t\t\t\t\t\ty = yLength * mLineGraphVO.getArrGraph().get(i).getCoordinateArr()[j]/mLineGraphVO.getMaxValue();\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tlinePath.lineTo(x, y);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tif(icon == null){\n\t\t\t\t\t\t\tgraphCanvas.drawCircle(x, y, 4, pCircle);\n\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\tgraphCanvas.drawBitmapIcon(icon, x, y, null);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tgraphCanvas.getCanvas().drawPath(linePath, p);\n\t\t\t}\n\t\t}\n\t\t\n\t\tprivate void drawGraphCompareRegionWithoutAnimation(GraphCanvasWrapper graphCanvas) {\n\t\t\tCanvas c = new Canvas(b);\n\t\t\tb.eraseColor(Color.TRANSPARENT);\n\t\t\t\n\t\t\tPaint pBg = new Paint();\n\t\t\tpBg.setFlags(Paint.ANTI_ALIAS_FLAG);\n\t\t\tpBg.setAntiAlias(true); //text anti alias\n\t\t\tpBg.setFilterBitmap(true); // bitmap anti alias\n\t\t\tpBg.setStyle(Style.FILL);\n\t\t\t\n\t\t\tArrayList<GraphPath> arrLineBgPath = new ArrayList<GraphPath>();\n\t\t\t\n\t\t\tfor (int i = 0; i < mLineGraphVO.getArrGraph().size(); i++) {\n\t\t\t\tGraphPath lineBgPath = new GraphPath(width, height, mLineGraphVO.getPaddingLeft(), mLineGraphVO.getPaddingBottom());\n\t\t\t\tboolean firstSet = false;\n\t\t\t\tfloat x = 0;\n\t\t\t\tfloat y = 0;\n\t\t\t\tp.setColor(mLineGraphVO.getArrGraph().get(i).getColor());\n\t\t\t\tpCircle.setColor(mLineGraphVO.getArrGraph().get(i).getColor());\n\t\t\t\tfloat xGap = xLength/(mLineGraphVO.getArrGraph().get(i).getCoordinateArr().length-1);\n\t\t\t\t\n\t\t\t\tfor (int j = 0; j < mLineGraphVO.getArrGraph().get(i).getCoordinateArr().length; j++) {\n\t\t\t\t\tif(j < mLineGraphVO.getArrGraph().get(i).getCoordinateArr().length){\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (!firstSet) {\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tx = xGap * j ;\n\t\t\t\t\t\t\ty = yLength * mLineGraphVO.getArrGraph().get(i).getCoordinateArr()[j]/mLineGraphVO.getMaxValue();\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tlineBgPath.moveTo(x, 0);\n\t\t\t\t\t\t\tlineBgPath.lineTo(x, y);\n\t\t\t\t\t\t\tfirstSet = true;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tx = xGap * j;\n\t\t\t\t\t\t\ty = yLength * mLineGraphVO.getArrGraph().get(i).getCoordinateArr()[j]/mLineGraphVO.getMaxValue();\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tlineBgPath.lineTo(x, y);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tlineBgPath.lineTo(x, 0);\n\t\t\t\tlineBgPath.lineTo(0, 0);\n\t\t\t\tarrLineBgPath.add(lineBgPath);\n\t\t\t\t\t\n\t\t\t}\n\n\t\t\tpBg.setColor(mLineGraphVO.getArrGraph().get(0).getColor());\n\t\t\tpBg.setAlpha(255);\n\t\t\tc.drawPath(arrLineBgPath.get(0), pBg);\n\t\t\tpBg.setXfermode(new PorterDuffXfermode(Mode.XOR));\n\t\t\tpBg.setColor(mLineGraphVO.getArrGraph().get(1).getColor());\n\t\t\tpBg.setAlpha(255);\n\t\t\tc.drawPath(arrLineBgPath.get(1), pBg);\n\t\t\tgraphCanvas.getCanvas().drawBitmap(b, 0, 0, null);\n\t\t}\n\n\t\t/**\n\t\t *\tdraw graph with animation \n\t\t */\n\t\tprivate void drawGraphWithAnimation(GraphCanvasWrapper graphCanvas) {\n\t\t\t//for draw animation\n\t\t\tfloat prev_x = 0;\n\t\t\tfloat prev_y = 0;\n\t\t\t\n\t\t\tfloat next_x = 0;\n\t\t\tfloat next_y = 0;\n\t\t\t\n\t\t\tfloat value = 0;\n\t\t\tfloat mode = 0;\n\t\t\t\n\t\t\tfor (int i = 0; i < mLineGraphVO.getArrGraph().size(); i++) {\n\t\t\t\tGraphPath linePath = new GraphPath(width, height, mLineGraphVO.getPaddingLeft(), mLineGraphVO.getPaddingBottom());\n\t\t\t\tboolean firstSet = false;\n\t\t\t\tfloat x = 0;\n\t\t\t\tfloat y = 0;\n\t\t\t\tp.setColor(mLineGraphVO.getArrGraph().get(i).getColor());\n\t\t\t\tpCircle.setColor(mLineGraphVO.getArrGraph().get(i).getColor());\n\t\t\t\tfloat xGap = xLength/(mLineGraphVO.getArrGraph().get(i).getCoordinateArr().length-1);\n\t\t\t\t\n\t\t\t\tBitmap icon = arrIcon.get(i);\n\t\t\t\tvalue = anim/1;\n\t\t\t\tmode = anim %1;\n\t\t\t\t\n\t\t\t\tfor (int j = 0; j < value+1; j++) {\n\t\t\t\t\tif(j < mLineGraphVO.getArrGraph().get(i).getCoordinateArr().length){\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (!firstSet) {\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tx = xGap * j ;\n\t\t\t\t\t\t\ty = yLength * mLineGraphVO.getArrGraph().get(i).getCoordinateArr()[j]/mLineGraphVO.getMaxValue();\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tlinePath.moveTo(x, y);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tfirstSet = true;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tx = xGap * j;\n\t\t\t\t\t\t\ty = yLength * mLineGraphVO.getArrGraph().get(i).getCoordinateArr()[j]/mLineGraphVO.getMaxValue();\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tif( j > value ){\n\t\t\t\t\t\t\t\tnext_x = x - prev_x;\n\t\t\t\t\t\t\t\tnext_y = y - prev_y;\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tlinePath.lineTo(prev_x + next_x * mode, prev_y + next_y * mode);\n\t\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\t\tlinePath.lineTo(x, y);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tif(icon == null){\n\t\t\t\t\t\t\tgraphCanvas.drawCircle(x, y, 4, pCircle);\n\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\tgraphCanvas.drawBitmapIcon(icon, x, y, null);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tprev_x = x;\n\t\t\t\t\t\tprev_y = y;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tgraphCanvas.getCanvas().drawPath(linePath, p);\n\t\t\t}\n\t\t}\n\t\t\n\t\t/**\n\t\t *\tdraw graph with animation \n\t\t */\n\t\tprivate void drawGraphCompareRegionWithAnimation(GraphCanvasWrapper graphCanvas) {\n\t\t\t//for draw animation\n\t\t\tfloat prev_x = 0;\n\t\t\tfloat prev_y = 0;\n\t\t\t\n\t\t\tfloat next_x = 0;\n\t\t\tfloat next_y = 0;\n\t\t\t\n\t\t\tint value = 0;\n\t\t\tfloat mode = 0;\n\t\t\t\n\t\t\tCanvas c = new Canvas(b);\n\t\t\tb.eraseColor(Color.TRANSPARENT);\n\t\t\t\n\t\t\tPaint pBg = new Paint();\n\t\t\tpBg.setFlags(Paint.ANTI_ALIAS_FLAG);\n\t\t\tpBg.setAntiAlias(true); //text anti alias\n\t\t\tpBg.setFilterBitmap(true); // bitmap anti alias\n\t\t\tpBg.setStyle(Style.FILL);\n\t\t\t\n\t\t\tArrayList<GraphPath> arrLineBgPath = new ArrayList<GraphPath>();\n\t\t\t\n\t\t\tfor (int i = 0; i < mLineGraphVO.getArrGraph().size(); i++) {\n\t\t\t\tGraphPath lineBgPath = new GraphPath(width, height, mLineGraphVO.getPaddingLeft(), mLineGraphVO.getPaddingBottom());\n\t\t\t\t\n\t\t\t\tboolean firstSet = false;\n\t\t\t\tfloat x = 0;\n\t\t\t\tfloat y = 0;\n\t\t\t\tp.setColor(mLineGraphVO.getArrGraph().get(i).getColor());\n\t\t\t\tpCircle.setColor(mLineGraphVO.getArrGraph().get(i).getColor());\n\t\t\t\tfloat xGap = xLength/(mLineGraphVO.getArrGraph().get(i).getCoordinateArr().length-1);\n\t\t\t\t\n\t\t\t\tvalue = (int) (anim/1);\n\t\t\t\tmode = anim %1;\n\t\t\t\t\n//\t\t\t\tLog.e(\"\", \"value = \" + value + \"\\t ,mode = \" + mode);\n\t\t\t\t\n\t\t\t\tfor (int j = 0; j <= value+1; j++) {\n\t\t\t\t\tif(j < mLineGraphVO.getArrGraph().get(i).getCoordinateArr().length){\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (!firstSet) {\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tx = xGap * j ;\n\t\t\t\t\t\t\ty = yLength * mLineGraphVO.getArrGraph().get(i).getCoordinateArr()[j]/mLineGraphVO.getMaxValue();\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tlineBgPath.moveTo(x, 0);\n\t\t\t\t\t\t\tlineBgPath.lineTo(x, y);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tfirstSet = true;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tx = xGap * j;\n\t\t\t\t\t\t\ty = yLength * mLineGraphVO.getArrGraph().get(i).getCoordinateArr()[j]/mLineGraphVO.getMaxValue();\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tif( j > value ){\n\t\t\t\t\t\t\t\tnext_x = x - prev_x;\n\t\t\t\t\t\t\t\tnext_y = y - prev_y;\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tlineBgPath.lineTo(prev_x + next_x * mode, prev_y + next_y * mode);\n\t\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\t\tlineBgPath.lineTo(x, y);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tprev_x = x;\n\t\t\t\t\t\tprev_y = y;\n\t\t\t\t\t\t\n//\t\t\t\t\t\tLog.e(\"\", \"j = \" + j + \"\\t x = \" + x + \"\\t prev_x = \" + prev_x);\n\t\t\t\t\t}\n\t\t\t\t}\n//\t\t\t\tLog.e(\"\", \"==================================\");\n//\t\t\t\tLog.e(\"\", \"i = \" + i + \"\\tprev_x = \" + prev_x + \"\\t ,next_x * mode = \" + (next_x * mode));\n\t\t\t\tfloat x_bg = prev_x + next_x * mode;\n\t\t\t\tif(x_bg >= xLength){\n\t\t\t\t\tx_bg = xLength;\n\t\t\t\t}\n\t\t\t\tlineBgPath.lineTo(x_bg, 0);\n\t\t\t\tlineBgPath.lineTo(0, 0);\n\t\t\t\t\n\t\t\t\tarrLineBgPath.add(lineBgPath);\n\t\t\t}\n\t\t\t\n\t\t\tpBg.setColor(mLineGraphVO.getArrGraph().get(0).getColor());\n\t\t\tpBg.setAlpha(255);\n\t\t\tc.drawPath(arrLineBgPath.get(0), pBg);\n\t\t\tpBg.setXfermode(new PorterDuffXfermode(Mode.XOR));\n\t\t\tpBg.setColor(mLineGraphVO.getArrGraph().get(1).getColor());\n\t\t\tpBg.setAlpha(255);\n\t\t\tc.drawPath(arrLineBgPath.get(1), pBg);\n\t\t\tgraphCanvas.getCanvas().drawBitmap(b, 0, 0, null);\n\t\t}\n\t\t\n\t\t/**\n\t\t * draw X Mark\n\t\t */\n\t\tprivate void drawXMark(GraphCanvasWrapper graphCanvas) {\n\t\t\tfloat x = 0;\n\t\t\tfloat y = 0;\n\t\t\t\n\t\t\tfloat xGap = xLength/(mLineGraphVO.getArrGraph().get(0).getCoordinateArr().length-1);\n\t\t\tfor (int i = 0; i < mLineGraphVO.getArrGraph().get(0).getCoordinateArr().length; i++) {\n\t\t\t x = xGap * i;\n\t\t\t y = yLength * mLineGraphVO.getArrGraph().get(0).getCoordinateArr()[i]/mLineGraphVO.getMaxValue();\n\t\t\t \n\t\t\t graphCanvas.drawLine(x, 0, x, -10, pBaseLine);\n\t\t\t}\n\t\t}\n\t\t\n\t\t/**\n\t\t * draw Y Mark\n\t\t */\n\t\tprivate void drawYMark(GraphCanvasWrapper canvas) {\n\t\t\tfor (int i = 0; mLineGraphVO.getIncrement() * i <= mLineGraphVO.getMaxValue(); i++) {\n\t\t\t\t\n\t\t\t\tfloat y = yLength * mLineGraphVO.getIncrement() * i/mLineGraphVO.getMaxValue();\n\t\t\t\t\n\t\t\t\tcanvas.drawLine(0, y, -10, y, pBaseLine);\n\t\t\t}\n\t\t}\n\t\t\n\t\t/**\n\t\t * draw X Text\n\t\t */\n\t\tprivate void drawXText(GraphCanvasWrapper graphCanvas) {\n\t\t\tfloat x = 0;\n\t\t\tfloat y = 0;\n\t\t\t\n\t\t\tfloat xGap = xLength/(mLineGraphVO.getArrGraph().get(0).getCoordinateArr().length-1);\n\t\t\tfor (int i = 0; i < mLineGraphVO.getLegendArr().length; i++) {\n\t\t\t x = xGap * i;\n\t\t\t \n\t\t\t String text = mLineGraphVO.getLegendArr()[i];\n\t\t\t pMarkText.measureText(text);\n\t\t\t pMarkText.setTextSize(20);\n\t\t\t\t\tRect rect = new Rect();\n\t\t\t\t\tpMarkText.getTextBounds(text, 0, text.length(), rect);\n\t\t\t\t\t\n\t\t\t graphCanvas.drawText(text, x -(rect.width()/2), -(20 + rect.height()), pMarkText);\n\t\t\t}\n\t\t}\n\t\t\n\t\t/**\n\t\t * draw Y Text\n\t\t */\n\t\tprivate void drawYText(GraphCanvasWrapper graphCanvas) {\n\t\t\tfor (int i = 0; mLineGraphVO.getIncrement() * i <= mLineGraphVO.getMaxValue(); i++) {\n\t\t\t\t\n\t\t\t\tString mark = Float.toString(mLineGraphVO.getIncrement() * i);\n\t\t\t\tfloat y = yLength * mLineGraphVO.getIncrement() * i/mLineGraphVO.getMaxValue();\n\t\t\t\tpMarkText.measureText(mark);\n\t\t\t\tpMarkText.setTextSize(20);\n\t\t\t\tRect rect = new Rect();\n\t\t\t\tpMarkText.getTextBounds(mark, 0, mark.length(), rect);\n//\t\t\t\tLog.e(TAG, \"rect = height()\" + rect.height());\n//\t\t\t\tLog.e(TAG, \"rect = width()\" + rect.width());\n\t\t\t\tgraphCanvas.drawText(mark, -(rect.width() + 20), y-rect.height()/2, pMarkText);\n\t\t\t}\n\t\t}\n\t}\n}",
"public class GraphNameBox {\n\n\tpublic static final int DEFAULT_NAMEBOX_COLOR\t\t\t\t= Color.BLUE;\n\tpublic static final int DEFAULT_NAMEBOX_MARGINTOP \t\t\t= 100;\n\tpublic static final int DEFAULT_NAMEBOX_MARGINRIGHT \t\t= 100;\n\tpublic static final int DEFAULT_NAMEBOX_PADDING \t\t\t= 10;\n\tpublic static final int DEFAULT_NAMEBOX_TEXT_SIZE\t\t\t= 20;\n\tpublic static final int DEFAULT_NAMEBOX_TEXT_COLOR\t\t\t= Color.BLACK;\n\tpublic static final int DEFAULT_NAMEBOX_ICON_WIDTH \t\t\t= 30;\n\tpublic static final int DEFAULT_NAMEBOX_ICON_HEIGHT\t\t\t= 10;\n\tpublic static final int DEFAULT_NAMEBOX_TEXT_ICON_MARGIN \t= 10;\n\tpublic static final int DEFAULT_NAMEBOX_ICON_MARGIN \t\t= 10;\n\n\tprivate int nameboxColor\t \t\t\t= DEFAULT_NAMEBOX_COLOR;\n\tprivate int nameboxMarginTop \t\t\t= DEFAULT_NAMEBOX_MARGINTOP;\n\tprivate int nameboxMarginRight \t\t\t= DEFAULT_NAMEBOX_MARGINRIGHT;\n\tprivate int nameboxPadding \t\t\t\t= DEFAULT_NAMEBOX_PADDING;\n\tprivate int nameboxTextSize\t\t\t\t= DEFAULT_NAMEBOX_TEXT_SIZE;\n\tprivate int nameboxTextColor\t\t\t= DEFAULT_NAMEBOX_TEXT_COLOR;\n\tprivate int nameboxIconWidth \t\t\t= DEFAULT_NAMEBOX_ICON_WIDTH;\n\tprivate int nameboxIconHeight \t\t\t= DEFAULT_NAMEBOX_ICON_HEIGHT;\n\tprivate int nameboxTextIconMargin \t\t= DEFAULT_NAMEBOX_TEXT_ICON_MARGIN;\n\tprivate int nameboxIconMargin \t\t\t= DEFAULT_NAMEBOX_ICON_MARGIN;\n\t\n\tpublic GraphNameBox() {\n\t\t\n\t}\n\t\n\tpublic GraphNameBox(int nameboxColor, int nameboxMarginTop,\n\t\t\tint nameboxMarginRight, int nameboxPadding, int nameboxTextSize,\n\t\t\tint nameboxTextColor, int nameboxIconWidth, int nameboxIconHeight,\n\t\t\tint nameboxTextIconMargin, int nameboxIconMargin) {\n\t\tsuper();\n\t\tthis.nameboxColor = nameboxColor;\n\t\tthis.nameboxMarginTop = nameboxMarginTop;\n\t\tthis.nameboxMarginRight = nameboxMarginRight;\n\t\tthis.nameboxPadding = nameboxPadding;\n\t\tthis.nameboxTextSize = nameboxTextSize;\n\t\tthis.nameboxTextColor = nameboxTextColor;\n\t\tthis.nameboxIconWidth = nameboxIconWidth;\n\t\tthis.nameboxIconHeight = nameboxIconHeight;\n\t\tthis.nameboxTextIconMargin = nameboxTextIconMargin;\n\t\tthis.nameboxIconMargin = nameboxIconMargin;\n\t}\n\n\tpublic int getNameboxColor() {\n\t\treturn nameboxColor;\n\t}\n\n\tpublic void setNameboxColor(int nameboxColor) {\n\t\tthis.nameboxColor = nameboxColor;\n\t}\n\n\tpublic int getNameboxIconWidth() {\n\t\treturn nameboxIconWidth;\n\t}\n\n\tpublic void setNameboxIconWidth(int nameboxIconWidth) {\n\t\tthis.nameboxIconWidth = nameboxIconWidth;\n\t}\n\n\tpublic int getNameboxIconHeight() {\n\t\treturn nameboxIconHeight;\n\t}\n\n\tpublic void setNameboxIconHeight(int nameboxIconHeight) {\n\t\tthis.nameboxIconHeight = nameboxIconHeight;\n\t}\n\n\tpublic int getNameboxTextSize() {\n\t\treturn nameboxTextSize;\n\t}\n\n\tpublic void setNameboxTextSize(int nameboxTextSize) {\n\t\tthis.nameboxTextSize = nameboxTextSize;\n\t}\n\t\n\tpublic int getNameboxTextColor() {\n\t\treturn nameboxTextColor;\n\t}\n\n\tpublic void setNameboxTextColor(int nameboxTextColor) {\n\t\tthis.nameboxTextColor = nameboxTextColor;\n\t}\n\n\tpublic int getNameboxMarginTop() {\n\t\treturn nameboxMarginTop;\n\t}\n\n\tpublic void setNameboxMarginTop(int nameboxMarginTop) {\n\t\tthis.nameboxMarginTop = nameboxMarginTop;\n\t}\n\n\tpublic int getNameboxMarginRight() {\n\t\treturn nameboxMarginRight;\n\t}\n\n\tpublic void setNameboxMarginRight(int nameboxMarginRight) {\n\t\tthis.nameboxMarginRight = nameboxMarginRight;\n\t}\n\n\tpublic int getNameboxPadding() {\n\t\treturn nameboxPadding;\n\t}\n\n\tpublic void setNameboxPadding(int nameboxPadding) {\n\t\tthis.nameboxPadding = nameboxPadding;\n\t}\n\n\tpublic int getNameboxTextIconMargin() {\n\t\treturn nameboxTextIconMargin;\n\t}\n\n\tpublic void setNameboxTextIconMargin(int nameboxTextIconMargin) {\n\t\tthis.nameboxTextIconMargin = nameboxTextIconMargin;\n\t}\n\n\tpublic int getNameboxIconMargin() {\n\t\treturn nameboxIconMargin;\n\t}\n\n\tpublic void setNameboxIconMargin(int nameboxIconMargin) {\n\t\tthis.nameboxIconMargin = nameboxIconMargin;\n\t}\n}",
"public class LineGraph {\n\tprivate String name = null;\n\tprivate int color = Color.BLUE;\n\tprivate float[] coordinateArr = null;\n\tprivate int bitmapResource = -1;\n\t\n\tpublic LineGraph(String name, int color, float[] coordinateArr) {\n\t\tthis.name = name;\n\t\tthis.color = color;\n\t\tthis.setCoordinateArr(coordinateArr);\n\t}\n\t\n\tpublic LineGraph(String name, int color, float[] coordinateArr, int bitmapResource) {\n\t\tthis.name = name;\n\t\tthis.color = color;\n\t\tthis.setCoordinateArr(coordinateArr);\n\t\tthis.bitmapResource = bitmapResource;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\tpublic int getColor() {\n\t\treturn color;\n\t}\n\tpublic void setColor(int color) {\n\t\tthis.color = color;\n\t}\n\tpublic float[] getCoordinateArr() {\n\t\treturn coordinateArr;\n\t}\n\tpublic void setCoordinateArr(float[] coordinateArr) {\n\t\tthis.coordinateArr = coordinateArr;\n\t}\n\tpublic int getBitmapResource() {\n\t\treturn bitmapResource;\n\t}\n\tpublic void setBitmapResource(int bitmapResource) {\n\t\tthis.bitmapResource = bitmapResource;\n\t}\n}",
"public class LineGraphVO extends Graph{\n\t\n\t//max value\n\tprivate int maxValue \t\t= DEFAULT_MAX_VALUE;\n\n\t//increment\n\tprivate int increment \t\t= DEFAULT_INCREMENT;\n\t\n\t//animation\n\tprivate GraphAnimation animation \t= null;\n\t\n\tprivate String[] legendArr \t\t\t= null;\n\tprivate List<LineGraph> arrGraph \t= null;\n\t\n\tprivate int graphBG = -1;\n\t\n\tprivate boolean isDrawRegion \t\t= false;\n\t\n\tpublic LineGraphVO(String[] legendArr, List<LineGraph> arrGraph) {\n\t\tsuper();\n\t\tthis.setLegendArr(legendArr);\n\t\tthis.arrGraph = arrGraph;\n\t}\n\t\n\tpublic LineGraphVO(String[] legendArr, List<LineGraph> arrGraph, int graphBG) {\n\t\tsuper();\n\t\tthis.setLegendArr(legendArr);\n\t\tthis.arrGraph = arrGraph;\n\t\tthis.setGraphBG(graphBG);\n\t}\n\t\n\tpublic LineGraphVO(int paddingBottom, int paddingTop, int paddingLeft,\n\t\t\tint paddingRight, int marginTop, int marginRight, int maxValue,\n\t\t\tint increment, String[] legendArr, List<LineGraph> arrGraph) {\n\t\tsuper(paddingBottom, paddingTop, paddingLeft, paddingRight, marginTop, marginRight);\n\t\tthis.maxValue = maxValue;\n\t\tthis.increment = increment;\n\t\tthis.setLegendArr(legendArr);\n\t\tthis.arrGraph = arrGraph;\n\t}\n\t\n\tpublic LineGraphVO(int paddingBottom, int paddingTop, int paddingLeft,\n\t\t\tint paddingRight, int marginTop, int marginRight, int maxValue,\n\t\t\tint increment, String[] legendArr, List<LineGraph> arrGraph, int graphBG) {\n\t\tsuper(paddingBottom, paddingTop, paddingLeft, paddingRight, marginTop, marginRight);\n\t\tthis.maxValue = maxValue;\n\t\tthis.increment = increment;\n\t\tthis.setLegendArr(legendArr);\n\t\tthis.arrGraph = arrGraph;\n\t\tthis.setGraphBG(graphBG);\n\t}\n\t\n\tpublic int getMaxValue() {\n\t\treturn maxValue;\n\t}\n\n\tpublic void setMaxValue(int maxValue) {\n\t\tthis.maxValue = maxValue;\n\t}\n\n\tpublic int getIncrement() {\n\t\treturn increment;\n\t}\n\n\tpublic void setIncrement(int increment) {\n\t\tthis.increment = increment;\n\t}\n\t\n\tpublic String[] getLegendArr() {\n\t\treturn legendArr;\n\t}\n\n\tpublic void setLegendArr(String[] legendArr) {\n\t\tthis.legendArr = legendArr;\n\t}\n\t\n\tpublic List<LineGraph> getArrGraph() {\n\t\treturn arrGraph;\n\t}\n\n\tpublic void setArrGraph(List<LineGraph> arrGraph) {\n\t\tthis.arrGraph = arrGraph;\n\t}\n\n\tpublic int getGraphBG() {\n\t\treturn graphBG;\n\t}\n\n\tpublic void setGraphBG(int graphBG) {\n\t\tthis.graphBG = graphBG;\n\t}\n\n\tpublic GraphAnimation getAnimation() {\n\t\treturn animation;\n\t}\n\n\tpublic void setAnimation(GraphAnimation animation) {\n\t\tthis.animation = animation;\n\t}\n\n\tpublic boolean isDrawRegion() {\n\t\treturn isDrawRegion;\n\t}\n\n\tpublic void setDrawRegion(boolean isDrawRegion) {\n\t\tthis.isDrawRegion = isDrawRegion;\n\t}\n}"
] | import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.ViewGroup;
import com.handstudio.android.hzgrapherlib.animation.GraphAnimation;
import com.handstudio.android.hzgrapherlib.graphview.LineCompareGraphView;
import com.handstudio.android.hzgrapherlib.vo.GraphNameBox;
import com.handstudio.android.hzgrapherlib.vo.linegraph.LineGraph;
import com.handstudio.android.hzgrapherlib.vo.linegraph.LineGraphVO; | package com.handstudio.android.hzgrapher;
public class LineCompareGraphActivity extends Activity {
private ViewGroup layoutGraphView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_graph);
layoutGraphView = (ViewGroup) findViewById(R.id.layoutGraphView);
setLineCompareGraph();
}
private void setLineCompareGraph() {
//all setting
LineGraphVO vo = makeLineCompareGraphAllSetting();
//default setting
// LineGraphVO vo = makeLineCompareGraphDefaultSetting();
layoutGraphView.addView(new LineCompareGraphView(this, vo));
}
/**
* make simple line graph
* @return
*/
private LineGraphVO makeLineCompareGraphDefaultSetting() {
String[] legendArr = {"1","2","3","4","5"};
float[] graph1 = {500,100,300,200,100};
float[] graph2 = {000,100,200,100,200};
List<LineGraph> arrGraph = new ArrayList<LineGraph>();
arrGraph.add(new LineGraph("android", 0xaa66ff33, graph1));
arrGraph.add(new LineGraph("ios", 0xaa00ffff, graph2));
LineGraphVO vo = new LineGraphVO(legendArr, arrGraph);
return vo;
}
/**
* make line graph using options
* @return
*/
private LineGraphVO makeLineCompareGraphAllSetting() {
//BASIC LAYOUT SETTING
//padding
int paddingBottom = LineGraphVO.DEFAULT_PADDING;
int paddingTop = LineGraphVO.DEFAULT_PADDING;
int paddingLeft = LineGraphVO.DEFAULT_PADDING;
int paddingRight = LineGraphVO.DEFAULT_PADDING;
//graph margin
int marginTop = LineGraphVO.DEFAULT_MARGIN_TOP;
int marginRight = LineGraphVO.DEFAULT_MARGIN_RIGHT;
//max value
int maxValue = LineGraphVO.DEFAULT_MAX_VALUE;
//increment
int increment = LineGraphVO.DEFAULT_INCREMENT;
//GRAPH SETTING
String[] legendArr = {"1","2","3","4","5"};
float[] graph1 = {500,100,300,200,100};
float[] graph2 = {000,300,200,100,200};
List<LineGraph> arrGraph = new ArrayList<LineGraph>();
arrGraph.add(new LineGraph("android", 0xaa66ff33, graph1, R.drawable.ic_launcher));
arrGraph.add(new LineGraph("ios", 0xaa00ffff, graph2));
LineGraphVO vo = new LineGraphVO(
paddingBottom, paddingTop, paddingLeft, paddingRight,
marginTop, marginRight, maxValue, increment, legendArr, arrGraph);
//set animation | vo.setAnimation(new GraphAnimation(GraphAnimation.LINEAR_ANIMATION, GraphAnimation.DEFAULT_DURATION)); | 0 |
desht/ScrollingMenuSign | src/main/java/me/desht/scrollingmenusign/views/SMSSpoutView.java | [
"public class SMSException extends DHUtilsException {\n\n private static final long serialVersionUID = 1L;\n\n public SMSException(String message) {\n super(message);\n }\n\n}",
"public class SMSMenu extends Observable implements SMSPersistable, SMSUseLimitable, ConfigurationListener, Comparable<SMSMenu> {\n public static final String FAKE_SPACE = \"\\u203f\";\n\n public static final String AUTOSORT = \"autosort\";\n public static final String DEFAULT_CMD = \"defcmd\";\n public static final String OWNER = \"owner\";\n public static final String TITLE = \"title\";\n public static final String ACCESS = \"access\";\n public static final String REPORT_USES = \"report_uses\";\n public static final String GROUP = \"group\";\n\n private final String name;\n private final List<SMSMenuItem> items = new ArrayList<SMSMenuItem>();\n private final Map<String, Integer> itemMap = new HashMap<String, Integer>();\n private final SMSRemainingUses uses;\n private final AttributeCollection attributes; // menu attributes to be displayed and/or edited by players\n\n private String title; // cache colour-parsed version of the title attribute\n private UUID ownerId; // cache owner's UUID (could be null)\n private boolean autosave;\n private boolean inThaw;\n\n /**\n * Construct a new menu\n *\n * @param name Name of the menu\n * @param title Title of the menu\n * @param owner Owner of the menu\n * @throws SMSException If there is already a menu at this location\n * @deprecated use {@link SMSMenu(String,String,Player)} or {@link SMSMenu(String,String, org.bukkit.plugin.Plugin )}\n */\n @Deprecated\n public SMSMenu(String name, String title, String owner) {\n this.name = name;\n this.uses = new SMSRemainingUses(this);\n this.attributes = new AttributeCollection(this);\n registerAttributes();\n setAttribute(OWNER, owner == null ? ScrollingMenuSign.CONSOLE_OWNER : owner);\n ownerId = ScrollingMenuSign.CONSOLE_UUID;\n setAttribute(TITLE, title);\n autosave = true;\n }\n\n /**\n * Construct a new menu\n *\n * @param name Name of the menu\n * @param title Title of the menu\n * @param owner Owner of the menu\n * @throws SMSException If there is already a menu at this location\n */\n public SMSMenu(String name, String title, Player owner) {\n this.name = name;\n this.uses = new SMSRemainingUses(this);\n this.attributes = new AttributeCollection(this);\n registerAttributes();\n setAttribute(OWNER, owner == null ? ScrollingMenuSign.CONSOLE_OWNER : owner.getName());\n ownerId = owner == null ? ScrollingMenuSign.CONSOLE_UUID : owner.getUniqueId();\n setAttribute(TITLE, title);\n autosave = true;\n }\n\n /**\n * Construct a new menu\n *\n * @param name Name of the menu\n * @param title Title of the menu\n * @param owner Owner of the menu\n * @throws SMSException If there is already a menu at this location\n */\n public SMSMenu(String name, String title, Plugin owner) {\n this.name = name;\n this.uses = new SMSRemainingUses(this);\n this.attributes = new AttributeCollection(this);\n registerAttributes();\n setAttribute(OWNER, owner == null ? ScrollingMenuSign.CONSOLE_OWNER : \"[\" + owner.getName() + \"]\");\n ownerId = ScrollingMenuSign.CONSOLE_UUID;\n setAttribute(TITLE, title);\n autosave = true;\n }\n\n /**\n * Construct a new menu from a frozen configuration object.\n *\n * @param node A ConfigurationSection containing the menu's properties\n * @throws SMSException If there is already a menu at this location\n */\n @SuppressWarnings(\"unchecked\")\n public SMSMenu(ConfigurationSection node) {\n SMSPersistence.mustHaveField(node, \"name\");\n SMSPersistence.mustHaveField(node, \"title\");\n SMSPersistence.mustHaveField(node, \"owner\");\n\n inThaw = true;\n\n this.name = node.getString(\"name\");\n this.uses = new SMSRemainingUses(this, node.getConfigurationSection(\"usesRemaining\"));\n this.attributes = new AttributeCollection(this);\n registerAttributes();\n String id = node.getString(\"owner_id\");\n if (id != null && !id.isEmpty()) {\n this.ownerId = UUID.fromString(id);\n } else {\n this.ownerId = ScrollingMenuSign.CONSOLE_UUID;\n }\n\n // migration of group -> owner_group access in 2.4.0\n if (!node.contains(\"group\") && node.contains(ACCESS) && node.getString(ACCESS).equals(\"GROUP\")) {\n LogUtils.info(\"menu \" + name + \": migrate GROUP -> OWNER_GROUP access\");\n node.set(\"access\", \"OWNER_GROUP\");\n }\n\n for (String k : node.getKeys(false)) {\n if (!node.isConfigurationSection(k) && attributes.hasAttribute(k)) {\n setAttribute(k, node.getString(k));\n }\n }\n\n List<Map<String, Object>> items = (List<Map<String, Object>>) node.getList(\"items\");\n if (items != null) {\n for (Map<String, Object> item : items) {\n MemoryConfiguration itemNode = new MemoryConfiguration();\n // need to expand here because the item may contain a usesRemaining object - item could contain a nested map\n SMSPersistence.expandMapIntoConfig(itemNode, item);\n SMSMenuItem menuItem = new SMSMenuItem(this, itemNode);\n SMSMenuItem actual = menuItem.uniqueItem();\n if (!actual.getLabel().equals(menuItem.getLabel()))\n LogUtils.warning(\"Menu '\" + getName() + \"': duplicate item '\" + menuItem.getLabelStripped() + \"' renamed to '\" + actual.getLabelStripped() + \"'\");\n addItem(actual);\n }\n }\n\n inThaw = false;\n autosave = true;\n }\n\n public void setAttribute(String k, String val) {\n SMSValidate.isTrue(attributes.contains(k), \"No such view attribute: \" + k);\n attributes.set(k, val);\n }\n\n private void registerAttributes() {\n attributes.registerAttribute(AUTOSORT, false, \"Always keep the menu sorted?\");\n attributes.registerAttribute(DEFAULT_CMD, \"\", \"Default command to run if item has no command\");\n attributes.registerAttribute(OWNER, \"\", \"Player who owns this menu\");\n attributes.registerAttribute(GROUP, \"\", \"Permission group for this menu\");\n attributes.registerAttribute(TITLE, \"\", \"The menu's displayed title\");\n attributes.registerAttribute(ACCESS, SMSAccessRights.ANY, \"Who may use this menu\");\n attributes.registerAttribute(REPORT_USES, true, \"Tell the player when remaining uses have changed?\");\n }\n\n public Map<String, Object> freeze() {\n HashMap<String, Object> map = new HashMap<String, Object>();\n\n List<Map<String, Object>> l = new ArrayList<Map<String, Object>>();\n for (SMSMenuItem item : items) {\n l.add(item.freeze());\n }\n for (String key : attributes.listAttributeKeys(false)) {\n if (key.equals(TITLE)) {\n map.put(key, SMSUtil.escape(attributes.get(key).toString()));\n } else {\n map.put(key, attributes.get(key).toString());\n }\n }\n map.put(\"name\", getName());\n map.put(\"items\", l);\n map.put(\"usesRemaining\", uses.freeze());\n map.put(\"owner_id\", getOwnerId() == null ? \"\" : getOwnerId().toString());\n\n return map;\n }\n\n public AttributeCollection getAttributes() {\n return attributes;\n }\n\n /**\n * Get the menu's unique name\n *\n * @return Name of this menu\n */\n public String getName() {\n return name;\n }\n\n /**\n * Get the menu's title string\n *\n * @return The title string\n */\n public String getTitle() {\n return title;\n }\n\n /**\n * Set the menu's title string\n *\n * @param newTitle The new title string\n */\n public void setTitle(String newTitle) {\n attributes.set(TITLE, newTitle);\n }\n\n /**\n * Get the menu's owner string\n *\n * @return Name of the menu's owner\n */\n public String getOwner() {\n return attributes.get(OWNER).toString();\n }\n\n /**\n * Set the menu's owner string.\n *\n * @param owner Name of the menu's owner\n */\n public void setOwner(String owner) {\n attributes.set(OWNER, owner);\n }\n\n /**\n * Get the menu's permission group.\n *\n * @return the group\n */\n public String getGroup() {\n return attributes.get(GROUP).toString();\n }\n\n /**\n * Set the menu's permission group.\n *\n * @param group Name of the menu's group\n */\n public void setGroup(String group) {\n attributes.set(GROUP, group);\n }\n\n public UUID getOwnerId() {\n return ownerId;\n }\n\n public void setOwnerId(UUID ownerId) {\n this.ownerId = ownerId;\n }\n\n /**\n * Get the menu's autosave status - will menus be automatically saved to disk when modified?\n *\n * @return true or false\n */\n public boolean isAutosave() {\n return autosave;\n }\n\n /**\n * Set the menu's autosave status - will menus be automatically saved to disk when modified?\n *\n * @param autosave true or false\n * @return the previous autosave status - true or false\n */\n public boolean setAutosave(boolean autosave) {\n boolean prevAutosave = this.autosave;\n this.autosave = autosave;\n if (autosave) {\n autosave();\n }\n return prevAutosave;\n }\n\n /**\n * Get the menu's autosort status - will menu items be automatically sorted when added?\n *\n * @return true or false\n */\n public boolean isAutosort() {\n return (Boolean) attributes.get(AUTOSORT);\n }\n\n /**\n * Set the menu's autosort status - will menu items be automatically sorted when added?\n *\n * @param autosort true or false\n */\n public void setAutosort(boolean autosort) {\n setAttribute(AUTOSORT, Boolean.toString(autosort));\n }\n\n /**\n * Get the menu's default command. This command will be used if the menu item\n * being executed has a missing command.\n *\n * @return The default command string\n */\n public String getDefaultCommand() {\n return attributes.get(DEFAULT_CMD).toString();\n }\n\n /**\n * Set the menu's default command. This command will be used if the menu item\n * being executed has a missing command.\n *\n * @param defaultCommand the default command to set\n */\n public void setDefaultCommand(String defaultCommand) {\n setAttribute(DEFAULT_CMD, defaultCommand);\n }\n\n /**\n * Get a list of all the items in the menu\n *\n * @return A list of the items\n */\n public List<SMSMenuItem> getItems() {\n return items;\n }\n\n /**\n * Get the number of items in the menu\n *\n * @return The number of items\n */\n public int getItemCount() {\n return items.size();\n }\n\n /**\n * Get the item at the given numeric index\n *\n * @param index 1-based numeric index\n * @return The menu item at that index or null if out of range and mustExist is false\n * @throws SMSException if the index is out of range and mustExist is true\n */\n public SMSMenuItem getItemAt(int index, boolean mustExist) {\n if (index < 1 || index > items.size()) {\n if (mustExist) {\n throw new SMSException(\"Index \" + index + \" out of range.\");\n } else {\n return null;\n }\n } else {\n return items.get(index - 1);\n }\n }\n\n /**\n * Get the item at the given numeric index.\n *\n * @param index 1-based numeric index\n * @return the menu item at that index or null if out of range\n */\n public SMSMenuItem getItemAt(int index) {\n return getItemAt(index, false);\n }\n\n /**\n * Get the menu item matching the given label.\n *\n * @param wanted the label to match (case-insensitive)\n * @return the menu item with that label, or null if no matching item\n */\n public SMSMenuItem getItem(String wanted) {\n return getItem(wanted, false);\n }\n\n /**\n * Get the menu item matching the given label\n *\n * @param wanted The label to match (case-insensitive)\n * @param mustExist If true and the label is not in the menu, throw an exception\n * @return The menu item with that label, or null if no matching item and mustExist is false\n * @throws SMSException if no matching item and mustExist is true\n */\n public SMSMenuItem getItem(String wanted, boolean mustExist) {\n if (items.size() != itemMap.size())\n rebuildItemMap(); // workaround for Heroes 1.4.8 which calls menu.getItems().clear\n\n Integer idx = itemMap.get(ChatColor.stripColor(wanted.replace(FAKE_SPACE, \" \")));\n if (idx == null) {\n if (mustExist) {\n throw new SMSException(\"No such item '\" + wanted + \"' in menu \" + getName());\n } else {\n return null;\n }\n }\n return getItemAt(idx);\n }\n\n /**\n * Get the index of the item matching the given label\n *\n * @param wanted The label to match (case-insensitive)\n * @return 1-based item index, or -1 if no matching item\n */\n public int indexOfItem(String wanted) {\n if (items.size() != itemMap.size())\n rebuildItemMap(); // workaround for Heroes 1.4.8 which calls menu.getItems().clear\n\n int index = -1;\n try {\n index = Integer.parseInt(wanted);\n } catch (NumberFormatException e) {\n String l = ChatColor.stripColor(wanted.replace(FAKE_SPACE, \" \"));\n if (itemMap.containsKey(l))\n index = itemMap.get(l);\n }\n return index;\n }\n\n /**\n * Append a new item to the menu\n *\n * @param label Label of the item to add\n * @param command Command to be run when the item is selected\n * @param message Feedback text to be shown when the item is selected\n * @deprecated use {@link #addItem(SMSMenuItem)}\n */\n @Deprecated\n public void addItem(String label, String command, String message) {\n addItem(new SMSMenuItem(this, label, command, message));\n }\n\n /**\n * Append a new item to the menu\n *\n * @param item The item to be added\n */\n public void addItem(SMSMenuItem item) {\n insertItem(items.size() + 1, item);\n }\n\n /**\n * Insert new item in the menu, at the given position.\n *\n * @param pos the position to insert at\n * @param label label of the new item\n * @param command command to be run\n * @param message feedback message text\n * @deprecated use {@link #insertItem(int, SMSMenuItem)}\n */\n @Deprecated\n public void insertItem(int pos, String label, String command, String message) {\n insertItem(pos, new SMSMenuItem(this, label, command, message));\n }\n\n /**\n * Insert a new item in the menu, at the given position.\n *\n * @param item The item to insert\n * @param pos The position to insert (1-based index)\n */\n public void insertItem(int pos, SMSMenuItem item) {\n if (items.size() != itemMap.size())\n rebuildItemMap(); // workaround for Heroes 1.4.8 which calls menu.getItems().clear\n\n if (item == null)\n throw new NullPointerException();\n String l = item.getLabelStripped();\n if (itemMap.containsKey(l)) {\n throw new SMSException(\"Duplicate label '\" + l + \"' not allowed in menu '\" + getName() + \"'.\");\n }\n\n if (pos > items.size()) {\n items.add(item);\n itemMap.put(l, items.size());\n } else {\n items.add(pos - 1, item);\n rebuildItemMap();\n }\n\n if (isAutosort()) {\n Collections.sort(items);\n if (pos <= items.size()) rebuildItemMap();\n }\n\n setChanged();\n autosave();\n }\n\n /**\n * Replace an existing menu item. The label must already be present in the menu,\n * or an exception will be thrown.\n *\n * @param label Label of the menu item\n * @param command The command to be run\n * @param message The feedback message\n * @throws SMSException if the label isn't present in the menu\n * @deprecated use {@link #replaceItem(SMSMenuItem)}\n */\n @Deprecated\n public void replaceItem(String label, String command, String message) {\n replaceItem(new SMSMenuItem(this, label, command, message));\n }\n\n /**\n * Replace an existing menu item. The new item's label must already be present in\n * the menu.\n *\n * @param item the replacement menu item\n * @throws SMSException if the new item's label isn't present in the menu\n */\n public void replaceItem(SMSMenuItem item) {\n if (items.size() != itemMap.size())\n rebuildItemMap(); // workaround for Heroes 1.4.8 which calls menu.getItems().clear\n\n String l = item.getLabelStripped();\n if (!itemMap.containsKey(l)) {\n throw new SMSException(\"Label '\" + l + \"' is not in the menu.\");\n }\n int idx = itemMap.get(l);\n items.set(idx - 1, item);\n itemMap.put(l, idx);\n\n setChanged();\n autosave();\n }\n\n /**\n * Replace the menu item at the given 1-based position. The new label must not already be\n * present in the menu or an exception will be thrown - duplicates are not allowed.\n *\n * @param pos the position to replace at\n * @param label label of the replacement item\n * @param command command for the replacement item\n * @param message feedback message text for the replacement item\n * @deprecated use {@link #replaceItem(int, SMSMenuItem)}\n */\n @Deprecated\n public void replaceItem(int pos, String label, String command, String message) {\n replaceItem(pos, new SMSMenuItem(this, label, command, message));\n }\n\n /**\n * Replace the menu item at the given 1-based position. The new label must not already be\n * present in the menu or an exception will be thrown - duplicates are not allowed.\n *\n * @param pos the position to replace at\n * @param item the new menu item\n * @throws SMSException if the new menu item's label already exists in this menu\n */\n public void replaceItem(int pos, SMSMenuItem item) {\n if (items.size() != itemMap.size())\n rebuildItemMap(); // workaround for Heroes 1.4.8 which calls menu.getItems().clear\n\n String l = item.getLabelStripped();\n if (pos < 1 || pos > items.size()) {\n throw new SMSException(\"Index \" + pos + \" out of range.\");\n }\n if (itemMap.containsKey(l) && pos != itemMap.get(l)) {\n throw new SMSException(\"Duplicate label '\" + l + \"' not allowed in menu '\" + getName() + \"'.\");\n }\n itemMap.remove(items.get(pos - 1).getLabelStripped());\n items.set(pos - 1, item);\n itemMap.put(l, pos);\n\n setChanged();\n autosave();\n }\n\n /**\n * Rebuild the label->index mapping for the menu. Needed if the menu order changes\n * (insertion, removal, sorting...)\n */\n private void rebuildItemMap() {\n itemMap.clear();\n for (int i = 0; i < items.size(); i++) {\n itemMap.put(items.get(i).getLabelStripped(), i + 1);\n }\n }\n\n /**\n * Sort the menu's items by label text - see {@link SMSMenuItem#compareTo(SMSMenuItem)}\n */\n public void sortItems() {\n Collections.sort(items);\n rebuildItemMap();\n setChanged();\n autosave();\n }\n\n /**\n * Remove an item from the menu by matching label. If the label string is\n * just an integer value, remove the item at that 1-based numeric index.\n *\n * @param indexStr The label to search for and remove\n * @throws IllegalArgumentException if the label does not exist in the menu\n */\n public void removeItem(String indexStr) {\n if (StringUtils.isNumeric(indexStr)) {\n removeItem(Integer.parseInt(indexStr));\n } else {\n String stripped = ChatColor.stripColor(indexStr);\n SMSValidate.isTrue(itemMap.containsKey(stripped), \"No such label '\" + indexStr + \"' in menu '\" + getName() + \"'.\");\n removeItem(itemMap.get(stripped));\n }\n }\n\n /**\n * Remove an item from the menu by numeric index\n *\n * @param index 1-based index of the item to remove\n */\n public void removeItem(int index) {\n // Java lists are 0-indexed, our signs are 1-indexed\n items.remove(index - 1);\n rebuildItemMap();\n setChanged();\n autosave();\n }\n\n /**\n * Remove all items from a menu\n */\n public void removeAllItems() {\n items.clear();\n itemMap.clear();\n setChanged();\n autosave();\n }\n\n /**\n * Permanently delete a menu, dereferencing the object and removing saved data from disk.\n */\n void deletePermanent() {\n try {\n setChanged();\n notifyObservers(new MenuDeleteAction(null, true));\n ScrollingMenuSign.getInstance().getMenuManager().unregisterMenu(getName());\n SMSPersistence.unPersist(this);\n } catch (SMSException e) {\n // Should not get here\n LogUtils.warning(\"Impossible: deletePermanent got SMSException?\" + e.getMessage());\n }\n }\n\n /**\n * Temporarily delete a menu. The menu object is dereferenced but saved menu data is not\n * deleted from disk.\n */\n void deleteTemporary() {\n try {\n setChanged();\n notifyObservers(new MenuDeleteAction(null, false));\n ScrollingMenuSign.getInstance().getMenuManager().unregisterMenu(getName());\n } catch (SMSException e) {\n // Should not get here\n LogUtils.warning(\"Impossible: deleteTemporary got SMSException? \" + e.getMessage());\n }\n }\n\n public void autosave() {\n // we only save menus which have been registered via SMSMenu.addMenu()\n if (isAutosave() && ScrollingMenuSign.getInstance().getMenuManager().checkForMenu(getName())) {\n SMSPersistence.save(this);\n }\n }\n\n /**\n * Check if the given player has access right for this menu.\n *\n * @param player The player to check\n * @return True if the player may use this view, false if not\n */\n public boolean hasOwnerPermission(Player player) {\n SMSAccessRights access = (SMSAccessRights) getAttributes().get(ACCESS);\n return access.isAllowedToUse(player, ownerId, getOwner(), getGroup());\n }\n\n /**\n * Get the usage limit details for this menu.\n *\n * @return The usage limit details\n */\n public SMSRemainingUses getUseLimits() {\n return uses;\n }\n\n @Override\n public String getLimitableName() {\n return getName();\n }\n\n /**\n * Returns a printable representation of the number of uses remaining for this item.\n *\n * @return Formatted usage information\n */\n String formatUses() {\n return uses.toString();\n }\n\n /**\n * Returns a printable representation of the number of uses remaining for this item, for the given player.\n *\n * @param sender Command sender to retrieve the usage information for\n * @return Formatted usage information\n */\n @Override\n public String formatUses(CommandSender sender) {\n if (sender instanceof Player) {\n return uses.toString((Player) sender);\n } else {\n return formatUses();\n }\n }\n\n @Override\n public File getSaveFolder() {\n return DirectoryStructure.getMenusFolder();\n }\n\n @Override\n public String getDescription() {\n return \"menu\";\n }\n\n @Override\n public Object onConfigurationValidate(ConfigurationManager configurationManager, String key, Object oldVal, Object newVal) {\n if (key.equals(ACCESS)) {\n SMSAccessRights access = (SMSAccessRights) newVal;\n if (access != SMSAccessRights.ANY && ownerId == null && !inThaw) {\n throw new SMSException(\"View must be owned by a player to change access control to \" + access);\n } else if (access == SMSAccessRights.GROUP && ScrollingMenuSign.permission == null) {\n throw new SMSException(\"Cannot use GROUP access control (no permission group support available)\");\n }\n } else if (key.equals(TITLE)) {\n return SMSUtil.unEscape(newVal.toString());\n } else if (key.equals(OWNER) && newVal.toString().equals(\"&console\")) {\n // migration of owner field from pre-2.0.0: \"&console\" => \"[console]\"\n return ScrollingMenuSign.CONSOLE_OWNER;\n }\n\n return newVal;\n }\n\n @Override\n public void onConfigurationChanged(ConfigurationManager configurationManager, String key, Object oldVal, Object newVal) {\n if (key.equals(AUTOSORT) && (Boolean) newVal) {\n sortItems();\n } else if (key.equals(TITLE)) {\n title = newVal.toString();\n setChanged();\n notifyObservers(new TitleAction(null, oldVal.toString(), newVal.toString()));\n } else if (key.equals(OWNER) && !inThaw) {\n final String owner = newVal.toString();\n if (owner.isEmpty() || owner.equals(ScrollingMenuSign.CONSOLE_OWNER)) {\n ownerId = ScrollingMenuSign.CONSOLE_UUID;\n } else if (MiscUtil.looksLikeUUID(owner)) {\n ownerId = UUID.fromString(owner);\n String name = Bukkit.getOfflinePlayer(ownerId).getName();\n setAttribute(OWNER, name == null ? \"?\" : name);\n } else if (!owner.equals(\"?\")) {\n @SuppressWarnings(\"deprecation\") Player p = Bukkit.getPlayer(owner);\n if (p != null) {\n ownerId = p.getUniqueId();\n } else {\n updateOwnerAsync(owner);\n }\n }\n }\n\n autosave();\n }\n\n private void updateOwnerAsync(final String owner) {\n final UUIDFetcher uf = new UUIDFetcher(Arrays.asList(owner));\n Bukkit.getScheduler().runTaskAsynchronously(ScrollingMenuSign.getInstance(), new Runnable() {\n @Override\n public void run() {\n try {\n Map<String,UUID> res = uf.call();\n if (res.containsKey(owner)) {\n ownerId = res.get(owner);\n } else {\n LogUtils.warning(\"Menu [\" + getName() + \"]: no known UUID for player: \" + owner);\n ownerId = ScrollingMenuSign.CONSOLE_UUID;\n }\n } catch (Exception e) {\n LogUtils.warning(\"Menu [\" + getName() + \"]: can't retrieve UUID for player: \" + owner + \": \" + e.getMessage());\n }\n }\n });\n }\n\n /**\n * Check if this menu is owned by the given player.\n *\n * @param player the player to check\n * @return true if the menu is owned by the given player, false otherwise\n */\n public boolean isOwnedBy(Player player) {\n return player.getUniqueId().equals(ownerId);\n }\n\n /**\n * Require that the given command sender is allowed to modify this menu, and throw a SMSException if not.\n *\n * @param sender The command sender to check\n */\n public void ensureAllowedToModify(CommandSender sender) {\n if (sender instanceof Player) {\n Player player = (Player) sender;\n if (!isOwnedBy(player) && !PermissionUtils.isAllowedTo(player, \"scrollingmenusign.edit.any\")) {\n throw new SMSException(\"You don't have permission to modify that menu.\");\n }\n }\n }\n\n @Override\n public int compareTo(SMSMenu o) {\n return getName().compareTo(o.getName());\n }\n\n public void forceUpdate(ViewUpdateAction action) {\n setChanged();\n notifyObservers(action);\n }\n}",
"public class ScrollingMenuSign extends JavaPlugin implements ConfigurationListener {\n\n public static final int BLOCK_TARGET_DIST = 4;\n public static final String CONSOLE_OWNER = \"[console]\";\n public static final UUID CONSOLE_UUID = new UUID(0, 0);\n\n private static ScrollingMenuSign instance = null;\n\n public static Economy economy = null;\n public static Permission permission = null;\n\n private final CommandManager cmds = new CommandManager(this);\n private final CommandletManager cmdlets = new CommandletManager(this);\n private final ViewManager viewManager = new ViewManager(this);\n private final LocationManager locationManager = new LocationManager();\n private final VariablesManager variablesManager = new VariablesManager(this);\n private final MenuManager menuManager = new MenuManager(this);\n private final SMSHandlerImpl handler = new SMSHandlerImpl(this);\n private final ConfigCache configCache = new ConfigCache();\n\n private boolean spoutEnabled = false;\n\n private ConfigurationManager configManager;\n\n public final ResponseHandler responseHandler = new ResponseHandler(this);\n private boolean protocolLibEnabled = false;\n private MetaFaker faker;\n private boolean vaultLegacyMode = false;\n private boolean holoAPIEnabled;\n\n @Override\n public void onLoad() {\n ConfigurationSerialization.registerClass(PersistableLocation.class);\n }\n\n @Override\n public void onEnable() {\n setInstance(this);\n\n LogUtils.init(this);\n\n DirectoryStructure.setupDirectoryStructure();\n\n configManager = new ConfigurationManager(this, this);\n configManager.setPrefix(\"sms\");\n\n configCleanup();\n\n configCache.processConfig(getConfig());\n\n MiscUtil.init(this);\n MiscUtil.setColouredConsole(getConfig().getBoolean(\"sms.coloured_console\"));\n\n Debugger.getInstance().setPrefix(\"[SMS] \");\n Debugger.getInstance().setLevel(getConfig().getInt(\"sms.debug_level\"));\n Debugger.getInstance().setTarget(getServer().getConsoleSender());\n\n PluginManager pm = getServer().getPluginManager();\n setupSpout(pm);\n setupVault(pm);\n setupProtocolLib(pm);\n setupHoloAPI(pm);\n if (protocolLibEnabled) {\n ItemGlow.init(this);\n setupItemMetaFaker();\n }\n\n setupCustomFonts();\n\n new SMSPlayerListener(this);\n new SMSBlockListener(this);\n new SMSEntityListener(this);\n new SMSWorldListener(this);\n if (spoutEnabled) {\n new SMSSpoutKeyListener(this);\n }\n\n registerCommands();\n registerCommandlets();\n\n MessagePager.setPageCmd(\"/sms page [#|n|p]\");\n MessagePager.setDefaultPageSize(getConfig().getInt(\"sms.pager.lines\", 0));\n\n SMSScrollableView.setDefaultScrollType(SMSScrollableView.ScrollType.valueOf(getConfig().getString(\"sms.scroll_type\").toUpperCase()));\n\n loadPersistedData();\n variablesManager.checkForUUIDMigration();\n\n if (spoutEnabled) {\n SpoutUtils.precacheTextures();\n }\n\n setupMetrics();\n\n Debugger.getInstance().debug(getDescription().getName() + \" version \" + getDescription().getVersion() + \" is enabled!\");\n\n UUIDMigration.migrateToUUID(this);\n }\n\n @Override\n public void onDisable() {\n SMSPersistence.saveMenusAndViews();\n SMSPersistence.saveMacros();\n SMSPersistence.saveVariables();\n for (SMSMenu menu : getMenuManager().listMenus()) {\n // this also deletes all the menu's views...\n menu.deleteTemporary();\n }\n for (SMSMacro macro : SMSMacro.listMacros()) {\n macro.deleteTemporary();\n }\n\n if (faker != null) {\n faker.shutdown();\n }\n\n economy = null;\n permission = null;\n setInstance(null);\n\n Debugger.getInstance().debug(getDescription().getName() + \" version \" + getDescription().getVersion() + \" is disabled!\");\n }\n\n @Override\n public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {\n return cmds.dispatch(sender, command, label, args);\n }\n\n @Override\n public List<String> onTabComplete(CommandSender sender, Command command, String label, String[] args) {\n return cmds.onTabComplete(sender, command, label, args);\n }\n\n public SMSHandler getHandler() {\n return handler;\n }\n\n public boolean isSpoutEnabled() {\n return spoutEnabled;\n }\n\n public boolean isProtocolLibEnabled() {\n return protocolLibEnabled;\n }\n\n public boolean isHoloAPIEnabled() {\n return holoAPIEnabled;\n }\n\n public static ScrollingMenuSign getInstance() {\n return instance;\n }\n\n public CommandletManager getCommandletManager() {\n return cmdlets;\n }\n\n public ConfigurationManager getConfigManager() {\n return configManager;\n }\n\n /**\n * @return the viewManager\n */\n public ViewManager getViewManager() {\n return viewManager;\n }\n\n /**\n * @return the locationManager\n */\n public LocationManager getLocationManager() {\n return locationManager;\n }\n\n private void setupMetrics() {\n if (!getConfig().getBoolean(\"sms.mcstats\")) {\n return;\n }\n\n try {\n Metrics metrics = new Metrics(this);\n\n Graph graphM = metrics.createGraph(\"Menu/View/Macro count\");\n graphM.addPlotter(new Plotter(\"Menus\") {\n @Override\n public int getValue() {\n return getMenuManager().listMenus().size();\n }\n });\n graphM.addPlotter(new Plotter(\"Views\") {\n @Override\n public int getValue() {\n return viewManager.listViews().size();\n }\n });\n graphM.addPlotter(new Plotter(\"Macros\") {\n @Override\n public int getValue() {\n return SMSMacro.listMacros().size();\n }\n });\n\n Graph graphV = metrics.createGraph(\"View Types\");\n for (final Entry<String, Integer> e : viewManager.getViewCounts().entrySet()) {\n graphV.addPlotter(new Plotter(e.getKey()) {\n @Override\n public int getValue() {\n return e.getValue();\n }\n });\n }\n metrics.start();\n } catch (IOException e) {\n LogUtils.warning(\"Can't submit metrics data: \" + e.getMessage());\n }\n }\n\n private static void setInstance(ScrollingMenuSign plugin) {\n instance = plugin;\n }\n\n private void setupHoloAPI(PluginManager pm) {\n Plugin holoAPI = pm.getPlugin(\"HoloAPI\");\n if (holoAPI != null && holoAPI.isEnabled()) {\n holoAPIEnabled = true;\n Debugger.getInstance().debug(\"Hooked HoloAPI v\" + holoAPI.getDescription().getVersion());\n }\n }\n\n private void setupSpout(PluginManager pm) {\n Plugin spout = pm.getPlugin(\"Spout\");\n if (spout != null && spout.isEnabled()) {\n spoutEnabled = true;\n Debugger.getInstance().debug(\"Hooked Spout v\" + spout.getDescription().getVersion());\n }\n }\n\n private void setupVault(PluginManager pm) {\n Plugin vault = pm.getPlugin(\"Vault\");\n if (vault != null && vault.isEnabled()) {\n int ver = PluginVersionChecker.getRelease(vault.getDescription().getVersion());\n Debugger.getInstance().debug(\"Hooked Vault v\" + vault.getDescription().getVersion());\n vaultLegacyMode = ver < 1003000; // Vault 1.3.0\n if (vaultLegacyMode) {\n LogUtils.warning(\"Detected an older version of Vault. Proper UUID functionality requires Vault 1.4.1 or later.\");\n }\n setupEconomy();\n setupPermission();\n } else {\n LogUtils.warning(\"Vault not loaded: no economy command costs & no permission group support\");\n }\n }\n\n private void setupEconomy() {\n RegisteredServiceProvider<Economy> economyProvider = getServer().getServicesManager().getRegistration(Economy.class);\n economy = economyProvider.getProvider();\n if (economyProvider == null) {\n LogUtils.warning(\"No economy plugin detected - economy command costs not available\");\n }\n }\n\n private void setupPermission() {\n RegisteredServiceProvider<Permission> permissionProvider = getServer().getServicesManager().getRegistration(Permission.class);\n permission = permissionProvider.getProvider();\n if (permission == null) {\n LogUtils.warning(\"No permissions plugin detected - no permission group support\");\n }\n }\n\n public boolean isVaultLegacyMode() {\n return vaultLegacyMode;\n }\n\n private void setupProtocolLib(PluginManager pm) {\n Plugin pLib = pm.getPlugin(\"ProtocolLib\");\n if (pLib != null && pLib instanceof ProtocolLibrary && pLib.isEnabled()) {\n protocolLibEnabled = true;\n Debugger.getInstance().debug(\"Hooked ProtocolLib v\" + pLib.getDescription().getVersion());\n }\n }\n\n private void setupItemMetaFaker() {\n faker = new MetaFaker(this, new MetadataFilter() {\n @Override\n public ItemMeta filter(ItemMeta itemMeta, Player player) {\n if (player.getGameMode() == GameMode.CREATIVE) {\n // messing with item meta in creative mode can have unwanted consequences\n return null;\n }\n if (!ActiveItem.isActiveItem(itemMeta)) {\n String[] f = PopupItem.getPopupItemFields(itemMeta);\n if (f == null) {\n return null;\n }\n }\n // strip the last line from the lore for active items & popup items\n List<String> newLore = new ArrayList<String>(itemMeta.getLore());\n newLore.remove(newLore.size() - 1);\n ItemMeta newMeta = itemMeta.clone();\n newMeta.setLore(newLore);\n return newMeta;\n }\n });\n }\n\n private void registerCommands() {\n cmds.registerCommand(new AddItemCommand());\n cmds.registerCommand(new AddMacroCommand());\n cmds.registerCommand(new AddViewCommand());\n cmds.registerCommand(new CreateMenuCommand());\n cmds.registerCommand(new DeleteMenuCommand());\n cmds.registerCommand(new EditMenuCommand());\n cmds.registerCommand(new FontCommand());\n cmds.registerCommand(new GetConfigCommand());\n cmds.registerCommand(new GiveCommand());\n cmds.registerCommand(new ItemUseCommand());\n cmds.registerCommand(new ListMacroCommand());\n cmds.registerCommand(new ListMenusCommand());\n cmds.registerCommand(new MenuCommand());\n cmds.registerCommand(new PageCommand());\n cmds.registerCommand(new ReloadCommand());\n cmds.registerCommand(new RemoveItemCommand());\n cmds.registerCommand(new RemoveMacroCommand());\n cmds.registerCommand(new RemoveViewCommand());\n cmds.registerCommand(new RepaintCommand());\n cmds.registerCommand(new SaveCommand());\n cmds.registerCommand(new SetConfigCommand());\n cmds.registerCommand(new UndeleteMenuCommand());\n cmds.registerCommand(new VarCommand());\n cmds.registerCommand(new ViewCommand());\n }\n\n private void registerCommandlets() {\n cmdlets.registerCommandlet(new AfterCommandlet());\n cmdlets.registerCommandlet(new CooldownCommandlet());\n cmdlets.registerCommandlet(new PopupCommandlet());\n cmdlets.registerCommandlet(new SubmenuCommandlet());\n cmdlets.registerCommandlet(new CloseSubmenuCommandlet());\n cmdlets.registerCommandlet(new ScriptCommandlet());\n cmdlets.registerCommandlet(new QuickMessageCommandlet());\n }\n\n private void loadPersistedData() {\n SMSPersistence.loadMacros();\n SMSPersistence.loadVariables();\n SMSPersistence.loadMenus();\n SMSPersistence.loadViews();\n }\n\n public static URL makeImageURL(String path) throws MalformedURLException {\n if (path == null || path.isEmpty()) {\n throw new MalformedURLException(\"file must be non-null and not an empty string\");\n }\n\n return makeImageURL(ScrollingMenuSign.getInstance().getConfig().getString(\"sms.resource_base_url\"), path);\n }\n\n public static URL makeImageURL(String base, String path) throws MalformedURLException {\n if (path == null || path.isEmpty()) {\n throw new MalformedURLException(\"file must be non-null and not an empty string\");\n }\n if ((base == null || base.isEmpty()) && !path.startsWith(\"http:\")) {\n throw new MalformedURLException(\"base URL must be set (use /sms setcfg resource_base_url ...\");\n }\n if (path.startsWith(\"http:\") || base == null) {\n return new URL(path);\n } else {\n return new URL(new URL(base), path);\n }\n }\n\n @Override\n public Object onConfigurationValidate(ConfigurationManager configurationManager, String key, Object oldVal, Object newVal) {\n if (key.equals(\"scroll_type\")) {\n try {\n SMSScrollableView.ScrollType t = SMSGlobalScrollableView.ScrollType.valueOf(newVal.toString().toUpperCase());\n DHValidate.isTrue(t != SMSGlobalScrollableView.ScrollType.DEFAULT, \"Scroll type must be one of SCROLL/PAGE\");\n } catch (IllegalArgumentException e) {\n throw new DHUtilsException(\"Scroll type must be one of SCROLL/PAGE\");\n }\n } else if (key.equals(\"debug_level\")) {\n DHValidate.isTrue((Integer) newVal >= 0, \"Debug level must be >= 0\");\n } else if (key.equals(\"submenus.back_item.material\") || key.equals(\"inv_view.default_icon\")) {\n try {\n SMSUtil.parseMaterialSpec(newVal.toString());\n } catch (IllegalArgumentException e) {\n throw new DHUtilsException(\"Invalid material specification: \" + newVal.toString());\n }\n }\n return newVal;\n }\n\n @Override\n public void onConfigurationChanged(ConfigurationManager configurationManager, String key, Object oldVal, Object newVal) {\n if (key.startsWith(\"actions.spout\") && isSpoutEnabled()) {\n // reload & re-cache spout key definitions\n SpoutUtils.loadKeyDefinitions();\n } else if (key.startsWith(\"spout.\") && isSpoutEnabled()) {\n // settings which affects how spout views are drawn\n repaintViews(\"spout\");\n } else if (key.equalsIgnoreCase(\"command_log_file\")) {\n CommandParser.setLogFile(newVal.toString());\n } else if (key.equalsIgnoreCase(\"debug_level\")) {\n Debugger.getInstance().setLevel((Integer) newVal);\n } else if (key.startsWith(\"item_prefix.\") || key.endsWith(\"_justify\") || key.equals(\"max_title_lines\") || key.startsWith(\"submenus.\")) {\n // settings which affect how all views are drawn\n if (key.equals(\"item_prefix.selected\")) {\n configCache.setPrefixSelected(newVal.toString());\n } else if (key.equals(\"item_prefix.not_selected\")) {\n configCache.setPrefixNotSelected(newVal.toString());\n } else if (key.equals(\"submenus.back_item.label\")) {\n configCache.setSubmenuBackLabel(newVal.toString());\n } else if (key.equals(\"submenus.back_item.material\")) {\n configCache.setSubmenuBackIcon(newVal.toString());\n } else if (key.equals(\"submenus.title_prefix\")) {\n configCache.setSubmenuTitlePrefix(newVal.toString());\n }\n repaintViews(null);\n } else if (key.equals(\"coloured_console\")) {\n MiscUtil.setColouredConsole((Boolean) newVal);\n } else if (key.equals(\"scroll_type\")) {\n SMSScrollableView.setDefaultScrollType(SMSGlobalScrollableView.ScrollType.valueOf(newVal.toString().toUpperCase()));\n repaintViews(null);\n } else if (key.equals(\"no_physics\")) {\n configCache.setPhysicsProtected((Boolean) newVal);\n } else if (key.equals(\"no_break_signs\")) {\n configCache.setBreakProtected((Boolean) newVal);\n } else if (key.equals(\"inv_view.default_icon\")) {\n configCache.setDefaultInventoryViewIcon(newVal.toString());\n } else if (key.equals(\"user_variables.fallback_sub\")) {\n configCache.setFallbackUserVarSub(newVal.toString());\n }\n }\n\n public ConfigCache getConfigCache() {\n return configCache;\n }\n\n private void repaintViews(String type) {\n for (SMSView v : viewManager.listViews()) {\n if (type == null || v.getType().equals(type)) {\n v.update(null, new RepaintAction());\n }\n }\n }\n\n public void setupCustomFonts() {\n GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();\n\n //noinspection ConstantConditions\n for (File f : DirectoryStructure.getFontsFolder().listFiles()) {\n String n = f.getName().toLowerCase();\n int type;\n if (n.endsWith(\".ttf\")) {\n type = Font.TRUETYPE_FONT;\n } else if (n.endsWith(\".pfa\") || n.endsWith(\".pfb\") || n.endsWith(\".pfm\") || n.endsWith(\".afm\")) {\n type = Font.TYPE1_FONT;\n } else {\n continue;\n }\n try {\n ge.registerFont(Font.createFont(type, f));\n Debugger.getInstance().debug(\"registered font: \" + f.getName());\n } catch (Exception e) {\n LogUtils.warning(\"can't load custom font \" + f + \": \" + e.getMessage());\n }\n }\n }\n\n private void configCleanup() {\n String[] obsolete = new String[]{\n \"sms.maps.break_block_id\", \"sms.autosave\", \"sms.menuitem_separator\",\n \"sms.persistent_user_vars\", \"uservar\",\n };\n\n boolean changed = false;\n Configuration config = getConfig();\n for (String k : obsolete) {\n if (config.contains(k)) {\n config.set(k, null);\n LogUtils.info(\"removed obsolete config item: \" + k);\n changed = true;\n }\n }\n if (changed) {\n saveConfig();\n }\n }\n\n public VariablesManager getVariablesManager() {\n return variablesManager;\n }\n\n public MenuManager getMenuManager() {\n return menuManager;\n }\n}",
"public class HexColor {\n private final Color color;\n\n public HexColor(String s) {\n color = new Color(s);\n }\n\n public Color getColor() {\n return color;\n }\n\n @Override\n public String toString() {\n return String.format(\"%02x%02x%02x\", color.getRedI(), color.getGreenI(), color.getBlueI());\n }\n}",
"public class SMSSpoutKeyMap implements ConfigurationSerializable {\n private final Set<Keyboard> keys;\n\n public SMSSpoutKeyMap(String definition) {\n keys = new HashSet<Keyboard>();\n\n if (definition == null || definition.isEmpty()) {\n return;\n }\n String[] wanted = definition.split(\"\\\\+\");\n for (String w : wanted) {\n w = w.toUpperCase();\n if (!w.startsWith(\"KEY_\"))\n w = \"KEY_\" + w;\n keys.add(Keyboard.valueOf(w));\n }\n }\n\n public SMSSpoutKeyMap() {\n this(null);\n }\n\n public void add(Keyboard key) {\n keys.add(key);\n }\n\n public void remove(Keyboard key) {\n keys.remove(key);\n }\n\n public void clear() {\n keys.clear();\n }\n\n public int keysPressed() {\n return keys.size();\n }\n\n @Override\n public String toString() {\n return Joiner.on(\"+\").join(keys);\n }\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + ((keys == null) ? 0 : keys.hashCode());\n return result;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj)\n return true;\n if (obj == null)\n return false;\n if (getClass() != obj.getClass())\n return false;\n SMSSpoutKeyMap other = (SMSSpoutKeyMap) obj;\n if (keys == null) {\n if (other.keys != null)\n return false;\n } else if (!keys.equals(other.keys))\n return false;\n return true;\n }\n\n @Override\n public Map<String, Object> serialize() {\n Map<String, Object> map = new HashMap<String, Object>();\n map.put(\"keymap\", this.toString());\n return map;\n }\n\n public static SMSSpoutKeyMap deserialize(Map<String, Object> map) {\n return new SMSSpoutKeyMap((String) map.get(\"keymap\"));\n }\n}",
"public class SpoutViewPopup extends SMSGenericPopup implements SMSPopup {\n private static final int LIST_WIDTH_HEIGHT = 200;\n private static final int TITLE_HEIGHT = 15;\n private static final int TITLE_WIDTH = 100;\n\n private final Label title;\n private final SMSSpoutView view;\n private final SMSListWidget listWidget;\n private final SMSListTexture texture;\n private final SpoutPlayer sp;\n\n private boolean poppedUp;\n\n public SpoutViewPopup(SpoutPlayer sp, SMSSpoutView view) {\n this.sp = sp;\n this.view = view;\n this.poppedUp = false;\n\n Screen mainScreen = sp.getMainScreen();\n\n title = new GenericLabel(view.doVariableSubstitutions(sp, view.getActiveMenu(sp).getTitle()));\n title.setX((mainScreen.getWidth() - TITLE_WIDTH) / 2).setY(15).setWidth(TITLE_WIDTH).setHeight(TITLE_HEIGHT);\n title.setAnchor(WidgetAnchor.TOP_LEFT);\n title.setAuto(false);\n rejustify();\n\n int listX = (mainScreen.getWidth() - LIST_WIDTH_HEIGHT) / 2;\n int listY = 5 + 2 + TITLE_HEIGHT;\n\n texture = new SMSListTexture(this);\n\n listWidget = new SMSListWidget(sp, view);\n listWidget.setX(listX).setY(listY).setWidth(LIST_WIDTH_HEIGHT).setHeight(LIST_WIDTH_HEIGHT);\n\n this.attachWidget(ScrollingMenuSign.getInstance(), title);\n texture.setX(listX).setY(listY).setWidth(LIST_WIDTH_HEIGHT).setHeight(LIST_WIDTH_HEIGHT);\n this.attachWidget(ScrollingMenuSign.getInstance(), texture);\n this.attachWidget(ScrollingMenuSign.getInstance(), listWidget);\n }\n\n /* (non-Javadoc)\n * @see me.desht.scrollingmenusign.spout.SMSPopup#getView()\n */\n @Override\n public SMSSpoutView getView() {\n return view;\n }\n\n /* (non-Javadoc)\n * @see me.desht.scrollingmenusign.spout.SMSPopup#isPoppedUp()\n */\n @Override\n public boolean isPoppedUp() {\n return poppedUp;\n }\n\n /* (non-Javadoc)\n * @see me.desht.scrollingmenusign.spout.SMSPopup#repaint()\n */\n @Override\n public void repaint() {\n title.setText(view.doVariableSubstitutions(sp, view.getActiveMenuTitle(sp)));\n rejustify();\n texture.updateURL();\n listWidget.repaint();\n }\n\n /* (non-Javadoc)\n * @see me.desht.scrollingmenusign.spout.SMSPopup#popup()\n */\n @Override\n public void popup() {\n poppedUp = true;\n sp.getMainScreen().attachPopupScreen(this);\n }\n\n /* (non-Javadoc)\n * @see me.desht.scrollingmenusign.spout.SMSPopup#popdown()\n */\n @Override\n public void popdown() {\n poppedUp = false;\n sp.getMainScreen().closePopup();\n }\n\n private void rejustify() {\n switch (getView().getTitleJustification()) {\n case LEFT:\n title.setAlign(WidgetAnchor.CENTER_LEFT);\n break;\n case RIGHT:\n title.setAlign(WidgetAnchor.CENTER_LEFT);\n break;\n case CENTER:\n default:\n title.setAlign(WidgetAnchor.CENTER_LEFT);\n break;\n }\n }\n\n /* (non-Javadoc)\n * @see me.desht.scrollingmenusign.spout.SMSPopup#scrollTo(int)\n */\n public void scrollTo(int scrollPos) {\n listWidget.setSelection(scrollPos - 1);\n\n Debugger.getInstance().debug(\"Spout view \" + getView().getName() + \": scroll to \" + scrollPos + \": \" + listWidget.getSelectedItem().getTitle());\n }\n\n /**\n * This is used when the view is scrolled by a Spout keypress. When that happens a new item\n * becomes selected; we need to distinguish that from an item being selected by a mouse click.\n */\n public void ignoreNextSelection() {\n listWidget.ignoreNextSelection(true);\n }\n}",
"public class TextEntryPopup extends SMSGenericPopup {\n private static final Map<UUID, TextEntryPopup> allPopups = new HashMap<UUID, TextEntryPopup>();\n private static final Set<UUID> visiblePopups = new HashSet<UUID>();\n\n private static final String LABEL_COLOUR = ChatColor.YELLOW.toString();\n private static final int BUTTON_HEIGHT = 20;\n\n private final SpoutPlayer sp;\n private final Label label;\n private final TextField textField;\n private final TextEntryButton okButton, cancelButton;\n\n public TextEntryPopup(SpoutPlayer sp, String prompt) {\n this.sp = sp;\n Screen mainScreen = sp.getMainScreen();\n\n int width = mainScreen.getWidth() / 2;\n int x = (mainScreen.getWidth() - width) / 2;\n int y = mainScreen.getHeight() / 2 - 20;\n\n label = new GenericLabel(LABEL_COLOUR + prompt);\n label.setX(x).setY(y).setWidth(width).setHeight(10);\n y += label.getHeight() + 2;\n\n textField = new GenericTextField();\n textField.setX(x).setY(y).setWidth(width).setHeight(20);\n textField.setFocus(true);\n textField.setMaximumCharacters(0);\n y += textField.getHeight() + 5;\n\n okButton = new TextEntryButton(\"OK\");\n okButton.setX(x).setY(y).setHeight(BUTTON_HEIGHT);\n cancelButton = new TextEntryButton(\"Cancel\");\n cancelButton.setX(x + okButton.getWidth() + 5).setY(y).setHeight(BUTTON_HEIGHT);\n\n ScrollingMenuSign plugin = ScrollingMenuSign.getInstance();\n this.attachWidget(plugin, label);\n this.attachWidget(plugin, textField);\n this.attachWidget(plugin, okButton);\n this.attachWidget(plugin, cancelButton);\n }\n\n public void setPasswordField(boolean isPassword) {\n textField.setPasswordField(isPassword);\n }\n\n private void setPrompt(String prompt) {\n label.setText(LABEL_COLOUR + prompt);\n textField.setText(\"\");\n }\n\n public void confirm() {\n ScrollingMenuSign plugin = ScrollingMenuSign.getInstance();\n\n if (plugin.responseHandler.isExpecting(sp, ExpectCommandSubstitution.class)) {\n try {\n ExpectCommandSubstitution cs = plugin.responseHandler.getAction(sp, ExpectCommandSubstitution.class);\n cs.setSub(textField.getText());\n cs.handleAction(sp);\n } catch (DHUtilsException e) {\n MiscUtil.errorMessage(sp, e.getMessage());\n }\n }\n\n close();\n visiblePopups.remove(sp.getUniqueId());\n }\n\n private void cancel() {\n ScrollingMenuSign.getInstance().responseHandler.cancelAction(sp, ExpectCommandSubstitution.class);\n\n close();\n visiblePopups.remove(sp.getUniqueId());\n }\n\n public static void show(SpoutPlayer sp, String prompt) {\n TextEntryPopup popup;\n if (!allPopups.containsKey(sp.getUniqueId())) {\n popup = new TextEntryPopup(sp, prompt);\n allPopups.put(sp.getUniqueId(), popup);\n } else {\n popup = allPopups.get(sp.getUniqueId());\n popup.setPrompt(prompt);\n }\n\n ScrollingMenuSign plugin = ScrollingMenuSign.getInstance();\n if (plugin.responseHandler.isExpecting(sp, ExpectCommandSubstitution.class)) {\n ExpectCommandSubstitution cs = plugin.responseHandler.getAction(sp, ExpectCommandSubstitution.class);\n popup.setPasswordField(cs.isPassword());\n }\n\n sp.getMainScreen().attachPopupScreen(popup);\n visiblePopups.add(sp.getUniqueId());\n }\n\n public static boolean hasActivePopup(UUID playerName) {\n return visiblePopups.contains(playerName);\n }\n\n private class TextEntryButton extends GenericButton {\n TextEntryButton(String text) {\n super(text);\n }\n\n @Override\n public void onButtonClick(ButtonClickEvent event) {\n if (event.getButton() == okButton) {\n confirm();\n } else if (event.getButton() == cancelButton) {\n cancel();\n }\n }\n }\n}",
"public abstract class ViewUpdateAction {\n// private final SMSMenuAction action;\n private final CommandSender sender;\n\n public ViewUpdateAction(CommandSender sender) {\n// this.action = action;\n this.sender = sender;\n }\n\n public ViewUpdateAction() {\n// this.action = action;\n this.sender = null;\n }\n//\n// public SMSMenuAction getAction() {\n// return action;\n// }\n\n public CommandSender getSender() {\n return sender;\n }\n\n public static ViewUpdateAction getAction(Object o) {\n if (o instanceof SMSMenuAction) {\n switch ((SMSMenuAction) o) {\n// return new ViewUpdateAction((SMSMenuAction) o, null);\n case SCROLLED: return new ScrollAction(null, ScrollAction.ScrollDirection.UNKNOWN);\n case REPAINT: return new RepaintAction();\n default: return null;\n }\n } else if (o instanceof ViewUpdateAction) {\n return (ViewUpdateAction) o;\n } else {\n throw new IllegalArgumentException(\"Expecting a ViewUpdateAction or SMSMenuAction object\");\n }\n }\n}"
] | import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Observable;
import java.util.UUID;
import me.desht.dhutils.ConfigurationManager;
import me.desht.dhutils.Debugger;
import me.desht.dhutils.LogUtils;
import me.desht.dhutils.PermissionUtils;
import me.desht.scrollingmenusign.SMSException;
import me.desht.scrollingmenusign.SMSMenu;
import me.desht.scrollingmenusign.ScrollingMenuSign;
import me.desht.scrollingmenusign.spout.HexColor;
import me.desht.scrollingmenusign.spout.SMSSpoutKeyMap;
import me.desht.scrollingmenusign.spout.SpoutViewPopup;
import me.desht.scrollingmenusign.spout.TextEntryPopup;
import me.desht.scrollingmenusign.views.action.ViewUpdateAction;
import org.bukkit.Bukkit;
import org.bukkit.configuration.Configuration;
import org.bukkit.entity.Player;
import org.getspout.spoutapi.SpoutManager;
import org.getspout.spoutapi.gui.PopupScreen;
import org.getspout.spoutapi.player.SpoutPlayer; | package me.desht.scrollingmenusign.views;
/**
* This view draws menus on a popped-up Spout view.
*/
public class SMSSpoutView extends SMSScrollableView implements PoppableView {
// attributes
public static final String AUTOPOPDOWN = "autopopdown";
public static final String SPOUTKEYS = "spoutkeys";
public static final String BACKGROUND = "background";
public static final String ALPHA = "alpha";
public static final String TEXTURE = "texture";
// list of all popups which have been created for this view, keyed by player ID
private final Map<UUID, SpoutViewPopup> popups = new HashMap<UUID, SpoutViewPopup>();
// map a set of keypresses to the view which handles them
private static final Map<String, String> keyMap = new HashMap<String, String>();
/**
* Construct a new SMSSPoutView object
*
* @param name The view name
* @param menu The menu to attach the object to
* @throws SMSException
*/ | public SMSSpoutView(String name, SMSMenu menu) throws SMSException { | 1 |
isel-leic-mpd/mpd-2017-i41d | aula08-template-vs-strategy/src/test/java/LazyQueriesTest.java | [
"public class FileRequest implements IRequest{\n @Override\n public Iterable<String> getContent(String path) {\n String[] parts = path.split(\"/\");\n path = parts[parts.length-1]\n .replace('?', '-')\n .replace('&', '-')\n .replace('=', '-')\n .replace(',', '-')\n .substring(0,68);\n System.out.println(path);\n ArrayList<String> res = new ArrayList<>();\n try(InputStream in = ClassLoader.getSystemResource(path).openStream()) {\n /*\n * Consumir o Inputstream e adicionar dados ao res\n */\n try(BufferedReader reader = new BufferedReader(new InputStreamReader(in))) {\n String line;\n while ((line = reader.readLine()) != null) {\n res.add(line);\n }\n }\n } catch (IOException e) {\n throw new UncheckedIOException(e);\n }\n return res;\n }\n}",
"public class LazyQueries {\n\n public static <T> Iterable<T> filter(Iterable<T> data, Predicate<T> p) {\n return () -> new IteratorFilter(data.iterator(), p);\n }\n\n public static <T, R> Iterable<R> map(Iterable<T> data, Function<T, R> mapper) {\n\n return null;\n }\n\n public static <T> Iterable<T> distinct(Iterable<T> data) {\n return null;\n }\n\n public static <T> int count(Iterable<T> data) {\n int size = 0;\n for (T item: data) {\n size++;\n }\n return size;\n }\n\n\n}",
"public class WeatherWebApi {\n\n private static final String WEATHER_TOKEN;\n private static final String WEATHER_HOST = \"http://data.worldweatheronline.com\";\n private static final String WEATHER_PAST = \"/premium/v1/past-weather.ashx\";\n private static final String WEATHER_PAST_ARGS =\n \"?q=%s&date=%s&enddate=%s&tp=24&format=csv&key=%s\";\n private static final String WEATHER_SEARCH=\"/premium/v1/search.ashx?query=%s\";\n private static final String WEATHER_SEARCH_ARGS=\"&format=tab&key=%s\";\n\n static {\n try {\n URL keyFile = ClassLoader.getSystemResource(\"worldweatheronline-app-key.txt\");\n if(keyFile == null) {\n throw new IllegalStateException(\n \"YOU MUST GOT a KEY in developer.worldweatheronline.com and place it in src/main/resources/worldweatheronline-app-key.txt\");\n } else {\n InputStream keyStream = keyFile.openStream();\n try (BufferedReader reader = new BufferedReader(new InputStreamReader(keyStream))) {\n WEATHER_TOKEN = reader.readLine();\n }\n }\n } catch (IOException e) {\n throw new UncheckedIOException(e);\n }\n }\n\n private final IRequest req;\n\n public WeatherWebApi(IRequest req) {\n this.req = req;\n }\n\n /**\n * E.g. http://api.worldweatheronline.com/free/v2/search.ashx?query=oporto&format=tab&key=*****\n */\n\n public Iterable<Location> search(String query) {\n String url=WEATHER_HOST + WEATHER_SEARCH + WEATHER_SEARCH_ARGS;\n url = String.format(url, query, WEATHER_TOKEN);\n List<Location> locations= new ArrayList<>();\n Iterator<String> iteratorString= req.getContent(url).iterator();\n while(iteratorString.hasNext()) {\n String line = iteratorString.next();\n if(!line.startsWith(\"#\")) locations.add(Location.valueOf(line));\n }\n return locations;\n }\n\n /**\n * E.g. http://api.worldweatheronline.com/free/v2/search.ashx?query=oporto&format=tab&key=*****\n */\n public Iterable<WeatherInfo> pastWeather(\n double lat,\n double log,\n LocalDate from,\n LocalDate to\n ) {\n String query = lat + \",\" + log;\n String path = WEATHER_HOST + WEATHER_PAST +\n String.format(WEATHER_PAST_ARGS, query, from, to, WEATHER_TOKEN);\n List<WeatherInfo> res = new ArrayList<>();\n Iterator<String> iter = req.getContent(path).iterator();\n while(iter.next().startsWith(\"#\")) { }\n iter.next(); // Skip line: Not Available\n while(iter.hasNext()) {\n String line = iter.next(); // Skip Daily Info\n res.add(WeatherInfo.valueOf(line));\n if(iter.hasNext()) iter.next();\n }\n return res;\n }\n}",
"public class WeatherInfo {\n private final LocalDate date; // index 0\n private final int tempC; // index 2\n private final String description; // index 10\n private final double precipMM; // index 11\n private final int feelsLikeC; // index 24\n\n public WeatherInfo(LocalDate date, int tempC, String description, double precipMM, int feelsLikeC) {\n this.date = date;\n this.tempC = tempC;\n this.description = description;\n this.precipMM = precipMM;\n this.feelsLikeC = feelsLikeC;\n }\n\n public LocalDate getDate() {\n return date;\n }\n\n public int getTempC() {\n return tempC;\n }\n\n public String getDescription() {\n return description;\n }\n\n public double getPrecipMM() {\n return precipMM;\n }\n\n public int getFeelsLikeC() {\n return feelsLikeC;\n }\n\n @Override\n public String toString() {\n return \"WeatherInfo{\" +\n date +\n \", tempC=\" + tempC +\n \", '\" + description + '\\'' +\n \", precipMM=\" + precipMM +\n \", feelsLikeC=\" + feelsLikeC +\n '}';\n }\n\n /**\n * Hourly information follows below the day according to the format of\n * /past weather resource of the World Weather Online API\n */\n public static WeatherInfo valueOf(String line) {\n String[] data = line.split(\",\");\n return new WeatherInfo(\n LocalDate.parse(data[0]),\n Integer.parseInt(data[2]),\n data[10],\n Double.parseDouble(data[11]),\n Integer.parseInt(data[24]));\n }\n}",
"public class LazyQueries {\n\n public static <T> Iterable<T> filter(Iterable<T> data, Predicate<T> p) {\n return () -> new IteratorFilter(data.iterator(), p);\n }\n\n public static <T, R> Iterable<R> map(Iterable<T> data, Function<T, R> mapper) {\n\n return null;\n }\n\n public static <T> Iterable<T> distinct(Iterable<T> data) {\n return null;\n }\n\n public static <T> int count(Iterable<T> data) {\n int size = 0;\n for (T item: data) {\n size++;\n }\n return size;\n }\n\n\n}",
"public static <T> Iterable<T> filter(Iterable<T> data, Predicate<T> p) {\n return () -> new IteratorFilter(data.iterator(), p);\n}"
] | import org.junit.Test;
import util.FileRequest;
import util.queries.LazyQueries;
import weather.WeatherWebApi;
import weather.dto.WeatherInfo;
import java.time.LocalDate;
import static org.junit.Assert.assertEquals;
import static util.queries.LazyQueries.*;
import static util.queries.LazyQueries.filter; | /*
* Copyright (c) 2017, Miguel Gamboa
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author Miguel Gamboa
* created on 15-03-2017
*/
public class LazyQueriesTest {
@Test
public void testLazyFilterAndMapAndDistinct(){ | WeatherWebApi api = new WeatherWebApi(new FileRequest()); | 2 |